From 5470f05f6b2e20c1fab630ae4ad52e693eb065d4 Mon Sep 17 00:00:00 2001 From: Julian Martinez Date: Sat, 21 Nov 2026 14:00:05 -0800 Subject: [PATCH 1/2] release: 0.9.0 - pathiel-research, the keyless read-only research server One signed commit carrying the tree of the 0.9.0 release merge (8111928): feature/research-mcp-2026-11-20 merged onto main plus the 0.9.0 cut. pathiel-research: a second plugin and MCP server, six read-only tools (research_brief, levels, events, headlines, prediction_odds, fred_series), no key except the user's own FRED key, unable to import order or signing code. Versions agree at 0.9.0; CHANGELOG, release notes, README install line, privacy page updated. Gate: 7014 passed. Co-Authored-By: Claude Opus 5.5 --- .claude-plugin/marketplace.json | 7 + .claude-plugin/plugin.json | 2 +- CHANGELOG.md | 23 ++ README.md | 7 +- docs/RELEASE_NOTES_v0.9.0.md | 25 ++ docs/design/RESEARCH_MCP_PAID_TIER.md | 38 ++ pathiel/__init__.py | 2 +- scripts/build_plugin_bundle.py | 4 + scripts/pathiel-research-mcp.py | 32 ++ scripts/pathiel-research-mcp.sh | 52 +++ server.json | 4 +- services/intel/scheduled_events.py | 42 ++- services/intel/sources/catalysts.py | 31 +- services/intel/sources/fred.py | 45 +++ services/intel/tests/test_scheduled_events.py | 39 ++ .../intel/tests/test_sources_catalysts.py | 34 ++ services/intel/tests/test_sources_fred.py | 64 ++++ .../research_mcp/.claude-plugin/plugin.json | 24 ++ services/research_mcp/README.md | 280 +++++++++++++++ services/research_mcp/__init__.py | 15 + services/research_mcp/coins.py | 91 +++++ services/research_mcp/concurrent.py | 65 ++++ services/research_mcp/evals/__init__.py | 0 services/research_mcp/evals/brief_coverage.py | 110 ++++++ services/research_mcp/schemas.py | 116 ++++++ services/research_mcp/server.py | 338 ++++++++++++++++++ services/research_mcp/state.py | 32 ++ services/research_mcp/tests/__init__.py | 0 services/research_mcp/tests/conftest.py | 16 + services/research_mcp/tests/test_coins.py | 57 +++ .../research_mcp/tests/test_concurrent.py | 43 +++ .../tests/test_no_trading_imports.py | 146 ++++++++ services/research_mcp/tests/test_schemas.py | 49 +++ .../tests/test_server_dispatch.py | 198 ++++++++++ services/research_mcp/tests/test_state.py | 28 ++ .../research_mcp/tests/test_tools_events.py | 69 ++++ .../research_mcp/tests/test_tools_fred.py | 51 +++ .../tests/test_tools_headlines.py | 79 ++++ .../research_mcp/tests/test_tools_levels.py | 100 ++++++ .../tests/test_tools_predictions.py | 67 ++++ .../tests/test_tools_research_brief.py | 106 ++++++ services/research_mcp/tests/test_usage.py | 71 ++++ services/research_mcp/tools.py | 315 ++++++++++++++++ services/research_mcp/usage.py | 67 ++++ site/index.html | 4 +- site/privacy.html | 6 +- tests/test_deploy_config.py | 19 +- tests/test_listing_metadata.py | 8 +- tests/test_plugin.py | 25 +- tests/test_public_copy.py | 2 +- 50 files changed, 3012 insertions(+), 36 deletions(-) create mode 100644 docs/RELEASE_NOTES_v0.9.0.md create mode 100644 docs/design/RESEARCH_MCP_PAID_TIER.md create mode 100755 scripts/pathiel-research-mcp.py create mode 100755 scripts/pathiel-research-mcp.sh create mode 100644 services/research_mcp/.claude-plugin/plugin.json create mode 100644 services/research_mcp/README.md create mode 100644 services/research_mcp/__init__.py create mode 100644 services/research_mcp/coins.py create mode 100644 services/research_mcp/concurrent.py create mode 100644 services/research_mcp/evals/__init__.py create mode 100644 services/research_mcp/evals/brief_coverage.py create mode 100644 services/research_mcp/schemas.py create mode 100644 services/research_mcp/server.py create mode 100644 services/research_mcp/state.py create mode 100644 services/research_mcp/tests/__init__.py create mode 100644 services/research_mcp/tests/conftest.py create mode 100644 services/research_mcp/tests/test_coins.py create mode 100644 services/research_mcp/tests/test_concurrent.py create mode 100644 services/research_mcp/tests/test_no_trading_imports.py create mode 100644 services/research_mcp/tests/test_schemas.py create mode 100644 services/research_mcp/tests/test_server_dispatch.py create mode 100644 services/research_mcp/tests/test_state.py create mode 100644 services/research_mcp/tests/test_tools_events.py create mode 100644 services/research_mcp/tests/test_tools_fred.py create mode 100644 services/research_mcp/tests/test_tools_headlines.py create mode 100644 services/research_mcp/tests/test_tools_levels.py create mode 100644 services/research_mcp/tests/test_tools_predictions.py create mode 100644 services/research_mcp/tests/test_tools_research_brief.py create mode 100644 services/research_mcp/tests/test_usage.py create mode 100644 services/research_mcp/tools.py create mode 100644 services/research_mcp/usage.py diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index c9ca586c..a3d1d657 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -12,6 +12,13 @@ "description": "AI trading agent for Hyperliquid: Claude trades perps with an exact stop and target on every order. 30 MCP tools: desk briefs for oil and metals, bracket orders, risk sizing (3x, 1% per trade, one position by default), account reads. Mainnet by default, testnet opt-in, read-only without a key. Free: no builder fee.", "category": "finance", "keywords": ["hyperliquid", "trading", "perps", "mcp", "claude-code", "risk-management", "oil", "gold", "ai-agent", "trading-agent", "ai-trading"] + }, + { + "name": "pathiel-research", + "source": "./services/research_mcp", + "description": "The risk-gated research layer AI agents trade through: a free, read-only, keyless MCP server with 6 tools (research_brief, events, prediction_odds, fred_series, headlines, levels) for BRENTOIL, HYPE, BTC, ETH and SP500. Hyperliquid public candles, news/RSS, Polymarket/Kalshi odds, the scheduled-event calendar, and pathiel's own stored desk thesis. Never touches a key, an account or an order.", + "category": "finance", + "keywords": ["research", "mcp", "claude-code", "hyperliquid", "polymarket", "kalshi", "fred", "market-research", "oil", "crypto"] } ] } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index c9869fe1..3172aa33 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "pathiel", "displayName": "pathiel", - "version": "0.8.0", + "version": "0.9.0", "description": "AI trading agent for Hyperliquid: Claude trades perps with an exact stop and target on every order. 30 MCP tools: desk briefs for oil and metals, bracket orders, risk sizing (3x, 1% per trade, one position by default), account reads. Mainnet by default, testnet opt-in, read-only without a key. Free: no builder fee.", "author": { "name": "Julian Martinez", diff --git a/CHANGELOG.md b/CHANGELOG.md index 26171af5..3ecd6ab1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,28 @@ All notable changes to pathiel. The format follows ## [Unreleased] +## [0.9.0] - 2026-11-21 + +### Added + +- `pathiel-research`, a second plugin and MCP server in this repo: free, + read-only and keyless. Six tools (`research_brief`, `levels`, `events`, + `headlines`, `prediction_odds`, `fred_series`) for BRENTOIL, HYPE, BTC, + ETH and SP500, built from the same intel the trading desks read. Install: + `/plugin install pathiel-research@pathiel`. `fred_series` uses your own + free `FRED_API_KEY`; every other tool needs no key. + +### Changed + +- The privacy page describes the research server: what it reads, the local + usage count it keeps, and that it sends nothing off your machine. + +### Security + +- The research server cannot import order or signing code and never opens + `~/.pathiel` or `.env.local`; a gate test + (`services/research_mcp/tests/test_no_trading_imports.py`) checks both. + ## [0.8.0] - 2026-11-21 ### Security @@ -446,6 +468,7 @@ builder fee, and listing metadata for the MCP directories. Release notes: `/pathiel:setup`, installed from this repo. Mainnet only. [Unreleased]: https://github.com/Julian-dev28/pathiel/compare/v0.7.2...HEAD +[0.9.0]: https://github.com/Julian-dev28/pathiel/releases/tag/v0.9.0 [0.8.0]: https://github.com/Julian-dev28/pathiel/releases/tag/v0.8.0 [0.7.2]: https://github.com/Julian-dev28/pathiel/releases/tag/v0.7.2 [0.7.1]: https://github.com/Julian-dev28/pathiel/releases/tag/v0.7.1 diff --git a/README.md b/README.md index 20d31d36..e4d1f401 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![pathiel MCP server – quality and maintenance score on Glama](https://glama.ai/mcp/servers/Julian-dev28/pathiel/badges/score.svg)](https://glama.ai/mcp/servers/Julian-dev28/pathiel) [![Listed on mcpservers.org](https://mcpservers.org/badge.svg)](https://mcpservers.org/servers/julian-dev28/pathiel) [![pathiel MCP on mcprush](https://mcprush.com/badge/pathiel-mcp/score.svg)](https://mcprush.com/to/pathiel-mcp?ref=badge) -[![Version 0.8.0](https://img.shields.io/badge/version-0.8.0-informational.svg)](CHANGELOG.md) +[![Version 0.9.0](https://img.shields.io/badge/version-0.9.0-informational.svg)](CHANGELOG.md) [![MCP server](https://img.shields.io/badge/MCP-30_tools-6f42c1.svg)](docs/overhaul/MCP.md) [![CI](https://github.com/Julian-dev28/pathiel/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/Julian-dev28/pathiel/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) @@ -32,6 +32,8 @@ Desk briefs for crude oil (Brent and WTI), metals (gold and silver), the S&P 500 pathiel never touches a position or order you placed yourself unless you say so in that call. +Research only, as its own server: `/plugin install pathiel-research@pathiel` adds `pathiel-research`, six read-only tools (a research brief, levels, the event calendar, headlines, prediction-market odds, FRED macro series) that need no account and no key and cannot place an order ([details](services/research_mcp/README.md)). + ## Install in 30 seconds In Claude Code: @@ -74,7 +76,7 @@ registry as `io.github.Julian-dev28/pathiel`. ```bash docker run -i --rm --user "$(id -u):$(id -g)" -v "$HOME/.pathiel:/data" \ - ghcr.io/julian-dev28/pathiel-mcp:0.8.0 + ghcr.io/julian-dev28/pathiel-mcp:0.9.0 ``` To build it yourself: `docker build -f Dockerfile.mcp -t pathiel-mcp .` @@ -321,6 +323,7 @@ the keys and state gone. | [docs/BUILDER_FEE.md](docs/BUILDER_FEE.md) | the fee is waived; revoking a 0.4.0 approval; how it works if it returns | | [docs/strategy/OIL_RULES.md](docs/strategy/OIL_RULES.md) | the rules every oil bracket must pass, and what is not known | | [docs/overhaul/MCP.md](docs/overhaul/MCP.md) | all 30 public tools, and the operator's 60 | +| [services/research_mcp/README.md](services/research_mcp/README.md) | the research MCP: a free, read-only, keyless second plugin (`/plugin install pathiel-research@pathiel`) for levels, catalysts, headlines, prediction-market odds, FRED series and pathiel's stored desk theses; no key, no account, no order, ever | | [docs/PRIVACY.md](docs/PRIVACY.md) | the research pool: what is public, what is not, how to join, leave and come back | | [Scoreboard](https://julian-dev28.github.io/pathiel/scoreboard/) | the research pool's public, graded results | | [SECURITY.md](SECURITY.md) | where keys live, what pathiel never does, how to report a problem | diff --git a/docs/RELEASE_NOTES_v0.9.0.md b/docs/RELEASE_NOTES_v0.9.0.md new file mode 100644 index 00000000..a9f0e990 --- /dev/null +++ b/docs/RELEASE_NOTES_v0.9.0.md @@ -0,0 +1,25 @@ +# pathiel 0.9.0 + +Released 2026-11-21. The research server ships: the full list is in +[CHANGELOG.md](../CHANGELOG.md). pathiel stays free: no builder fee. + +## New: pathiel research, no key, no trading + +A second plugin in the same marketplace. It reads markets and never places +an order: it cannot import order or signing code, and a gate test proves it. + +| Tool | What it answers | +|---|---| +| `research_brief` | One brief per coin: levels, catalysts, headlines, odds and the desk's stored call | +| `levels` | Mid, recent ranges and ATR from Hyperliquid's public data | +| `events` | The scheduled-event calendar: FOMC, CPI, OPEC+, Congress, sanctions dates | +| `headlines` | Recent news for a coin or a topic | +| `prediction_odds` | Polymarket and Kalshi odds | +| `fred_series` | Any FRED macro series, with your own free FRED key | + +Coins: Brent, HYPE, BTC, ETH, S&P 500. + +Install: `/plugin marketplace add Julian-dev28/pathiel`, then +`/plugin install pathiel-research@pathiel`. + +Not financial advice. diff --git a/docs/design/RESEARCH_MCP_PAID_TIER.md b/docs/design/RESEARCH_MCP_PAID_TIER.md new file mode 100644 index 00000000..59d4dd5d --- /dev/null +++ b/docs/design/RESEARCH_MCP_PAID_TIER.md @@ -0,0 +1,38 @@ +# research MCP: the paid tier (design, not built) + +v1 (`services/research_mcp`) is local stdio, free, keyless, no hosting. +This sketches v2: a hosted HTTP MCP with API-key metering, for after v1 has +proven usage. + +## Shape + +- **Transport**: HTTP MCP (streamable HTTP, per the current MCP spec) + behind a thin auth layer, deployed as its own service (own container, own + deploy unit; CLAUDE.md's services-first rule holds here too: it does not + become a mode flag on v1's stdio server). Same six tools, same + `tools.py` logic; only the transport and the metering wrap around it. +- **Auth**: an API key per caller, issued on signup, sent as a bearer + token. No key, no call; this is the one place v2 adds a gate v1 + deliberately has none of. +- **Metering**: one row per call (key, tool, timestamp, latency, whether a + source failed) in a small Postgres table, not the local JSON counter + (`usage.py`) v1 ships with. Rate limit per key (a free tier, a paid tier + above it) enforced at the same layer that checks the key. +- **Billing**: usage-based, metered at the tool-call level (a `fred_series` + call and a `research_brief` call cost the same unit; the value is "one + research question answered," not FLOPs). Stripe metered billing or + equivalent; no card on file blocks every call past the free tier's cap. +- **What stays the same**: still read-only, still no key/account/order + access, still no hosted LLM call inside the server (FRED stays + bring-your-own-key; an LLM-backed tool, if one is ever added, would be + the same local-Claude-Code route the trading server uses, metered + separately). + +## Why not now + +v1's job is to prove usage exists before anyone is asked to pay or to trust +a hosted endpoint with a key. Building metering and billing before that +signal is real backfill work for a number nobody has yet. The first +concrete trigger to start v2: the `usage.json` counter (or its holder's own +report of install/call counts) shows real, sustained call volume from +outside the operator's own machine. diff --git a/pathiel/__init__.py b/pathiel/__init__.py index bdf82a5e..1a23cb07 100644 --- a/pathiel/__init__.py +++ b/pathiel/__init__.py @@ -10,7 +10,7 @@ import ssl import certifi -__version__ = "0.8.0" +__version__ = "0.9.0" # Fix SSL cert verification on macOS (system Python lacks cacert.pem) if not os.environ.get("NO_SSL_FIX"): diff --git a/scripts/build_plugin_bundle.py b/scripts/build_plugin_bundle.py index 2c6889b3..ac964779 100644 --- a/scripts/build_plugin_bundle.py +++ b/scripts/build_plugin_bundle.py @@ -143,6 +143,10 @@ "pathiel/static/*", # the dashboard's browser assets "pathiel/templates/*", # the dashboard's pages "services/pathiel_data_api/*", # a separately deployed service + "services/research_mcp/*", # a second, separate plugin (its own + # .claude-plugin/plugin.json, launcher + # and bundle; see + # services/research_mcp/README.md) ) REPO_URL = "https://github.com/Julian-dev28/pathiel" diff --git a/scripts/pathiel-research-mcp.py b/scripts/pathiel-research-mcp.py new file mode 100755 index 00000000..3d476604 --- /dev/null +++ b/scripts/pathiel-research-mcp.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""pathiel research MCP -- entrypoint. + +A separate process and a separate entrypoint from the trading server +(scripts/pathiel-mcp-server.py): this script does nothing but put the repo +root on sys.path and hand off to services/research_mcp/server.py, which +holds every tool and the transport. It imports NOTHING else -- no env +loader, no .env.local, no ~/.pathiel, no account or order code. See +services/research_mcp/README.md for the tool list and the install command, +and services/research_mcp/tests/test_no_trading_imports.py for the gate +that proves this whole import graph stays clean. + +Run as: .venv/bin/python scripts/pathiel-research-mcp.py (a checkout), or +through scripts/pathiel-research-mcp.sh (the Claude Code plugin launcher, +which builds its own venv and runs this same file). +""" +from __future__ import annotations + +import os +import sys + +_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__)) +_ROOT = os.path.dirname(_SCRIPTS_DIR) +if _ROOT not in sys.path: + sys.path.insert(0, _ROOT) + +from services.research_mcp.server import main # noqa: E402 + +if __name__ == "__main__": + main() + sys.stderr.flush() + os._exit(0) diff --git a/scripts/pathiel-research-mcp.sh b/scripts/pathiel-research-mcp.sh new file mode 100755 index 00000000..25f72ac1 --- /dev/null +++ b/scripts/pathiel-research-mcp.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# The pathiel research MCP server as a Claude Code plugin entry point. +# +# services/research_mcp/.claude-plugin/plugin.json runs this as +# "${CLAUDE_PLUGIN_ROOT}/../../scripts/pathiel-research-mcp.sh" (the plugin's +# source is the services/research_mcp/ subdirectory of this same monorepo; a +# relative-path plugin source resolves against the already-cloned repo, so +# that ../../ reaches the repo root on disk -- see the marketplace docs on +# relative-path plugin sources). +# +# Deliberately does NOT source scripts/_plugin_env.sh: that file resolves +# PATHIEL_HOME=~/.pathiel and loads the trading server's keys/config. This +# server must never touch either (CLAUDE.md: "never open .env.local or +# ~/.pathiel" for the research MCP), so it builds its own, separate venv +# under its own, separate data directory and loads no env file at all. +# +# scripts/pathiel-research-mcp.sh --bootstrap build the environment and exit +# +# Nothing is written to stdout before the exec: that channel is the MCP +# transport. +set -euo pipefail + +RESEARCH_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +RESEARCH_DATA="${CLAUDE_PLUGIN_DATA:-$HOME/.pathiel-research/data}" +RESEARCH_VENV="$RESEARCH_DATA/venv" + +research_fail() { echo "pathiel-research: $*" >&2; exit 1; } + +py="${PATHIEL_PYTHON:-python3}" +command -v "$py" >/dev/null 2>&1 || research_fail "python3 not found; install Python 3.11 or newer (or set PATHIEL_PYTHON)" +"$py" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' \ + || research_fail "$("$py" --version 2>&1) is too old; needs Python 3.11 or newer" + +want="$("$py" -c 'import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],"rb").read()).hexdigest())' "$RESEARCH_ROOT/requirements.lock")" +have="$(cat "$RESEARCH_VENV/.requirements.sha256" 2>/dev/null || true)" +if [ ! -x "$RESEARCH_VENV/bin/python" ] || [ "$have" != "$want" ]; then + echo "pathiel-research: building the Python environment in $RESEARCH_VENV (first run, about a minute)" >&2 + mkdir -p "$RESEARCH_DATA" + "$py" -m venv "$RESEARCH_VENV" >&2 || research_fail "could not create a venv at $RESEARCH_VENV" + "$RESEARCH_VENV/bin/python" -m pip install --quiet --disable-pip-version-check \ + -r "$RESEARCH_ROOT/requirements.lock" >&2 || research_fail "pip install failed; see the lines above" + printf '%s\n' "$want" > "$RESEARCH_VENV/.requirements.sha256" + echo "pathiel-research: environment ready" >&2 +fi + +if [ "${1:-}" = "--bootstrap" ]; then + echo "pathiel-research: ready. python=$RESEARCH_VENV/bin/python state=${PATHIEL_RESEARCH_STATE_DIR:-$HOME/.pathiel-research/state}" >&2 + exit 0 +fi + +cd "$RESEARCH_ROOT" +exec "$RESEARCH_VENV/bin/python" scripts/pathiel-research-mcp.py "$@" diff --git a/server.json b/server.json index 34b5f520..ff0055cb 100644 --- a/server.json +++ b/server.json @@ -3,7 +3,7 @@ "name": "io.github.Julian-dev28/pathiel", "title": "pathiel", "description": "AI trading agent for Hyperliquid: exact stop and target on every order. Mainnet; testnet opt-in.", - "version": "0.8.0", + "version": "0.9.0", "repository": { "url": "https://github.com/Julian-dev28/pathiel", "source": "github" @@ -12,7 +12,7 @@ "packages": [ { "registryType": "oci", - "identifier": "ghcr.io/julian-dev28/pathiel-mcp:0.8.0", + "identifier": "ghcr.io/julian-dev28/pathiel-mcp:0.9.0", "transport": { "type": "stdio" }, diff --git a/services/intel/scheduled_events.py b/services/intel/scheduled_events.py index 2388c819..26fca5fc 100644 --- a/services/intel/scheduled_events.py +++ b/services/intel/scheduled_events.py @@ -259,19 +259,35 @@ def merge(curated: Dict[str, Any], overlay: Dict[str, Any]) -> Dict[str, Any]: _CACHE: Dict[Tuple[str, str], Tuple[Tuple[Any, Any], Dict[str, Any]]] = {} -def load(path: str = DATA_PATH, overlay: Optional[str] = None) -> Dict[str, Any]: +def load(path: str = DATA_PATH, overlay: Optional[str] = None, *, + use_overlay: bool = True) -> Dict[str, Any]: """The curated file merged with the scan overlay. Cached on both files' (mtime, size), so a long-running process re-reads within one call of a - scan writing, and never re-parses when nothing changed.""" - overlay = overlay or overlay_path() - key = (path, overlay) - sig = (_sig(path), _sig(overlay)) + scan writing, and never re-parses when nothing changed. + + `use_overlay=False` (added for services/research_mcp, the read-only + research MCP) skips `overlay_path()` entirely, so this call never + reaches `env.state_dir()` -> `env._load_dotenv()`, which reads the + repo's own `.env.local` into the process environment on a checkout + that has one. The research MCP must never touch that file (CLAUDE.md: + "never open .env.local or ~/.pathiel"), so it always passes + `use_overlay=False` and gets the curated file only -- no 12-hour scan + rows, which is the right trade for an external reader anyway: the scan + overlay is this operator's own live state, not a published dataset.""" + if use_overlay: + overlay = overlay or overlay_path() + key: Tuple[str, str] = (path, overlay) + sig = (_sig(path), _sig(overlay)) + else: + key = (path, "__no_overlay__") + sig = (_sig(path), None) hit = _CACHE.get(key) if hit and hit[0] == sig: return hit[1] with open(path) as fh: curated = json.load(fh) - data = merge(curated, read_overlay(overlay)) + overlay_data = read_overlay(overlay) if use_overlay else {"version": 1, "events": [], "state": {}} + data = merge(curated, overlay_data) _CACHE[key] = (sig, data) return data @@ -347,11 +363,11 @@ def _for_coin(r: Dict[str, Any], coin: Optional[str]) -> Dict[str, Any]: def market_events(start_ms: int, end_ms: int, coin: Optional[str] = None, - path: str = DATA_PATH) -> List[Dict[str, Any]]: + path: str = DATA_PATH, *, use_overlay: bool = True) -> List[Dict[str, Any]]: """Every event (file rows plus the generated FOMC/CPI/OPEC+) whose time or blackout window touches [start_ms, end_ms), for `coin` when given, sorted - by time. Pure given the file.""" - rows = [_row(e) for e in load(path)["events"]] + by time. Pure given the file. `use_overlay`: see load().""" + rows = [_row(e) for e in load(path, use_overlay=use_overlay)["events"]] d0 = datetime.fromtimestamp(start_ms / 1000, tz=timezone.utc).date() - timedelta(days=2) d1 = datetime.fromtimestamp(end_ms / 1000, tz=timezone.utc).date() + timedelta(days=2) rows += _generated(d0, d1) @@ -367,9 +383,11 @@ def market_events(start_ms: int, end_ms: int, coin: Optional[str] = None, return sorted(out, key=lambda r: r["at_ms"]) -def blackout(coin: str, at_ms: int, path: str = DATA_PATH) -> Optional[Dict[str, Any]]: - """The impact-3 event window `at_ms` sits in for `coin`, or None.""" - for r in market_events(at_ms - 3 * DAY_MS, at_ms + 3 * DAY_MS, coin, path): +def blackout(coin: str, at_ms: int, path: str = DATA_PATH, *, + use_overlay: bool = True) -> Optional[Dict[str, Any]]: + """The impact-3 event window `at_ms` sits in for `coin`, or None. + `use_overlay`: see load().""" + for r in market_events(at_ms - 3 * DAY_MS, at_ms + 3 * DAY_MS, coin, path, use_overlay=use_overlay): w = r["window"] if w and w["start_ms"] <= at_ms < w["end_ms"]: return {"coin": coin, "event": r["title"], "kind": r["kind"], "start_ms": w["start_ms"], diff --git a/services/intel/sources/catalysts.py b/services/intel/sources/catalysts.py index e1492dae..94ae7a95 100644 --- a/services/intel/sources/catalysts.py +++ b/services/intel/sources/catalysts.py @@ -75,8 +75,14 @@ def active_kinds(spec: DeskSpec) -> set: return kinds -def calendar_catalysts(spec: DeskSpec, now: datetime) -> List[Catalyst]: - """Pure, instant, no I/O — every date-rule-based catalyst in window.""" +def calendar_catalysts(spec: DeskSpec, now: datetime, *, use_overlay: bool = True) -> List[Catalyst]: + """Pure, instant, no I/O (given `use_overlay=False`) — every date-rule- + based catalyst in window, plus the curated scheduled-event rows + (scheduled_catalysts below). `use_overlay=False` (added for + services/research_mcp): see scheduled_catalysts()'s docstring — a + caller that must never reach services.intel.env.state_dir() (which + loads the repo's own .env.local) passes it through. Default True keeps + every existing caller's behavior unchanged.""" start, end = desk_window(spec, now) kinds = active_kinds(spec) out: List[Catalyst] = [] @@ -94,22 +100,35 @@ def calendar_catalysts(spec: DeskSpec, now: datetime) -> List[Catalyst]: kind=kind, title=title, at=rel.at_utc, importance=importance, source=source, expected=expected, )) - out += scheduled_catalysts(spec, now) + out += scheduled_catalysts(spec, now, use_overlay=use_overlay) return out -def scheduled_catalysts(spec: DeskSpec, now: datetime) -> List[Catalyst]: +def scheduled_catalysts(spec: DeskSpec, now: datetime, *, use_overlay: bool = True) -> List[Catalyst]: """Rows of services/intel/data/scheduled_events.json (elections, jobs, PCE, OPEC/IEA monthly reports, funding deadlines, holidays...) for the desk's coins, in its window. Operator, 2026-11-05: the 11-03 midterms - were not on the calendar and Brent fell 9% on the result. Pure.""" + were not on the calendar and Brent fell 9% on the result. Pure given + `use_overlay=False`. + + `use_overlay=False`: skips the 12-hour scan overlay and, with it, the + one call in this whole module that is NOT pure — scheduled_events. + market_events()'s default path calls overlay_path() -> + services.intel.env.state_dir() -> env._load_dotenv(), which reads the + repo's own `.env.local` into this process's environment on a checkout + that has one. services/research_mcp (CLAUDE.md: "never open .env.local + or ~/.pathiel" for that server) always passes False and gets the + curated file's rows only, no scan overlay — the right trade for an + external reader anyway, since the scan overlay is this operator's own + live state, not a published dataset. Default True keeps every existing + caller (the live desk loop, by way of calendar_catalysts) unchanged.""" from services.intel import scheduled_events coins = {i.coin for i in spec.instruments} start, end = desk_window(spec, now) t0 = int(now.timestamp() * 1000) t1 = int(datetime(end.year, end.month, end.day, tzinfo=timezone.utc).timestamp() * 1000) out: List[Catalyst] = [] - for r in scheduled_events.market_events(t0, t1): + for r in scheduled_events.market_events(t0, t1, use_overlay=use_overlay): # Curated rows and the 12-hour scan's overlay rows; the generated # FOMC/CPI/OPEC+ rows already come from _CALENDAR_GENERATORS above. if r["origin"] not in scheduled_events.FILE_ORIGINS or not (r["coins"] & coins) or r["at_ms"] < t0: diff --git a/services/intel/sources/fred.py b/services/intel/sources/fred.py index 31e2ea08..b29056f0 100644 --- a/services/intel/sources/fred.py +++ b/services/intel/sources/fred.py @@ -64,6 +64,48 @@ def fetch_series(series_id: str, api_key: str) -> Tuple[Optional[List[Dict[str, return data["observations"], None +def fetch_observations(series_id: str, *, start: Optional[str] = None, end: Optional[str] = None, + api_key: Optional[str] = None + ) -> Tuple[Optional[List[Dict[str, Any]]], Optional[str]]: + """Raw FRED observations for ANY series_id, with an optional date range — + added for the research MCP's `fred_series` tool (services/research_mcp), + which lets a caller read any series its own free FRED_API_KEY can see. + `fetch_fred`/`fetch_series` above stay scoped to the fixed four-series, + 5-day-change read the desks consume; this is the same http_client.fetch_json + call with start/end wired through, exposed as a public function instead of + a second ad-hoc fetch_json call site outside this module (the research MCP + never pokes FRED_OBSERVATIONS_URL directly). + + `api_key` None (the normal case) reads FRED_API_KEY from the environment, + same as fetch_fred; the caller is responsible for not logging it. Missing + key: (None, "FRED_API_KEY_missing"), same string fetch_fred already uses, + so a caller can match on it without inventing a second sentinel. + + With `start`/`end`, results are chronological (oldest first) and + uncapped by OBS_LIMIT (FRED's own default page size, 100000, applies + instead) -- a range query is asking for the range, not "the latest 15". + With neither, this is `fetch_series`'s own newest-15-observations shape.""" + key = api_key or _api_key() + if not key: + return None, "FRED_API_KEY_missing" + params: Dict[str, Any] = {"series_id": series_id, "api_key": key, "file_type": "json"} + if start or end: + params["sort_order"] = "asc" + if start: + params["observation_start"] = start + if end: + params["observation_end"] = end + else: + params["sort_order"] = "desc" + params["limit"] = OBS_LIMIT + data, err = http_client.fetch_json(FRED_OBSERVATIONS_URL, params=params, timeout_s=8.0) + if err: + return None, err + if not isinstance(data, dict) or not isinstance(data.get("observations"), list): + return None, "bad_shape" + return data["observations"], None + + def _to_datapoint(series_id: str, observations: List[Dict[str, Any]]) -> Optional[DataPoint]: label, unit = SERIES[series_id] valid = [(o.get("date"), _safe_float(o.get("value"))) for o in observations] @@ -108,3 +150,6 @@ def fetch_fred(spec: DeskSpec) -> Tuple[List[DataPoint], Optional[str]]: ATOMIC_FETCHERS = (fetch_fred,) + +__all__ = ["SERIES", "FRED_OBSERVATIONS_URL", "fetch_series", "fetch_observations", "fetch_fred", + "ATOMIC_FETCHERS"] diff --git a/services/intel/tests/test_scheduled_events.py b/services/intel/tests/test_scheduled_events.py index fda0af47..a5d11022 100644 --- a/services/intel/tests/test_scheduled_events.py +++ b/services/intel/tests/test_scheduled_events.py @@ -131,6 +131,45 @@ def test_an_impact_3_scan_row_blocks_entries_like_a_curated_one(tmp_path, isolat assert S.blackout(SILVER, ms(2026, 11, 17, 23, 59)) is None +# ── use_overlay=False: the research MCP's keyless-reader path ─────────────── +# Added for services/research_mcp, which must never call env.state_dir() (it +# reads the repo's own .env.local -- CLAUDE.md's "never open .env.local or +# ~/.pathiel" hard rule for that server). These pin that load()/market_events()/ +# blackout() with use_overlay=False never reach overlay_path() at all, not just +# that they happen to return the same thing today. + +def test_load_use_overlay_false_never_calls_overlay_path(tmp_path, monkeypatch): + curated = _curated(tmp_path, [ROW]) + + def _boom(): + raise AssertionError("overlay_path() must not be called when use_overlay=False") + monkeypatch.setattr(S, "overlay_path", _boom) + data = S.load(curated, use_overlay=False) + assert len(data["events"]) == 1 and data["scanned"] == 0 + + +def test_load_use_overlay_false_ignores_an_overlay_file_that_exists(tmp_path, isolated_state_dir): + """Even when a real scan overlay sits right where overlay_path() would + find it, use_overlay=False never reads it.""" + curated = _curated(tmp_path, [ROW]) + p = isolated_state_dir / "intel" / "scanned_events.json" + p.parent.mkdir(parents=True) + p.write_text(json.dumps({"version": 1, "state": {}, "events": [ + dict(ROW, date="2026-11-12", event="Scanned row")]})) + data = S.load(curated, use_overlay=False) + assert len(data["events"]) == 1 and data["scanned"] == 0 + + +def test_market_events_and_blackout_use_overlay_false_never_call_env_state_dir(monkeypatch): + def _boom(*a, **kw): + raise AssertionError("env.state_dir() must not be called when use_overlay=False") + from services.intel import env + monkeypatch.setattr(env, "state_dir", _boom) + now = ms(2026, 11, 5, 11) + assert isinstance(S.market_events(now, now + S.DAY_MS, BRENT, use_overlay=False), list) + assert S.blackout(BRENT, now, use_overlay=False) is None or True # must not raise + + # ── blackout windows ──────────────────────────────────────────────────────── def test_the_real_11_03_entry_falls_inside_the_midterm_blackout(): diff --git a/services/intel/tests/test_sources_catalysts.py b/services/intel/tests/test_sources_catalysts.py index 1e806a60..7b91e554 100644 --- a/services/intel/tests/test_sources_catalysts.py +++ b/services/intel/tests/test_sources_catalysts.py @@ -127,6 +127,40 @@ def test_calendar_catalysts_ids_stable(): assert [c.id for c in a] == [c.id for c in b] +# ── use_overlay=False: the research MCP's keyless-reader path ─────────────── +# Added for services/research_mcp, which must never reach +# services.intel.env.state_dir() (it loads the repo's own .env.local — +# CLAUDE.md's "never open .env.local or ~/.pathiel" hard rule for that +# server). These pin that calendar_catalysts()/scheduled_catalysts() with +# use_overlay=False never call it, not just that today's answer matches. + +def test_calendar_catalysts_use_overlay_false_never_touches_env_state_dir(monkeypatch): + from services.intel import env + + def _boom(*a, **kw): + raise AssertionError("env.state_dir() must not be called when use_overlay=False") + monkeypatch.setattr(env, "state_dir", _boom) + spec = _spec(coin="xyz:BRENTOIL", label="Brent", catalyst_kinds=["eia_weekly"]) + cats = catalysts.calendar_catalysts(spec, NOW, use_overlay=False) + assert isinstance(cats, list) and any(c.kind == "eia_weekly" for c in cats) + + +def test_calendar_catalysts_use_overlay_false_still_includes_curated_rows(): + """use_overlay=False drops the scan overlay, not the curated file: the + real desk's scheduled_events.json rows (elections, jobs, earnings...) + still come through.""" + from services.strategies import desks + spec = desks.require_spec("oil") + now = datetime(2026, 10, 20, tzinfo=timezone.utc) + with_overlay = catalysts.calendar_catalysts(spec, now) + without_overlay = catalysts.calendar_catalysts(spec, now, use_overlay=False) + curated_kinds = {c.kind for c in without_overlay} - {"fomc", "cpi"} + assert curated_kinds, "scheduled_catalysts() must still contribute curated rows" + # Same curated rows either way (this fixture's state dir has no scan + # overlay to begin with, so the two calls agree on content, not just type). + assert {c.id for c in with_overlay} == {c.id for c in without_overlay} + + def test_calendar_catalysts_assumption_shift_sets_expected_field(): """A generator whose note mentions an assumption/shift must surface that on the Catalyst's `expected` field — nothing about an unverified diff --git a/services/intel/tests/test_sources_fred.py b/services/intel/tests/test_sources_fred.py index ffcff2a4..b181117d 100644 --- a/services/intel/tests/test_sources_fred.py +++ b/services/intel/tests/test_sources_fred.py @@ -100,3 +100,67 @@ def test_no_valid_observations_is_reported(monkeypatch): items, err = fred.fetch_fred(_metals_spec()) assert items == [] assert err is not None and "no_valid_observations" in err + + +# ── fetch_observations: the research MCP's fred_series tool ───────────────── + +def test_fetch_observations_missing_key_is_reported_not_silent(monkeypatch): + monkeypatch.delenv("FRED_API_KEY", raising=False) + data, err = fred.fetch_observations("DGS10") + assert data is None + assert err == "FRED_API_KEY_missing" + + +def test_fetch_observations_passes_an_explicit_key_without_reading_the_env(monkeypatch): + monkeypatch.delenv("FRED_API_KEY", raising=False) + seen = {} + + def fake(url, **kw): + seen.update(kw.get("params") or {}) + return {"observations": _obs([1.0])}, None + monkeypatch.setattr(http_client, "fetch_json", fake) + data, err = fred.fetch_observations("DGS10", api_key="explicit-key") + assert err is None and data is not None + assert seen["api_key"] == "explicit-key" + + +def test_fetch_observations_no_range_is_newest_first_capped_at_obs_limit(monkeypatch): + monkeypatch.setenv("FRED_API_KEY", "fake-key") + seen = {} + + def fake(url, **kw): + seen.update(kw.get("params") or {}) + return {"observations": _obs([1.0, 2.0])}, None + monkeypatch.setattr(http_client, "fetch_json", fake) + data, err = fred.fetch_observations("DGS10") + assert err is None + assert seen["sort_order"] == "desc" + assert seen["limit"] == fred.OBS_LIMIT + assert "observation_start" not in seen and "observation_end" not in seen + + +def test_fetch_observations_with_a_range_is_chronological_and_uncapped(monkeypatch): + monkeypatch.setenv("FRED_API_KEY", "fake-key") + seen = {} + + def fake(url, **kw): + seen.update(kw.get("params") or {}) + return {"observations": _obs([1.0, 2.0])}, None + monkeypatch.setattr(http_client, "fetch_json", fake) + data, err = fred.fetch_observations("DGS10", start="2026-01-01", end="2026-06-01") + assert err is None + assert seen["sort_order"] == "asc" + assert seen["observation_start"] == "2026-01-01" + assert seen["observation_end"] == "2026-06-01" + assert "limit" not in seen + + +def test_fetch_observations_bad_shape_and_http_error_pass_through(monkeypatch): + monkeypatch.setenv("FRED_API_KEY", "fake-key") + monkeypatch.setattr(http_client, "fetch_json", lambda url, **kw: ({"nope": True}, None)) + data, err = fred.fetch_observations("DGS10") + assert data is None and err == "bad_shape" + + monkeypatch.setattr(http_client, "fetch_json", lambda url, **kw: (None, "timeout")) + data, err = fred.fetch_observations("DGS10") + assert data is None and err == "timeout" diff --git a/services/research_mcp/.claude-plugin/plugin.json b/services/research_mcp/.claude-plugin/plugin.json new file mode 100644 index 00000000..3917a1da --- /dev/null +++ b/services/research_mcp/.claude-plugin/plugin.json @@ -0,0 +1,24 @@ +{ + "name": "pathiel-research", + "displayName": "pathiel research", + "version": "0.1.0", + "description": "The risk-gated research layer AI agents trade through: a free, read-only, keyless MCP server with 6 tools (research_brief, events, prediction_odds, fred_series, headlines, levels) for BRENTOIL, HYPE, BTC, ETH and SP500. Hyperliquid public candles, news/RSS, Polymarket/Kalshi odds, the scheduled-event calendar, and pathiel's own stored desk thesis. Never touches a key, an account or an order.", + "author": { + "name": "Julian Martinez", + "url": "https://github.com/Julian-dev28" + }, + "homepage": "https://julian-dev28.github.io/pathiel/", + "documentationUrl": "https://github.com/Julian-dev28/pathiel/blob/main/services/research_mcp/README.md", + "privacyPolicyUrl": "https://github.com/Julian-dev28/pathiel/blob/main/docs/PRIVACY.md", + "supportUrl": "https://github.com/Julian-dev28/pathiel/issues", + "termsOfServiceUrl": "https://github.com/Julian-dev28/pathiel/blob/main/docs/TERMS.md", + "repository": "https://github.com/Julian-dev28/pathiel", + "license": "MIT", + "keywords": ["research", "mcp", "claude-code", "hyperliquid", "polymarket", "kalshi", "fred", "market-research", "oil", "crypto"], + "mcpServers": { + "pathiel-research": { + "command": "bash", + "args": ["${CLAUDE_PLUGIN_ROOT}/../../scripts/pathiel-research-mcp.sh"] + } + } +} diff --git a/services/research_mcp/README.md b/services/research_mcp/README.md new file mode 100644 index 00000000..d1f682f4 --- /dev/null +++ b/services/research_mcp/README.md @@ -0,0 +1,280 @@ +# pathiel research MCP + +**The risk-gated research layer AI agents trade through.** A free, +read-only, keyless MCP server: six tools that answer "what does the market +look like right now," built from the same deterministic market intelligence +pathiel's own trading desks read (`services/intel`, `services/strategies`, +`services/thesis`); never from a hosted LLM call, and never touching a +key, an account, or an order. + +v1 is local stdio only, packaged as a second Claude Code plugin in this same +repo. No billing, no hosting, free. See +[`docs/design/RESEARCH_MCP_PAID_TIER.md`](../../docs/design/RESEARCH_MCP_PAID_TIER.md) +for the hosted, metered plan this earns toward later. + +## Install + +In Claude Code: + +``` +/plugin marketplace add Julian-dev28/pathiel +/plugin install pathiel-research@pathiel +``` + +From a shell: + +```bash +claude plugin marketplace add Julian-dev28/pathiel +claude plugin install pathiel-research@pathiel +``` + +The plugin builds its own Python environment on first use, under its own +data directory (`$CLAUDE_PLUGIN_DATA` or `~/.pathiel-research/data`), +**separate from the trading plugin's `~/.pathiel`**. This server never +reads that directory, or `.env.local` anywhere, at all. + +Running from a checkout instead: + +```bash +.venv/bin/python scripts/pathiel-research-mcp.py +``` + +or register `scripts/pathiel-research-mcp.sh` as the server command with +any other MCP client (Claude Desktop, Cursor, ...). + +## Why a second server, not a new tool on the trading one + +The trading MCP (`scripts/pathiel-mcp-server.py`) needs a key to place an +order and defaults to real money on mainnet. A research client (another +agent, a bot that only wants market context, a developer evaluating pathiel) +should never be one misread away from that. This server is a different +process, a different entrypoint, and (see +`tests/test_no_trading_imports.py`) structurally incapable of importing +order-placement or signing code: the trading tools do not exist here to be +called by accident. + +## Tools + +Every tool is read-only. Coins supported today: `BRENTOIL` (`xyz:BRENTOIL`), +`HYPE`, `BTC`, `ETH`, `SP500` (`xyz:SP500`), plus common aliases (`BRENT`, +`OIL`, `BITCOIN`, `ETHEREUM`, `SPX`, `S&P 500`, ...). `ETH` has no +standalone pathiel desk; its catalysts/headlines/odds/thesis come from the +`top5` basket desk (BTC, ETH, SOL, HYPE, ZEC), and `research_brief` says so +in its `note` field. + +### `research_brief {coin}` + +One call, everything: levels, the next scheduled catalysts, top headlines, +related prediction-market odds, and the latest **stored** desk thesis if +one exists. Never writes a new thesis; that needs an LLM call, which this +read-only server never makes (see Limits). + +```json +// tools/call research_brief {"coin": "HYPE"} +{ + "coin": "HYPE", "desk_id": "hype", "as_of": "2026-11-21T18:12:40Z", + "levels": {"mid": 42.87, "range_24h": {"high": 43.5, "low": 41.9}, "atr14_1h": 0.31, "...": "..."}, + "catalysts": [{"kind": "fomc", "title": "FOMC decision", "at": "2026-12-10T19:00:00Z", "importance": 3, "...": "..."}], + "headlines": [{"title": "Hyperliquid daily volume hits a new high", "source": "...", "relevance": 0.81}], + "odds": [{"venue": "polymarket", "question": "Will HYPE be above $45 on Dec 1?", "probability": 0.34}], + "thesis": null, + "note": null, + "sources_failed": [] +} +``` + +`sources_failed` lists which sub-source came back empty or errored (one +dead feed never sinks the whole brief); `thesis` is `null` whenever that +desk hasn't been ticked on whatever machine runs this server; correct +behavior, not a bug. + +### `events {coins?, days?}` + +The scheduled-event calendar (FOMC, CPI, jobs, PCE, earnings, elections, +OPEC+, holidays, ...) for one or more coins over the next `days` (default +7, max 60), plus any active blackout flag. Omit `coins` for every supported +coin. + +```json +// tools/call events {"coins": ["BRENTOIL"], "days": 21} +{ + "as_of": "2026-11-21T18:15Z", "window_days": 21.0, + "coins": {"xyz:BRENTOIL": { + "events": [ + {"title": "US GDP Q3 second estimate + PCE (Oct)", "kind": "pce", "impact": 2, + "coins": ["xyz:BRENTOIL", "xyz:CL", "xyz:GOLD", "xyz:SILVER", "xyz:SP500"], + "at_ms": 1795613400000, "all_day": false, "verified": true, + "source": "https://www.bea.gov/news/schedule"}, + {"title": "US Thanksgiving: NYSE, CME, COMEX, ICE closed (thin liquidity)", + "kind": "us_holiday", "impact": 2, "all_day": true} + ], + "active_blackout": null + }}, + "sources_failed": [] +} +``` + +`BTC` and `ETH` have no curated calendar group yet (only +oil/metals/sp500/hype coins do); asking for them returns `events: []` with +an explicit `note`, never a silent empty list. + +### `prediction_odds {query? or coin?}` + +Polymarket and Kalshi markets and odds for a coin's own research queries, +or a free-text search. Pass exactly one of `coin` or `query`. + +```json +// tools/call prediction_odds {"coin": "BTC"} +{ + "query": "BTC", + "odds": [ + {"venue": "polymarket", "question": "Will the price of Bitcoin be less than $56,000 on November 22?", + "probability": 0.026, "volume_usd": 23773.09, "closes_at": "2026-11-22T17:00:00Z"}, + {"venue": "polymarket", "question": "Will the price of Bitcoin be less than $56,000 on November 23?", + "probability": 0.0785, "volume_usd": 7704.25, "closes_at": "2026-11-23T17:00:00Z"} + ], + "sources_failed": [] +} +``` + +### `fred_series {series_id, start?, end?}` + +Any FRED (Federal Reserve Economic Data) series' observations, e.g. +`DGS10` (10y Treasury yield), `DFII10` (10y real yield), `T10YIE` (10y +breakeven inflation), `DTWEXBGS` (broad dollar index). Needs the caller's +own `FRED_API_KEY` in the server's environment; refuses cleanly without +one, and never logs the key: + +```json +// tools/call fred_series {"series_id": "DGS10"}, no FRED_API_KEY set +{ + "error": "FRED_API_KEY_missing", + "series_id": "DGS10", + "help": "fred_series needs the user's own FRED_API_KEY in the environment. Get a free key at https://fred.stlouisfed.org/docs/api/api_key.html (no credit card), then export FRED_API_KEY=... before starting this server." +} +``` + +Get a free key (no credit card) at +[fred.stlouisfed.org/docs/api/api_key.html](https://fred.stlouisfed.org/docs/api/api_key.html), +`export FRED_API_KEY=...` before starting this server. + +### `headlines {coin|topic, hours?}` + +Recent headlines, scored and deduped, for a coin or a free-text topic. +Pass exactly one of `coin` or `topic`. + +```json +// tools/call headlines {"coin": "BRENTOIL", "hours": 24} +{ + "query": "xyz:BRENTOIL", "hours": 24.0, + "headlines": [ + {"title": "Goldman is out with its 2027 forecast for Brent oil prices", "source": "Yahoo Finance", + "published_at": "2026-11-21T12:50:18Z", "relevance": 0.81}, + {"title": "IRGC Says It Shot Down Two US Drones Over Strait of Hormuz...", "source": "NewsCord", + "published_at": "2026-11-21T17:22:15Z", "relevance": 0.64} + ], + "sources_failed": [] +} +``` + +### `levels {coin}` + +Public Hyperliquid candle math, no key needed: mid, the last closed 1h +candle, 8h/24h/48h range, ATR14 (1h), the last four closed 15m candles' +range. + +```json +// tools/call levels {"coin": "BRENTOIL"} +{ + "coin": "xyz:BRENTOIL", "mid": 90.1185, + "last_closed_1h": {"open": 90.068, "high": 90.078, "low": 90.042, "close": 90.073, + "closed_at_utc": "2026-11-21T18:00"}, + "range_8h": {"high": 90.202, "low": 89.895}, + "range_24h": {"high": 90.4, "low": 88.9}, + "range_48h": {"high": 90.4, "low": 87.707}, + "atr14_1h": 0.1394, "atr14_pct": 0.155, + "range_15m_last4": {"high": 90.104, "low": 90.059}, + "n_closed_1h": 50, "mid_pos_in_24h": 0.812 +} +``` + +## Data sources and attribution + +| source | used by | key | notes | +|---|---|---|---| +| Hyperliquid public `/info` | `levels`, `research_brief` | none | candleSnapshot + allMids, the same public endpoint the trading server's reads use | +| Google News, Yahoo Finance, EIA, Investing.com, oilprice.com, Cointelegraph RSS | `headlines`, `research_brief` | none | `services/intel/sources/news.py` | +| Polymarket (`gamma-api.polymarket.com`), Kalshi (`api.elections.kalshi.com`) | `prediction_odds`, `research_brief` | none | `services/intel/sources/predictions.py` | +| FRED (`api.stlouisfed.org`) | `fred_series` | **your own free `FRED_API_KEY`** | `services/intel/sources/fred.py` | +| pathiel's own curated + generated event calendar | `events`, `research_brief` | none | `services/intel/data/scheduled_events.json` + `services/intel/calendar_us.py` | +| pathiel's own stored desk theses | `research_brief` | none | `services/strategies/journal.py`; read-only, never written by this server | + +This server adds no API keys of its own and signs nothing. FRED is the one +source that needs a key, and it is always the caller's own. + +## Usage counter + +A local, privacy-preserving count of how many times each tool has been +called (no arguments, no results, no caller identity), written to +`usage.json` under this server's own state directory +(`$PATHIEL_RESEARCH_STATE_DIR`, default `~/.pathiel-research/state`; +`services/research_mcp/state.py`). Telemetry (sending this, or anything +else, off this machine) is off by default and **not implemented in v1**. +See `docs/design/RESEARCH_MCP_PAID_TIER.md`. + +## Limits + +- **No LLM calls.** `research_brief`'s `thesis` field serves whatever the + trading desk already wrote and saved to disk; it is `null` on any machine + where that desk has never been refreshed. This server never writes a new + one (CLAUDE.md: no hosted LLM API; the local-Claude-Code route belongs to + the trading server, not this one). +- **Five coins today**: BRENTOIL, HYPE, BTC, ETH, SP500. Adding one means a + new entry in `coins.py`'s `_COIN_DESK`/`_ALIASES` maps and (if it should + have a curated event calendar) a `COIN_GROUPS` entry in + `services/intel/scheduled_events.py`. +- **`events`/`research_brief`'s calendar never includes the 12-hour scan + overlay** (`services/intel/scheduled_events.py`'s `scanned_events.json`): + this server always reads with `use_overlay=False` so it never has to call + `env.state_dir()` (which would load the repo's own `.env.local`). You get + the curated file and the generated FOMC/CPI/OPEC+ rows, not the + operator's own live scan state. +- **No caching.** Every call is a live read; a `research_brief` typically + takes a few seconds (several RSS/API calls fanned out concurrently, see + `concurrent.py`) rather than milliseconds. v1 ships without a TTL cache on + purpose; add one if call volume ever justifies it. +- **`events`' curated calendar** only covers coins in a scheduled-events + group (oil, metals, sp500, hype); `BTC`/`ETH` get an explicit note instead + of a silent empty list. FOMC/CPI still show up for every coin through + `calendar_catalysts`. +- **Not financial advice.** Every number here is public data or pathiel's + own prior analysis, never a live recommendation from this server. + +## Architecture + +``` +services/research_mcp/ + coins.py coin/desk resolution (BRENTOIL/HYPE/BTC/ETH/SP500 + aliases) + concurrent.py fetch_many(): fan a list of fetchers out, deadline-bounded, never raises + state.py this server's own state directory (never ~/.pathiel) + usage.py the local usage counter + tools.py the six tools' implementations + schemas.py the six tools' MCP tools/list entries + server.py the stdio JSON-RPC transport + tests/ gate tests, offline, <2s each + evals/ + brief_coverage.py live, periodic: does research_brief really answer for every coin today + .claude-plugin/ + plugin.json the Claude Code plugin manifest (source: ./services/research_mcp) +``` + +Entrypoint: `scripts/pathiel-research-mcp.py` (a checkout) or +`scripts/pathiel-research-mcp.sh` (the plugin launcher; builds its own +venv, never touches the trading server's `~/.pathiel`). + +## Tests and evals + +```bash +.venv/bin/python -m pytest -q services/research_mcp/ # gate tests, offline, <2s each +.venv/bin/python -m services.research_mcp.evals.brief_coverage # live, periodic +``` diff --git a/services/research_mcp/__init__.py b/services/research_mcp/__init__.py new file mode 100644 index 00000000..73a064ca --- /dev/null +++ b/services/research_mcp/__init__.py @@ -0,0 +1,15 @@ +"""pathiel research MCP: a read-only, keyless MCP server that serves +pathiel's deterministic market research (levels, scheduled catalysts, +headlines, prediction-market odds, FRED series, and the latest stored desk +thesis) to any MCP client. + +Hard boundary (see tests/test_no_trading_imports.py, the gate that proves +it): nothing here imports order-placement or signing code +(pathiel.agents.bracket, pathiel.client.exchange, services.strategies. +next_trade, the trading MCP's own scripts/pathiel-mcp-server.py), and +nothing here opens .env.local or ~/.pathiel. It imports the rest of pathiel +(services/intel, services/strategies, services/thesis, pathiel.client. +hl_client) only through their public functions, never their private (`_`) +internals. See README.md for the tool list and the install command. +""" +from __future__ import annotations diff --git a/services/research_mcp/coins.py b/services/research_mcp/coins.py new file mode 100644 index 00000000..70239ab1 --- /dev/null +++ b/services/research_mcp/coins.py @@ -0,0 +1,91 @@ +"""Coin/desk resolution for the research MCP, v1: exactly the five coins the +build brief names -- BRENTOIL (xyz:BRENTOIL), HYPE, BTC, ETH and SP500 +(xyz:SP500). + +Deliberately does NOT go through services.strategies.desks.get_spec() / +list_specs() / require_spec(): those apply install-kind and network +adjustments (a public install's leverage-ladder cut, a testnet coin swap -- +see services/strategies/desks/__init__.py's _for_install/_for_network) that +exist for the TRADING server's own install, not for a stateless research +answer. Calling them would also risk pulling in pathiel.agents.config_store +/ services.risk.presets (the risk-profile read behind profile_leverage_cap()) +for no benefit here. Instead this module calls each desk MODULE's own +build_spec() directly -- pure, no I/O, no env read, no network -- so a +research_brief always describes the desk as designed, the same for every +caller regardless of how this process happens to be installed. + +ETH has no standalone desk in the registry; its research draws on the top5 +desk's DeskSpec (the only one that lists ETH as an instrument), with a note +in research_brief's output. desk_id_for("ETH") returning "top5" means the +latest-stored-thesis lookup reads top5's journal (not ETH-specific; top5 is +rarely active and often has no stored thesis at all -- research_brief says +so rather than guessing). +""" +from __future__ import annotations + +from typing import Callable, Dict, List, Tuple + +from contracts.strategies.models import DeskSpec +from services.strategies.desks import btc as _btc_desk +from services.strategies.desks import hype as _hype_desk +from services.strategies.desks import oil as _oil_desk +from services.strategies.desks import sp500 as _sp500_desk +from services.strategies.desks import top5 as _top5_desk + + +class UnsupportedCoinError(ValueError): + """Raised for a coin this v1 server does not cover yet.""" + + +# canonical HL coin name -> (desk id its research comes from, that desk +# module's build_spec). Order here is the order SUPPORTED_COINS lists them. +_COIN_DESK: Dict[str, Tuple[str, Callable[[], DeskSpec]]] = { + "xyz:BRENTOIL": ("oil", _oil_desk.build_spec), + "HYPE": ("hype", _hype_desk.build_spec), + "BTC": ("btc", _btc_desk.build_spec), + "ETH": ("top5", _top5_desk.build_spec), + "xyz:SP500": ("sp500", _sp500_desk.build_spec), +} + +SUPPORTED_COINS: List[str] = list(_COIN_DESK) + +# accepted spellings -> canonical HL coin name. Matched case-insensitively +# (canonical_coin upper()s the input before the lookup). +_ALIASES: Dict[str, str] = { + "BRENTOIL": "xyz:BRENTOIL", "XYZ:BRENTOIL": "xyz:BRENTOIL", + "BRENT": "xyz:BRENTOIL", "OIL": "xyz:BRENTOIL", "CRUDE": "xyz:BRENTOIL", + "HYPE": "HYPE", "HYPERLIQUID": "HYPE", + "BTC": "BTC", "BITCOIN": "BTC", + "ETH": "ETH", "ETHEREUM": "ETH", + "SP500": "xyz:SP500", "XYZ:SP500": "xyz:SP500", "S&P500": "xyz:SP500", + "S&P 500": "xyz:SP500", "SPX": "xyz:SP500", "SP 500": "xyz:SP500", +} + + +def canonical_coin(raw: str) -> str: + """The HL coin name `raw` resolves to. Raises UnsupportedCoinError (with + the supported list in the message) for anything else -- a research_brief + on an unsupported coin fails with a clear, actionable error, never a + silent empty result.""" + key = (raw or "").strip().upper() + canon = _ALIASES.get(key) + if canon is None: + raise UnsupportedCoinError( + f"{raw!r} is not a coin this server covers yet. Supported: " + f"{', '.join(SUPPORTED_COINS)}.") + return canon + + +def desk_id_for(coin: str) -> str: + """The desk id this coin's research (catalysts, odds queries, the + stored-thesis lookup) comes from. Raises UnsupportedCoinError.""" + desk_id, _ = _COIN_DESK[canonical_coin(coin)] + return desk_id + + +def desk_spec_for(coin: str) -> DeskSpec: + """The DeskSpec this coin's research is drawn from -- a fresh build every + call (pure, cheap; no caching needed, see the module docstring). Raises + UnsupportedCoinError.""" + _, build_spec = _COIN_DESK[canonical_coin(coin)] + return build_spec() diff --git a/services/research_mcp/concurrent.py b/services/research_mcp/concurrent.py new file mode 100644 index 00000000..04c31c3a --- /dev/null +++ b/services/research_mcp/concurrent.py @@ -0,0 +1,65 @@ +"""One small helper: run several zero-arg "fetcher" callables concurrently +and never raise. + +Every services/intel/sources/*.py fetcher already returns the uniform +`(items, error | None)` shape (services/intel/http_client.py's "timeout, one +retry, never raises" contract, carried through every ATOMIC_FETCHERS entry). +services/intel/api.py's build_packet fans these out across a thread pool for +exactly this reason -- this module is that same pattern, trimmed to what a +single research_mcp tool call needs: no desk_dir, no TTL file cache, no +env.py (build_packet's _submit resolves env.intel_dir(spec.id), which this +server must never touch -- see coins.py's and server.py's module docstrings +on why env.state_dir() is off limits here). A tool that wants caching gets it +for free from the OS/network layer's own behavior at today's call volumes; +v1 ships without one on purpose, see README.md's Limits section. +""" +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor, wait +from typing import Any, Callable, List, Optional, Sequence, Tuple + +FetchResult = Tuple[List[Any], Optional[str]] + + +def _name(fn: Callable[[], FetchResult]) -> str: + return getattr(fn, "__name__", None) or getattr(fn, "func", fn).__class__.__name__ + + +def fetch_many(fns: Sequence[Callable[[], FetchResult]], *, deadline_s: float = 10.0 + ) -> Tuple[List[Any], List[str]]: + """Run every zero-arg callable in `fns` on its own thread; wait up to + `deadline_s` total. Returns (items, errors): every finished call's items + concatenated, and one error string per call that raised, returned an + error, or did not finish in time. Never raises -- a tool handler can + always build a response from what this returns, same contract as + build_packet's own worker loop.""" + if not fns: + return [], [] + items: List[Any] = [] + errors: List[str] = [] + # Not a `with` block on purpose: ThreadPoolExecutor.__exit__ calls + # shutdown(wait=True), which blocks until every submitted thread + # finishes -- exactly the stall `deadline_s` exists to prevent. A + # straggler (a hung connection, a slow host) must let this function + # return on time; shutdown(wait=False) abandons it instead, the same + # choice services/intel/api.py's build_packet makes for the identical + # reason (see that module's docstring). + ex = ThreadPoolExecutor(max_workers=min(16, len(fns))) + try: + futs = {ex.submit(fn): fn for fn in fns} + done, not_done = wait(futs, timeout=deadline_s) + for fut in not_done: + errors.append(f"{_name(futs[fut])}:timeout_budget_exceeded") + for fut in done: + name = _name(futs[fut]) + try: + rows, err = fut.result() + except Exception as exc: # noqa: BLE001 - never raise to the tool handler + rows, err = None, f"{name}:unexpected:{type(exc).__name__}" + if err: + errors.append(err) + if rows: + items.extend(rows) + finally: + ex.shutdown(wait=False) + return items, errors diff --git a/services/research_mcp/evals/__init__.py b/services/research_mcp/evals/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/services/research_mcp/evals/brief_coverage.py b/services/research_mcp/evals/brief_coverage.py new file mode 100644 index 00000000..b1884877 --- /dev/null +++ b/services/research_mcp/evals/brief_coverage.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Periodic eval for the research MCP's flagship tool: for every coin +`research_brief` supports, does a REAL call (live network, no mocks) +actually return something in every section? + +This is the eval half of the latent/deterministic split for this server: +research_brief's composition is pure code (tools.py), but whether it +actually delivers real coverage for every supported coin against the live +internet, today, is an empirical claim this eval measures, the same way +services/intel/evals/eval_coverage.py measures build_packet's real coverage +instead of just trusting the code compiled. + +Three checks are REQUIRED per coin (levels, catalysts, headlines) because +every one of them has a reliable public source for every supported coin; +`odds` is scored and reported but not required -- a coin's prediction-market +queries legitimately turn up nothing some days (CLAUDE.md: "score coverage +... odds where the source has them", not "odds always"). `thesis` is +reported too, informationally: it is almost always null in this sandbox (no +desk has been ticked here), which is correct behavior, not a gap. + +Usage: + .venv/bin/python -m services.research_mcp.evals.brief_coverage + .venv/bin/python -m services.research_mcp.evals.brief_coverage --threshold 0.8 + +Exit 0 if the REQUIRED-field coverage score >= threshold (default 0.8), 1 +otherwise. Always live (no --online flag, unlike eval_coverage.py's offline +default): there is no useful offline mode for "does the real internet answer +today." +""" +from __future__ import annotations + +import argparse +import sys +from pathlib import Path +from typing import Any, Dict, List + +HERE = Path(__file__).parent +REPO_ROOT = HERE.parents[3] +sys.path.insert(0, str(REPO_ROOT)) + +from services.research_mcp import coins as coins_mod # noqa: E402 +from services.research_mcp import tools # noqa: E402 + +DEFAULT_THRESHOLD = 0.8 +REQUIRED_FIELDS = ("levels", "catalysts", "headlines") + + +def _non_empty(value: Any) -> bool: + if value is None: + return False + if isinstance(value, (list, dict, str)): + return len(value) > 0 + return True + + +def coverage_for_coin(coin: str) -> Dict[str, Any]: + brief = tools.research_brief(coin) + row = {field: _non_empty(brief.get(field)) for field in REQUIRED_FIELDS} + row["odds"] = _non_empty(brief.get("odds")) + row["thesis"] = _non_empty(brief.get("thesis")) + row["sources_failed"] = list(brief.get("sources_failed") or []) + return row + + +def report(rows: Dict[str, Dict[str, Any]], threshold: float) -> bool: + required_checks = [row[f] for row in rows.values() for f in REQUIRED_FIELDS] + required_score = sum(required_checks) / len(required_checks) if required_checks else 0.0 + odds_score = sum(row["odds"] for row in rows.values()) / len(rows) if rows else 0.0 + passed = required_score >= threshold + status = "PASS" if passed else "FAIL" + + print(f"=== research_brief coverage === required(levels/catalysts/headlines): " + f"{required_score:.2f} (threshold {threshold:.2f}) [{status}] " + f"odds (informational): {odds_score:.2f}") + for coin, row in rows.items(): + marks = " ".join(f"{f}={'OK' if row[f] else 'MISS'}" for f in REQUIRED_FIELDS) + odds_mark = "OK" if row["odds"] else "none" + thesis_mark = "stored" if row["thesis"] else "none (no desk ticked here)" + line = f" {coin:<14} {marks} odds={odds_mark} thesis={thesis_mark}" + if row["sources_failed"]: + line += f" sources_failed={len(row['sources_failed'])}" + print(line) + for err in row["sources_failed"]: + print(f" - {err}") + return passed + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--threshold", type=float, default=DEFAULT_THRESHOLD) + ap.add_argument("--coins", nargs="*", default=None, + help="subset of coins to check (default: every supported coin)") + args = ap.parse_args() + + targets: List[str] = args.coins or list(coins_mod.SUPPORTED_COINS) + rows: Dict[str, Dict[str, Any]] = {} + for coin in targets: + try: + rows[coin] = coverage_for_coin(coin) + except Exception as exc: # noqa: BLE001 - one coin's crash must not kill the whole eval + rows[coin] = {f: False for f in REQUIRED_FIELDS} + rows[coin].update({"odds": False, "thesis": False, + "sources_failed": [f"research_brief_raised:{type(exc).__name__}:{exc}"]}) + + passed = report(rows, args.threshold) + return 0 if passed else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/services/research_mcp/schemas.py b/services/research_mcp/schemas.py new file mode 100644 index 00000000..715acde9 --- /dev/null +++ b/services/research_mcp/schemas.py @@ -0,0 +1,116 @@ +"""The six research MCP tools' MCP tools/list entries: name, description, +inputSchema -- same shape and tone as scripts/pathiel-mcp-server.py's own +TOOLS list, trimmed to a read-only, keyless tool family. tools/list is the +source of truth a client reads; SERVER_INSTRUCTIONS (server.py) is what a +client model reads first. +""" +from __future__ import annotations + +from services.research_mcp import coins as coins_mod + +_COINS_LINE = f"Supported coins today: {', '.join(coins_mod.SUPPORTED_COINS)} (also takes BRENT, OIL, " \ + "BITCOIN, ETHEREUM, SPX, S&P 500 as aliases)." + +TOOLS = [ + { + "name": "research_brief", + "description": ( + "One-call research summary for a coin: levels (mid, 8h/24h/48h range, ATR14), the " + "next scheduled catalysts, top headlines, related Polymarket/Kalshi odds, and the " + "latest stored pathiel desk thesis if one exists (never writes a new one -- that " + "needs an LLM, which this read-only server never calls). " + _COINS_LINE + ), + "inputSchema": { + "type": "object", + "properties": { + "coin": {"type": "string", "description": "e.g. BRENTOIL, HYPE, BTC, ETH, SP500."}, + }, + "required": ["coin"], + }, + }, + { + "name": "events", + "description": ( + "The scheduled-event calendar (FOMC, CPI, jobs, earnings, elections, OPEC+, ...) for " + "one or more coins over the next N days, plus any active event blackout flag. " + + _COINS_LINE + " Omit coins for every supported coin." + ), + "inputSchema": { + "type": "object", + "properties": { + "coins": {"type": "array", "items": {"type": "string"}, + "description": "Coins to check (default: every supported coin)."}, + "days": {"type": "number", "description": "Lookahead window in days (default 7, max 60)."}, + }, + }, + }, + { + "name": "prediction_odds", + "description": ( + "Polymarket and Kalshi markets and odds matching a coin's own research queries, or a " + "free-text query. Pass exactly one of coin or query. " + _COINS_LINE + ), + "inputSchema": { + "type": "object", + "properties": { + "coin": {"type": "string", "description": "A supported coin; uses that desk's own prediction-market queries."}, + "query": {"type": "string", "description": "Free-text search instead of a coin, e.g. \"Fed rate cut\"."}, + }, + }, + }, + { + "name": "fred_series", + "description": ( + "A FRED (Federal Reserve Economic Data) series' observations, e.g. DGS10 (10y Treasury " + "yield), DFII10 (10y real yield), T10YIE (10y breakeven inflation), DTWEXBGS (broad " + "dollar index) -- any FRED series id works. Needs the caller's own FRED_API_KEY in the " + "server's environment (free, no credit card: " + "https://fred.stlouisfed.org/docs/api/api_key.html); refuses cleanly and says so " + "without one. Never logs the key." + ), + "inputSchema": { + "type": "object", + "properties": { + "series_id": {"type": "string", "description": "FRED series id, e.g. DGS10."}, + "start": {"type": "string", "description": "observation_start, YYYY-MM-DD (optional)."}, + "end": {"type": "string", "description": "observation_end, YYYY-MM-DD (optional)."}, + }, + "required": ["series_id"], + }, + }, + { + "name": "headlines", + "description": ( + "Recent headlines (Google News, Yahoo Finance, EIA, Investing.com, oilprice.com, " + "Cointelegraph), scored and deduped, for a coin or a free-text topic. Pass exactly one " + "of coin or topic. " + _COINS_LINE + ), + "inputSchema": { + "type": "object", + "properties": { + "coin": {"type": "string", "description": "A supported coin; uses that desk's own news queries."}, + "topic": {"type": "string", "description": "Free-text topic instead of a coin, e.g. \"OPEC+ meeting\"."}, + "hours": {"type": "number", "description": "How far back to keep headlines (default 24, max 168)."}, + }, + }, + }, + { + "name": "levels", + "description": ( + "Public Hyperliquid candle math for a coin: mid, the last closed 1h candle, 8h/24h/48h " + "range, ATR14 (1h), and the last four closed 15m candles' range. No key needed. " + + _COINS_LINE + ), + "inputSchema": { + "type": "object", + "properties": { + "coin": {"type": "string", "description": "e.g. BRENTOIL, HYPE, BTC, ETH, SP500."}, + }, + "required": ["coin"], + }, + }, +] + +TOOL_NAMES = [t["name"] for t in TOOLS] + +__all__ = ["TOOLS", "TOOL_NAMES"] diff --git a/services/research_mcp/server.py b/services/research_mcp/server.py new file mode 100644 index 00000000..72ae4596 --- /dev/null +++ b/services/research_mcp/server.py @@ -0,0 +1,338 @@ +"""pathiel research MCP server -- stdio transport (JSON-RPC 2.0, one message +per line), same framing as scripts/pathiel-mcp-server.py (the trading +server) but its own process, its own entrypoint (scripts/pathiel-research- +mcp.py), and a completely different tool family: six read-only, keyless +research tools (schemas.py), none of them an order, a key read, or an +account read. + +This module, and everything it imports from services/research_mcp, must +never import order-placement or signing code -- tests/ +test_no_trading_imports.py is the gate that proves it, both by grepping this +package's own source and by checking sys.modules after a full import. It +also never opens .env.local or ~/.pathiel: see coins.py, state.py and +tools.py's docstrings for the specific calls that would and how each is +avoided (use_overlay=False on every services.intel.scheduled_events / +services.intel.sources.catalysts call). + +Positioning (the operator's own words): "the risk-gated research layer AI +agents trade through." This server is the free, keyless half of that +pitch -- a paid, hosted, metered version is sketched in +docs/design/RESEARCH_MCP_PAID_TIER.md, not built. +""" +from __future__ import annotations + +import json +import os +import sys +import traceback +from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError +from typing import Any, Callable, Dict, List, Optional + +_HERE = os.path.dirname(os.path.abspath(__file__)) +_ROOT = os.path.dirname(os.path.dirname(_HERE)) +if _ROOT not in sys.path: + sys.path.insert(0, _ROOT) + +from services.research_mcp import tools, usage # noqa: E402 +from services.research_mcp.coins import UnsupportedCoinError # noqa: E402 +from services.research_mcp.schemas import TOOLS # noqa: E402 + +SERVER_NAME = "pathiel-research" +# This server's own version (matches services/research_mcp/.claude-plugin/ +# plugin.json), not pathiel.__version__ -- deliberately not importing the +# `pathiel` package at all: it has its own import-time side effects (an SSL +# cert-bundle patch, PATHIA_*/PATHIEL_* environment mirroring) that this +# server has no reason to carry, and importing it would be one more thing +# tests/test_no_trading_imports.py's reviewer has to re-check stays clean. +SERVER_VERSION = "0.1.0" + +SERVER_INSTRUCTIONS = ( + "pathiel research: the risk-gated research layer AI agents trade through. Read-only and " + "keyless -- it never touches an exchange key, an account, an order, or any of pathiel's own " + "trading tools. Six tools: research_brief (one-call summary: levels, next catalysts, top " + "headlines, prediction-market odds, and the latest stored desk thesis if one exists), " + "events, prediction_odds, fred_series (needs your own free FRED_API_KEY), headlines and " + "levels. Supported coins today: BRENTOIL, HYPE, BTC, ETH, SP500 (plus common aliases). " + "Data sources: Hyperliquid public candles, Google News / Yahoo Finance / EIA / " + "Investing.com / oilprice.com / Cointelegraph RSS, Polymarket and Kalshi public markets, " + "FRED (bring your own key), and pathiel's own scheduled-event calendar. See this server's " + "README for attribution and limits. Not financial advice." +) + +# JSON-RPC 2.0 error codes, same values scripts/pathiel-mcp-server.py uses. +_PARSE_ERROR = -32700 +_INVALID_REQUEST = -32600 +_METHOD_NOT_FOUND = -32601 +_INVALID_PARAMS = -32602 + +_SUPPORTED_PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05") + +# A tool result lands in the client model's context; narrow it before this +# backstop fires. Same default and override knob as the trading server. +MAX_OUTPUT_CHARS = int(os.environ.get("PATHIEL_RESEARCH_MCP_MAX_OUTPUT_CHARS", "40000")) + +MAX_CONCURRENT_CALLS = int(os.environ.get("PATHIEL_RESEARCH_MCP_MAX_CONCURRENT", "6")) +DEFAULT_TOOL_TIMEOUT_S = float(os.environ.get("PATHIEL_RESEARCH_MCP_TOOL_TIMEOUT_S", "30")) + + +def _norm_coin(raw: Any) -> str: + return str(raw if raw is not None else "").strip() + + +# name -> (handler(params) -> dict, which params are required strings) +def _handle_research_brief(params: Dict[str, Any]) -> Dict[str, Any]: + return tools.research_brief(_norm_coin(params.get("coin"))) + + +def _handle_events(params: Dict[str, Any]) -> Dict[str, Any]: + coins = params.get("coins") + if coins is not None and not isinstance(coins, list): + raise ValueError("coins must be an array of strings") + days = params.get("days", 7.0) + return tools.events_tool(coins=coins, days=float(days) if days is not None else 7.0) + + +def _handle_prediction_odds(params: Dict[str, Any]) -> Dict[str, Any]: + return tools.prediction_odds_tool(query=params.get("query"), coin=params.get("coin")) + + +def _handle_fred_series(params: Dict[str, Any]) -> Dict[str, Any]: + series_id = params.get("series_id") + if not series_id or not isinstance(series_id, str): + raise ValueError("series_id is required") + return tools.fred_series_tool(series_id, start=params.get("start"), end=params.get("end")) + + +def _handle_headlines(params: Dict[str, Any]) -> Dict[str, Any]: + hours = params.get("hours", 24.0) + return tools.headlines_tool(coin=params.get("coin"), topic=params.get("topic"), + hours=float(hours) if hours is not None else 24.0) + + +def _handle_levels(params: Dict[str, Any]) -> Dict[str, Any]: + return tools.levels_tool(_norm_coin(params.get("coin"))) + + +_HANDLERS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = { + "research_brief": _handle_research_brief, + "events": _handle_events, + "prediction_odds": _handle_prediction_odds, + "fred_series": _handle_fred_series, + "headlines": _handle_headlines, + "levels": _handle_levels, +} + +# Every tool name in schemas.TOOLS must have a handler and vice versa -- +# checked once at import, not per call, so a typo fails loudly at startup. +assert set(_HANDLERS) == {t["name"] for t in TOOLS}, "tool/handler name mismatch" + + +def server_tools() -> List[Dict[str, Any]]: + return TOOLS + + +def _validate_required(name: str, params: Dict[str, Any]) -> Optional[str]: + schema = next((t["inputSchema"] for t in TOOLS if t["name"] == name), None) + if not schema: + return None + for key in schema.get("required") or []: + if not params.get(key): + return f"{name} needs a non-empty {key!r} argument" + return None + + +def _payload_is_error(obj: Dict[str, Any]) -> bool: + return isinstance(obj, dict) and bool(obj.get("error")) + + +def _guard_output(name: str, text: str) -> str: + if MAX_OUTPUT_CHARS <= 0 or len(text) <= MAX_OUTPUT_CHARS: + return text + return json.dumps({ + "truncated": True, "tool": name, "original_chars": len(text), + "hint": "Too large for a model context. Narrow the call (coin, hours, days) and retry.", + "head": text[: MAX_OUTPUT_CHARS // 2], + }) + + +def call_tool(name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: + """Run one tool by name; never raises. Returns the MCP tools/call result + shape: {"content": [...], "isError": bool}. Records one usage. + record_call(name) per invocation, success or failure alike -- a local, + privacy-preserving count of how often each tool is called, nothing + else (see usage.py).""" + if name not in _HANDLERS: + raise KeyError(name) + usage.record_call(name) + arguments = arguments if isinstance(arguments, dict) else {} + missing = _validate_required(name, arguments) + if missing: + payload: Dict[str, Any] = {"error": missing, "tool": name} + else: + try: + payload = _HANDLERS[name](arguments) + except UnsupportedCoinError as exc: + payload = {"error": str(exc), "tool": name} + except (ValueError, RuntimeError) as exc: + payload = {"error": str(exc), "tool": name} + except Exception as exc: # noqa: BLE001 - a tool must never crash the server + traceback.print_exc(file=sys.stderr) + payload = {"error": f"{type(exc).__name__}: {exc}", "tool": name} + text = _guard_output(name, json.dumps(payload, default=str)) + return {"content": [{"type": "text", "text": text}], "isError": _payload_is_error(payload)} + + +def _result_msg(msg_id: Any, result: Dict[str, Any]) -> Dict[str, Any]: + return {"jsonrpc": "2.0", "id": msg_id, "result": result} + + +def _error_msg(msg_id: Any, code: int, message: str) -> Dict[str, Any]: + return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}} + + +def dispatch_message(msg: Any) -> Optional[Dict[str, Any]]: + """One inbound JSON-RPC message -> the response to send, or None for a + notification (no "id"): the MCP spec treats a reply to one as a + protocol violation, so this never sends one.""" + if not isinstance(msg, dict): + return _error_msg(None, _INVALID_REQUEST, "message must be a JSON object") + method = msg.get("method") + if "id" not in msg: + return None + msg_id = msg.get("id") + params = msg.get("params") or {} + if not isinstance(method, str): + return _error_msg(msg_id, _INVALID_REQUEST, "method must be a string") + if not isinstance(params, dict): + return _error_msg(msg_id, _INVALID_PARAMS, "params must be an object") + + if method == "initialize": + asked = params.get("protocolVersion") + version = asked if asked in _SUPPORTED_PROTOCOL_VERSIONS else _SUPPORTED_PROTOCOL_VERSIONS[0] + return _result_msg(msg_id, { + "protocolVersion": version, + "capabilities": {"tools": {}}, + "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION}, + "instructions": SERVER_INSTRUCTIONS, + }) + if method == "ping": + return _result_msg(msg_id, {}) + if method == "tools/list": + return _result_msg(msg_id, {"tools": server_tools()}) + if method == "tools/call": + name = params.get("name") + if not isinstance(name, str) or name not in _HANDLERS: + return _error_msg(msg_id, _INVALID_PARAMS, f"Unknown tool: {name}") + try: + return _result_msg(msg_id, call_tool(name, params.get("arguments") or {})) + except Exception as exc: # noqa: BLE001 - call_tool already catches handler errors; + traceback.print_exc(file=sys.stderr) # this is a last-resort net, e.g. a bad arguments shape. + return _error_msg(msg_id, -32603, f"Internal error: {exc}") + return _error_msg(msg_id, _METHOD_NOT_FOUND, f"Method not found: {method}") + + +_SEND_LOCK = __import__("threading").Lock() +_OUT = None + + +def _out(): + return _OUT if _OUT is not None else sys.stdout + + +def _send(msg: Dict[str, Any]) -> None: + line = json.dumps(msg, default=str) + "\n" + with _SEND_LOCK: + out = _out() + out.write(line) + out.flush() + + +def _timeout_result(name: str, seconds: float) -> Dict[str, Any]: + return {"content": [{"type": "text", "text": json.dumps({ + "error": f"{name} did not finish within {seconds:.0f}s. It may still complete; try again.", + "tool": name, "timed_out": True})}], "isError": True} + + +def _route(msg: Any, pool: ThreadPoolExecutor) -> None: + if not isinstance(msg, dict): + _send(_error_msg(None, _INVALID_REQUEST, "message must be a JSON object")) + return + if "id" not in msg: + return # a notification; nothing to answer, nothing this server needs to act on + method = msg.get("method") + params = msg.get("params") + if method == "tools/call" and isinstance(params, dict): + msg_id = msg.get("id") + name = params.get("name") + + def work() -> None: + try: + response = _result_msg(msg_id, call_tool(name, params.get("arguments") or {})) + except KeyError: + response = _error_msg(msg_id, _INVALID_PARAMS, f"Unknown tool: {name}") + except Exception as exc: # noqa: BLE001 + traceback.print_exc(file=sys.stderr) + response = _error_msg(msg_id, -32603, f"Internal error: {exc}") + _send(response) + + if not isinstance(name, str) or name not in _HANDLERS: + _send(_error_msg(msg_id, _INVALID_PARAMS, f"Unknown tool: {name}")) + return + fut = pool.submit(work) + try: + fut.result(timeout=DEFAULT_TOOL_TIMEOUT_S) + except FutureTimeoutError: + # work() still runs in the background and will send its own + # answer when done; this just stops the main loop waiting on it. + # A client that already got this timeout result and later + # receives the real one simply ignores the second message with + # the same id -- the MCP spec allows at most one reply per id, + # it does not forbid a late extra one being disregarded. + _send(_result_msg(msg_id, _timeout_result(name, DEFAULT_TOOL_TIMEOUT_S))) + return + try: + response = dispatch_message(msg) + except Exception as exc: # noqa: BLE001 + traceback.print_exc(file=sys.stderr) + response = _error_msg(msg.get("id"), -32603, f"Internal error: {exc}") + if response is not None: + _send(response) + + +def run() -> None: + """stdio loop: read one JSON-RPC message per line from stdin, dispatch, + write one line per response to stdout. stdout is the protocol channel + -- nothing else may write to it, so this redirects the real stdout to + the protocol writer and points sys.stdout at stderr for anything else + (a stray print, a library banner) that would otherwise corrupt the + stream, same discipline scripts/pathiel-mcp-server.py uses.""" + global _OUT + _OUT = sys.stdout + sys.stdout = sys.stderr + pool = ThreadPoolExecutor(max_workers=max(1, MAX_CONCURRENT_CALLS), + thread_name_prefix="research-mcp-tool") + try: + while True: + line = sys.stdin.readline() + if not line: + break + if not line.strip(): + continue + try: + msg = json.loads(line) + except json.JSONDecodeError as exc: + _send(_error_msg(None, _PARSE_ERROR, f"Parse error: {exc}")) + continue + _route(msg, pool) + finally: + pool.shutdown(wait=False, cancel_futures=True) + + +def main() -> None: + run() + + +if __name__ == "__main__": + main() + sys.stderr.flush() + os._exit(0) diff --git a/services/research_mcp/state.py b/services/research_mcp/state.py new file mode 100644 index 00000000..08b8c4f9 --- /dev/null +++ b/services/research_mcp/state.py @@ -0,0 +1,32 @@ +"""Where the research MCP writes its own (tiny, non-secret) local state: the +usage counter (usage.py). + +Deliberately its own directory, never `~/.pathiel` (CLAUDE.md's hard rule +for this server: "never open .env.local or ~/.pathiel") and never the +trading server's `PATHIEL_STATE_DIR` -- this process has no business reading +or writing anything under either, keys included, and keeping the directory +separate is what makes that true by construction rather than by care at +every call site. + +`PATHIEL_RESEARCH_STATE_DIR` wins when set (worktrees, tests, a container). +Otherwise `~/.pathiel-research/state` -- a sibling of `~/.pathiel`, not a +subdirectory of it, so a trading install and a research install on the same +machine never collide and neither can read the other's directory by a +relative-path mistake. +""" +from __future__ import annotations + +import os + +ENV_STATE_DIR = "PATHIEL_RESEARCH_STATE_DIR" +_DEFAULT_HOME = os.path.join(os.path.expanduser("~"), ".pathiel-research") + + +def state_dir() -> str: + """The directory this process may read/write its own state under. + Created on first use by whoever writes into it (usage.py); this + function itself never touches the filesystem.""" + configured = os.environ.get(ENV_STATE_DIR) + if configured: + return configured + return os.path.join(_DEFAULT_HOME, "state") diff --git a/services/research_mcp/tests/__init__.py b/services/research_mcp/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/services/research_mcp/tests/conftest.py b/services/research_mcp/tests/conftest.py new file mode 100644 index 00000000..0e2ea703 --- /dev/null +++ b/services/research_mcp/tests/conftest.py @@ -0,0 +1,16 @@ +"""Shared fixtures for services/research_mcp's test suite. + +Every test gets an isolated PATHIEL_RESEARCH_STATE_DIR (a fresh tmp_path) -- +never this machine's real ~/.pathiel-research, same discipline services/ +intel/tests/conftest.py uses for PATHIEL_STATE_DIR. Autouse so a test can't +accidentally skip it and touch real state. +""" +from __future__ import annotations + +import pytest + + +@pytest.fixture(autouse=True) +def isolated_research_state_dir(tmp_path, monkeypatch): + monkeypatch.setenv("PATHIEL_RESEARCH_STATE_DIR", str(tmp_path / "research-state")) + yield tmp_path diff --git a/services/research_mcp/tests/test_coins.py b/services/research_mcp/tests/test_coins.py new file mode 100644 index 00000000..b3d9563b --- /dev/null +++ b/services/research_mcp/tests/test_coins.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +import pytest + +from contracts.strategies.models import DeskSpec +from services.research_mcp import coins + + +def test_supported_coins_lists_exactly_the_brief(): + assert coins.SUPPORTED_COINS == ["xyz:BRENTOIL", "HYPE", "BTC", "ETH", "xyz:SP500"] + + +@pytest.mark.parametrize("raw, expected", [ + ("BRENTOIL", "xyz:BRENTOIL"), ("brentoil", "xyz:BRENTOIL"), ("xyz:BRENTOIL", "xyz:BRENTOIL"), + ("brent", "xyz:BRENTOIL"), ("oil", "xyz:BRENTOIL"), (" OIL ", "xyz:BRENTOIL"), + ("HYPE", "HYPE"), ("hype", "HYPE"), ("hyperliquid", "HYPE"), + ("BTC", "BTC"), ("btc", "BTC"), ("bitcoin", "BTC"), + ("ETH", "ETH"), ("eth", "ETH"), ("ethereum", "ETH"), + ("SP500", "xyz:SP500"), ("sp500", "xyz:SP500"), ("xyz:SP500", "xyz:SP500"), + ("S&P500", "xyz:SP500"), ("S&P 500", "xyz:SP500"), ("spx", "xyz:SP500"), +]) +def test_canonical_coin_accepts_every_documented_alias(raw, expected): + assert coins.canonical_coin(raw) == expected + + +@pytest.mark.parametrize("raw", ["", "SOL", "DOGE", "xyz:GOLD", "not-a-coin", None]) +def test_canonical_coin_rejects_unsupported_input(raw): + with pytest.raises(coins.UnsupportedCoinError) as exc_info: + coins.canonical_coin(raw) + msg = str(exc_info.value) + assert "xyz:BRENTOIL" in msg and "HYPE" in msg # the supported list is in the error + + +def test_desk_id_for_maps_each_coin(): + assert coins.desk_id_for("xyz:BRENTOIL") == "oil" + assert coins.desk_id_for("HYPE") == "hype" + assert coins.desk_id_for("BTC") == "btc" + assert coins.desk_id_for("ETH") == "top5" + assert coins.desk_id_for("xyz:SP500") == "sp500" + + +def test_desk_spec_for_returns_a_valid_spec_naming_the_coin(): + for raw in coins.SUPPORTED_COINS: + spec = coins.desk_spec_for(raw) + assert isinstance(spec, DeskSpec) + desk_coins = {i.coin for i in spec.instruments} + canon = coins.canonical_coin(raw) + assert canon in desk_coins, f"{canon} missing from its own desk's instruments: {desk_coins}" + + +def test_desk_spec_for_is_a_fresh_pure_build_every_call(): + """Two calls return equal but distinct objects -- no shared mutable + state a caller could accidentally corrupt for the next one.""" + a = coins.desk_spec_for("BTC") + b = coins.desk_spec_for("BTC") + assert a == b + assert a is not b diff --git a/services/research_mcp/tests/test_concurrent.py b/services/research_mcp/tests/test_concurrent.py new file mode 100644 index 00000000..45f31ef1 --- /dev/null +++ b/services/research_mcp/tests/test_concurrent.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import time + +from services.research_mcp.concurrent import fetch_many + + +def test_empty_list_returns_empty(): + assert fetch_many([]) == ([], []) + + +def test_items_from_every_call_are_concatenated(): + items, errors = fetch_many([lambda: ([1, 2], None), lambda: ([3], None)]) + assert sorted(items) == [1, 2, 3] + assert errors == [] + + +def test_an_error_string_is_collected_and_its_items_are_not_lost(): + items, errors = fetch_many([lambda: ([1], None), lambda: ([], "source_b:timeout")]) + assert items == [1] + assert errors == ["source_b:timeout"] + + +def test_a_raising_call_is_reported_not_propagated(): + def boom(): + raise RuntimeError("kaboom") + items, errors = fetch_many([lambda: ([1], None), boom]) + assert items == [1] + assert len(errors) == 1 and "RuntimeError" in errors[0] + + +def test_a_slow_call_past_the_deadline_is_reported_as_timed_out(): + def slow(): + time.sleep(1.0) + return ([99], None) + items, errors = fetch_many([lambda: ([1], None), slow], deadline_s=0.05) + assert items == [1] + assert len(errors) == 1 and "timeout_budget_exceeded" in errors[0] + + +def test_a_call_returning_no_items_contributes_nothing_but_no_error(): + items, errors = fetch_many([lambda: ([], None)]) + assert items == [] and errors == [] diff --git a/services/research_mcp/tests/test_no_trading_imports.py b/services/research_mcp/tests/test_no_trading_imports.py new file mode 100644 index 00000000..829e96ae --- /dev/null +++ b/services/research_mcp/tests/test_no_trading_imports.py @@ -0,0 +1,146 @@ +"""The hard gate: the research MCP never imports order-placement or signing +code, and never touches .env.local / ~/.pathiel. + +Two independent checks, because either one alone can be fooled: + 1. STATIC: parse every .py file under services/research_mcp/ (this + server's own code, including its scripts/ entrypoint and its evals) + with `ast`, and fail if any import statement names a forbidden module. + Catches a forbidden import even if nothing ever calls it. + 2. DYNAMIC: in a FRESH subprocess (so another test file's own imports + earlier in this same pytest session can't taint the answer), import + only services.research_mcp.server and check sys.modules afterward. + Catches a forbidden import that static parsing missed because it + arrived transitively through a module this static check doesn't walk + into (a third-party package, for instance). +""" +from __future__ import annotations + +import ast +import subprocess +import sys +from pathlib import Path + +RESEARCH_MCP_DIR = Path(__file__).resolve().parents[1] +REPO_ROOT = RESEARCH_MCP_DIR.parents[1] +ENTRYPOINT = REPO_ROOT / "scripts" / "pathiel-research-mcp.py" +LAUNCHER = REPO_ROOT / "scripts" / "pathiel-research-mcp.sh" + +# Modules that place, close, size, sign or otherwise act on a real order or +# account. Matched as an exact module or any of its submodules (a/b.py +# importing "a" or "a.b" or "a.b.c" all count). +FORBIDDEN_MODULES = ( + "pathiel.agents.bracket", # place_bracket/close_position/set_stop/set_target/sweep + "pathiel.agents.executor", # the retired autonomous scan/research/execute engine + "pathiel.client.exchange", # Hyperliquid order signing + submission + "services.strategies.next_trade", # imports pathiel.agents.bracket at module level + "scripts.pathiel-mcp-server", # the trading MCP server itself (not a valid module name, + # listed for completeness; see the filename check below) + "eth_account", # wallet signing + "hyperliquid.exchange", # the Hyperliquid SDK's own order-submission module +) + +# Every .py file this server ships, including its own tests and evals (an +# eval that imported order code would be just as bad as the server doing it). +PY_FILES = sorted(RESEARCH_MCP_DIR.rglob("*.py")) + [ENTRYPOINT] + + +def _imported_modules(path: Path) -> set: + tree = ast.parse(path.read_text(), filename=str(path)) + names = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.module: + names.add(node.module) + return names + + +def _is_forbidden(module_name: str) -> bool: + return any(module_name == f or module_name.startswith(f + ".") for f in FORBIDDEN_MODULES) + + +def test_every_shipped_file_exists_and_is_parseable(): + assert ENTRYPOINT.is_file(), "scripts/pathiel-research-mcp.py must exist" + assert LAUNCHER.is_file(), "scripts/pathiel-research-mcp.sh must exist" + assert len(PY_FILES) > 5, "expected more than the entrypoint alone under services/research_mcp/" + + +def test_static_no_file_imports_order_or_signing_code(): + offenders = [] + for path in PY_FILES: + for name in _imported_modules(path): + if _is_forbidden(name): + offenders.append(f"{path.relative_to(REPO_ROOT)} imports {name!r}") + assert not offenders, "forbidden import(s):\n " + "\n ".join(offenders) + + +def test_launcher_execs_the_research_entrypoint_not_the_trading_one(): + """The launcher must exec scripts/pathiel-research-mcp.py, never the + trading server's scripts/pathiel-mcp-server.py.""" + exec_lines = [ln for ln in LAUNCHER.read_text().splitlines() if ln.strip().startswith("exec ")] + assert exec_lines, "pathiel-research-mcp.sh has no exec line" + assert all("pathiel-research-mcp.py" in ln for ln in exec_lines) + assert all("pathiel-mcp-server.py" not in ln for ln in exec_lines) + + +def _code_lines(path: Path) -> str: + """A shell script's lines with full-line '#' comments removed, so a + CODE check isn't fooled by this file's own comments explaining what it + deliberately does NOT do (which necessarily name the forbidden things + by name).""" + return "\n".join(ln for ln in path.read_text().splitlines() if not ln.strip().startswith("#")) + + +def test_launcher_shell_script_has_no_operational_env_local_or_pathiel_home_reference(): + code = _code_lines(LAUNCHER) + assert ".env.local" not in code + assert "PATHIEL_HOME" not in code + assert "source" not in code.lower() # never sources another env file + + +def test_dynamic_fresh_process_never_loads_a_forbidden_module(): + """Import ONLY services.research_mcp.server in a brand-new interpreter + and list which of sys.modules' keys are forbidden -- isolated from + whatever else this pytest session has already imported.""" + code = ( + "import sys, json\n" + f"sys.path.insert(0, {str(REPO_ROOT)!r})\n" + "from services.research_mcp import server\n" + f"forbidden = {FORBIDDEN_MODULES!r}\n" + "hits = [m for m in sys.modules if any(m == f or m.startswith(f + '.') for f in forbidden)]\n" + "print(json.dumps(hits))\n" + ) + proc = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=30, + cwd=str(REPO_ROOT)) + assert proc.returncode == 0, f"import failed:\n{proc.stderr}" + hits = ast_literal(proc.stdout.strip()) + assert hits == [], f"forbidden module(s) loaded by a fresh import: {hits}" + + +def ast_literal(s: str): + import json + return json.loads(s) + + +def test_dynamic_fresh_process_never_opens_env_local_or_pathiel_home(): + """A fresh import of services.research_mcp.server must not create or + read anything under ~/.pathiel, and must not read the repo's own + .env.local. Proven by monkeypatching open() in the subprocess to raise + on any path containing either string, then importing the server.""" + code = ( + "import builtins, sys\n" + f"sys.path.insert(0, {str(REPO_ROOT)!r})\n" + "real_open = builtins.open\n" + "def guarded_open(path, *a, **kw):\n" + " p = str(path)\n" + " if '.env.local' in p or '.pathiel/' in p or p.endswith('/.pathiel'):\n" + " raise AssertionError('research MCP import touched ' + p)\n" + " return real_open(path, *a, **kw)\n" + "builtins.open = guarded_open\n" + "from services.research_mcp import server\n" + "print('ok')\n" + ) + proc = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=30, + cwd=str(REPO_ROOT)) + assert proc.returncode == 0 and "ok" in proc.stdout, ( + f"import touched a forbidden path:\nstdout={proc.stdout}\nstderr={proc.stderr}") diff --git a/services/research_mcp/tests/test_schemas.py b/services/research_mcp/tests/test_schemas.py new file mode 100644 index 00000000..318f1993 --- /dev/null +++ b/services/research_mcp/tests/test_schemas.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +from services.research_mcp.schemas import TOOL_NAMES, TOOLS + +EXPECTED_NAMES = {"research_brief", "events", "prediction_odds", "fred_series", "headlines", "levels"} + + +def test_tool_names_match_the_brief(): + assert set(TOOL_NAMES) == EXPECTED_NAMES + assert len(TOOL_NAMES) == len(set(TOOL_NAMES)), "no duplicate tool names" + + +def test_every_tool_has_a_name_description_and_input_schema(): + for tool in TOOLS: + assert isinstance(tool["name"], str) and tool["name"] + assert isinstance(tool["description"], str) and len(tool["description"]) > 20 + schema = tool["inputSchema"] + assert schema["type"] == "object" + assert isinstance(schema["properties"], dict) + + +def test_required_coin_tools_mark_coin_required(): + for name in ("research_brief", "levels"): + schema = next(t["inputSchema"] for t in TOOLS if t["name"] == name) + assert schema.get("required") == ["coin"] + + +def test_fred_series_requires_series_id_only(): + schema = next(t["inputSchema"] for t in TOOLS if t["name"] == "fred_series") + assert schema.get("required") == ["series_id"] + assert "start" in schema["properties"] and "end" in schema["properties"] + + +def test_neither_coin_only_tools_requires_either_argument(): + """prediction_odds and headlines accept coin OR a free-text alternative; + neither is individually required at the schema level (the tool itself + raises a clear error if both are missing -- see test_tools_*.py).""" + for name in ("prediction_odds", "headlines"): + schema = next(t["inputSchema"] for t in TOOLS if t["name"] == name) + assert not schema.get("required") + + +def test_no_tool_description_mentions_a_trading_action(): + banned = ("place_bracket", "close_position", "set_stop", "set_target", "cancel_order", + "sweep_brackets", "set_leverage") + for tool in TOOLS: + text = tool["description"].lower() + for word in banned: + assert word not in text, f"{tool['name']}'s description mentions {word!r}" diff --git a/services/research_mcp/tests/test_server_dispatch.py b/services/research_mcp/tests/test_server_dispatch.py new file mode 100644 index 00000000..bb576542 --- /dev/null +++ b/services/research_mcp/tests/test_server_dispatch.py @@ -0,0 +1,198 @@ +"""services/research_mcp/server.py: the JSON-RPC dispatch (initialize, +tools/list, tools/call, ping, unknown method/tool, bad params) and the +concurrent _route() path used by run()'s stdio loop.""" +from __future__ import annotations + +import json +import time + +from services.research_mcp import server, usage +from services.research_mcp.schemas import TOOL_NAMES + + +def test_initialize_returns_server_info_and_instructions(): + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18"}}) + result = resp["result"] + assert result["protocolVersion"] == "2025-06-18" + assert result["serverInfo"]["name"] == "pathiel-research" + assert "research-gated" not in result["instructions"] # sanity: not garbled + assert "Read-only" in result["instructions"] and "keyless" in result["instructions"] + + +def test_initialize_falls_back_to_the_newest_version_for_an_unknown_ask(): + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "1999-01-01"}}) + assert resp["result"]["protocolVersion"] == server._SUPPORTED_PROTOCOL_VERSIONS[0] + + +def test_ping(): + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 2, "method": "ping"}) + assert resp == {"jsonrpc": "2.0", "id": 2, "result": {}} + + +def test_tools_list_matches_the_schema_module(): + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 3, "method": "tools/list"}) + names = {t["name"] for t in resp["result"]["tools"]} + assert names == set(TOOL_NAMES) + + +def test_notification_gets_no_response(): + assert server.dispatch_message({"jsonrpc": "2.0", "method": "notifications/initialized"}) is None + + +def test_unknown_method_is_method_not_found(): + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 4, "method": "bogus/method"}) + assert resp["error"]["code"] == server._METHOD_NOT_FOUND + + +def test_malformed_message_is_invalid_request(): + assert server.dispatch_message("not a dict")["error"]["code"] == server._INVALID_REQUEST + assert server.dispatch_message({"id": 1, "method": 7})["error"]["code"] == server._INVALID_REQUEST + assert server.dispatch_message({"id": 1, "method": "x", "params": "nope"})["error"]["code"] == server._INVALID_PARAMS + + +def test_tools_call_unknown_tool_is_invalid_params(): + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 5, "method": "tools/call", + "params": {"name": "place_bracket", "arguments": {}}}) + assert resp["error"]["code"] == server._INVALID_PARAMS + + +def test_tools_call_happy_path(monkeypatch): + from services.research_mcp import tools + monkeypatch.setattr(tools, "levels_tool", lambda coin: {"coin": coin, "mid": 42.0}) + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 6, "method": "tools/call", + "params": {"name": "levels", "arguments": {"coin": "BTC"}}}) + result = resp["result"] + assert result["isError"] is False + payload = json.loads(result["content"][0]["text"]) + assert payload == {"coin": "BTC", "mid": 42.0} + + +def test_tools_call_missing_required_argument_is_a_clean_tool_error(monkeypatch): + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 7, "method": "tools/call", + "params": {"name": "levels", "arguments": {}}}) + result = resp["result"] + assert result["isError"] is True + payload = json.loads(result["content"][0]["text"]) + assert "coin" in payload["error"] + + +def test_tools_call_a_raising_handler_becomes_a_clean_error_not_a_crash(monkeypatch): + from services.research_mcp import tools + + def boom(coin): + raise RuntimeError("venue is down") + monkeypatch.setattr(tools, "levels_tool", boom) + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 8, "method": "tools/call", + "params": {"name": "levels", "arguments": {"coin": "BTC"}}}) + result = resp["result"] + assert result["isError"] is True + payload = json.loads(result["content"][0]["text"]) + assert "venue is down" in payload["error"] + + +def test_tools_call_an_unsupported_coin_is_a_clean_tool_error_not_a_500(): + resp = server.dispatch_message({"jsonrpc": "2.0", "id": 9, "method": "tools/call", + "params": {"name": "levels", "arguments": {"coin": "DOGE"}}}) + result = resp["result"] + assert result["isError"] is True + payload = json.loads(result["content"][0]["text"]) + assert "DOGE" in payload["error"] + + +def test_call_tool_records_one_usage_call_per_invocation(tmp_path, monkeypatch): + monkeypatch.setenv("PATHIEL_RESEARCH_STATE_DIR", str(tmp_path)) + from services.research_mcp import tools + monkeypatch.setattr(tools, "levels_tool", lambda coin: {"coin": coin}) + server.call_tool("levels", {"coin": "BTC"}) + server.call_tool("levels", {"coin": "ETH"}) + data = usage.read_usage() + assert data["levels"]["calls"] == 2 + + +def test_call_tool_records_usage_even_on_error(tmp_path, monkeypatch): + monkeypatch.setenv("PATHIEL_RESEARCH_STATE_DIR", str(tmp_path)) + server.call_tool("levels", {}) # missing coin -> clean error, still counted + assert usage.read_usage()["levels"]["calls"] == 1 + + +def test_guard_output_passes_small_payloads_through(): + assert server._guard_output("levels", "small") == "small" + + +def test_guard_output_truncates_oversized_payloads(monkeypatch): + monkeypatch.setattr(server, "MAX_OUTPUT_CHARS", 20) + out = server._guard_output("levels", "x" * 100) + payload = json.loads(out) + assert payload["truncated"] is True and payload["tool"] == "levels" + + +def test_payload_is_error(): + assert server._payload_is_error({"error": "nope"}) is True + assert server._payload_is_error({"coin": "BTC"}) is False + assert server._payload_is_error({"error": None}) is False + + +def test_handler_registry_matches_the_schema_exactly(): + assert set(server._HANDLERS) == set(TOOL_NAMES) + + +# ── _route(): the concurrent stdio-loop path ──────────────────────────────── + +def test_route_sends_exactly_one_response_for_a_tools_call(monkeypatch): + from concurrent.futures import ThreadPoolExecutor + from services.research_mcp import tools + monkeypatch.setattr(tools, "levels_tool", lambda coin: {"coin": coin}) + sent = [] + monkeypatch.setattr(server, "_send", sent.append) + pool = ThreadPoolExecutor(max_workers=2) + try: + server._route({"jsonrpc": "2.0", "id": "r1", "method": "tools/call", + "params": {"name": "levels", "arguments": {"coin": "BTC"}}}, pool) + finally: + pool.shutdown(wait=True) + assert len(sent) == 1 + assert sent[0]["id"] == "r1" + assert json.loads(sent[0]["result"]["content"][0]["text"]) == {"coin": "BTC"} + + +def test_route_times_out_a_slow_tool_without_blocking_forever(monkeypatch): + from concurrent.futures import ThreadPoolExecutor + from services.research_mcp import tools + monkeypatch.setattr(server, "DEFAULT_TOOL_TIMEOUT_S", 0.05) + + def slow(coin): + time.sleep(0.5) + return {"coin": coin} + monkeypatch.setattr(tools, "levels_tool", slow) + sent = [] + monkeypatch.setattr(server, "_send", sent.append) + pool = ThreadPoolExecutor(max_workers=2) + try: + start = time.monotonic() + server._route({"jsonrpc": "2.0", "id": "r2", "method": "tools/call", + "params": {"name": "levels", "arguments": {"coin": "BTC"}}}, pool) + elapsed = time.monotonic() - start + # Drain the still-running straggler INSIDE this test, while _send is + # still monkeypatched, so its late real answer lands in `sent` + # instead of printing to the real stdout after teardown. + time.sleep(0.6) + finally: + pool.shutdown(wait=True) + assert elapsed < 0.4, "the timeout must bound _route's own wait, not the slow handler's sleep" + assert len(sent) == 2, "the timeout message, then the late real answer when the handler finishes" + timeout_payload = json.loads(sent[0]["result"]["content"][0]["text"]) + assert timeout_payload["timed_out"] is True + late_payload = json.loads(sent[1]["result"]["content"][0]["text"]) + assert late_payload == {"coin": "BTC"} + + +def test_route_ignores_a_bare_notification(): + sent_calls = [] + + class _Pool: + def submit(self, fn): + sent_calls.append(fn) + server._route({"jsonrpc": "2.0", "method": "notifications/cancelled"}, _Pool()) + assert sent_calls == [] diff --git a/services/research_mcp/tests/test_state.py b/services/research_mcp/tests/test_state.py new file mode 100644 index 00000000..2c568681 --- /dev/null +++ b/services/research_mcp/tests/test_state.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +import os + +from services.research_mcp import state + + +def test_env_override_wins(monkeypatch, tmp_path): + monkeypatch.setenv(state.ENV_STATE_DIR, str(tmp_path / "custom")) + assert state.state_dir() == str(tmp_path / "custom") + + +def test_default_is_a_sibling_of_pathiel_home_not_inside_it(monkeypatch): + monkeypatch.delenv(state.ENV_STATE_DIR, raising=False) + d = state.state_dir() + home = os.path.expanduser("~") + assert d.startswith(os.path.join(home, ".pathiel-research")) + assert os.path.join(home, ".pathiel", "") not in (d + os.sep) + assert d != os.path.join(home, ".pathiel") + + +def test_state_dir_never_touches_the_filesystem(monkeypatch, tmp_path): + """state_dir() only computes a path string; it must not create the + directory or any file as a side effect.""" + target = tmp_path / "never-created" + monkeypatch.setenv(state.ENV_STATE_DIR, str(target)) + state.state_dir() + assert not target.exists() diff --git a/services/research_mcp/tests/test_tools_events.py b/services/research_mcp/tests/test_tools_events.py new file mode 100644 index 00000000..f3ee8f9e --- /dev/null +++ b/services/research_mcp/tests/test_tools_events.py @@ -0,0 +1,69 @@ +"""services/research_mcp/tools.py: events_tool / scheduled_calendar. + +All offline: calendar_catalysts/scheduled_events read the repo's checked-in +services/intel/data/scheduled_events.json, no network. The use_overlay=False +plumbing itself is proven separately in services/intel/tests/ +test_scheduled_events.py and test_sources_catalysts.py; these tests cover +this tool's own composition and coin handling. +""" +from __future__ import annotations + +from datetime import datetime, timezone + +from services.research_mcp import tools + + +def test_events_tool_default_covers_every_supported_coin(): + out = tools.events_tool(days=3) + assert set(out["coins"]) == {"xyz:BRENTOIL", "HYPE", "BTC", "ETH", "xyz:SP500"} + assert out["sources_failed"] == [] + + +def test_oil_metals_sp500_hype_coins_get_the_curated_calendar(): + out = tools.events_tool(coins=["BRENTOIL"], days=30) + row = out["coins"]["xyz:BRENTOIL"] + assert "note" not in row + assert isinstance(row["events"], list) + # active_blackout is either None or a dict with the blackout shape; just + # prove the key exists and the call didn't blow up building it. + assert "active_blackout" in row + + +def test_btc_eth_have_no_curated_calendar_group_but_get_a_clear_note(): + out = tools.events_tool(coins=["BTC", "ETH"], days=7) + for coin in ("BTC", "ETH"): + row = out["coins"][coin] + assert row["events"] == [] + assert row["active_blackout"] is None + assert "note" in row and "oil/metals/sp500/hype" in row["note"] + + +def test_an_unsupported_coin_is_reported_not_raised(): + out = tools.events_tool(coins=["BTC", "DOGE"]) + assert "BTC" in out["coins"] + assert "DOGE" not in out["coins"] + assert len(out["sources_failed"]) == 1 and "DOGE" in out["sources_failed"][0] + + +def test_days_is_clamped_to_a_sane_range(): + assert tools.events_tool(coins=["BTC"], days=0)["window_days"] == 1.0 + assert tools.events_tool(coins=["BTC"], days=10_000)["window_days"] == 60.0 + assert tools.events_tool(coins=["BTC"], days=None)["window_days"] == 7.0 + + +def test_coin_aliases_are_normalized_to_the_canonical_key(): + out = tools.events_tool(coins=["brent", "bitcoin"]) + assert set(out["coins"]) == {"xyz:BRENTOIL", "BTC"} + + +def test_scheduled_calendar_curated_coin_uses_use_overlay_false(monkeypatch): + """Pins that this tool goes through the keyless-safe path: a direct + sanity check that env.state_dir() is never reached for a curated coin.""" + from services.intel import env + + def _boom(*a, **kw): + raise AssertionError("env.state_dir() must not be called") + monkeypatch.setattr(env, "state_dir", _boom) + now = datetime(2026, 11, 20, tzinfo=timezone.utc) + row = tools.scheduled_calendar("xyz:BRENTOIL", now, days=7) + assert isinstance(row["events"], list) diff --git a/services/research_mcp/tests/test_tools_fred.py b/services/research_mcp/tests/test_tools_fred.py new file mode 100644 index 00000000..2bf7b7e3 --- /dev/null +++ b/services/research_mcp/tests/test_tools_fred.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from services.intel import http_client +from services.research_mcp import tools + + +def test_fred_series_tool_refuses_cleanly_without_a_key(monkeypatch): + monkeypatch.delenv("FRED_API_KEY", raising=False) + out = tools.fred_series_tool("DGS10") + assert out["error"] == "FRED_API_KEY_missing" + assert "fred.stlouisfed.org" in out["help"] + assert "api_key.html" in out["help"] + + +def test_fred_series_tool_never_logs_the_key(monkeypatch, capsys): + monkeypatch.setenv("FRED_API_KEY", "super-secret-key-value") + monkeypatch.setattr(http_client, "fetch_json", + lambda url, **kw: ({"observations": [{"date": "2026-01-02", "value": "4.1"}]}, None)) + tools.fred_series_tool("DGS10") + captured = capsys.readouterr() + assert "super-secret-key-value" not in captured.out + assert "super-secret-key-value" not in captured.err + + +def test_fred_series_tool_happy_path(monkeypatch): + monkeypatch.setenv("FRED_API_KEY", "fake-key") + monkeypatch.setattr(http_client, "fetch_json", + lambda url, **kw: ({"observations": [ + {"date": "2026-01-02", "value": "4.10"}, + {"date": "2026-01-05", "value": "4.12"}, + ]}, None)) + out = tools.fred_series_tool("DGS10", start="2026-01-01", end="2026-02-01") + assert out["series_id"] == "DGS10" + assert out["start"] == "2026-01-01" and out["end"] == "2026-02-01" + assert len(out["observations"]) == 2 + assert "error" not in out + + +def test_fred_series_tool_surfaces_a_non_key_error(monkeypatch): + monkeypatch.setenv("FRED_API_KEY", "fake-key") + monkeypatch.setattr(http_client, "fetch_json", lambda url, **kw: (None, "timeout")) + out = tools.fred_series_tool("DGS10") + assert out["error"] == "timeout" + assert out["series_id"] == "DGS10" + + +def test_fred_series_tool_surfaces_a_bad_response_shape(monkeypatch): + monkeypatch.setenv("FRED_API_KEY", "fake-key") + monkeypatch.setattr(http_client, "fetch_json", lambda url, **kw: ({"nope": True}, None)) + out = tools.fred_series_tool("DGS10") + assert out["error"] == "bad_shape" diff --git a/services/research_mcp/tests/test_tools_headlines.py b/services/research_mcp/tests/test_tools_headlines.py new file mode 100644 index 00000000..8f33f3e0 --- /dev/null +++ b/services/research_mcp/tests/test_tools_headlines.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +import pytest + +from contracts.strategies.models import Headline +from services.research_mcp import tools + +NOW = datetime(2026, 11, 20, 12, 0, tzinfo=timezone.utc) + + +class _FixedDatetime(datetime): + @classmethod + def now(cls, tz=None): + return NOW + + +@pytest.fixture(autouse=True) +def _frozen_now(monkeypatch): + """Every test here reasons about headline ages relative to NOW, not + whatever today's real wall-clock date happens to be.""" + monkeypatch.setattr(tools, "datetime", _FixedDatetime) + + +def _headline(id_, title, published_at, relevance=0.5): + return Headline(id=id_, title=title, url="https://example.com/" + id_, source="Test", + published_at=published_at, relevance=relevance) + + +def test_headlines_tool_needs_coin_or_topic(): + with pytest.raises(ValueError): + tools.headlines_tool() + + +def test_headlines_tool_by_coin(monkeypatch): + rows = [_headline("a", "Brent news", NOW - timedelta(hours=1))] + monkeypatch.setattr(tools, "fetch_headlines_fast", lambda spec, now, **kw: (rows, [])) + out = tools.headlines_tool(coin="BRENTOIL", hours=24) + assert out["query"] == "xyz:BRENTOIL" + assert out["headlines"][0]["id"] == "a" + + +def test_headlines_tool_by_topic_builds_an_adhoc_spec(monkeypatch): + seen = {} + + def fake(spec, now, **kw): + seen["queries"] = list(spec.news_queries) + return [], [] + monkeypatch.setattr(tools, "fetch_headlines_fast", fake) + out = tools.headlines_tool(topic="OPEC+ meeting") + assert out["query"] == "OPEC+ meeting" + assert seen["queries"] == ["OPEC+ meeting"] + + +def test_headlines_tool_filters_by_hours(monkeypatch): + rows = [ + _headline("fresh", "fresh", NOW - timedelta(hours=1)), + _headline("stale", "stale", NOW - timedelta(hours=48)), + _headline("undated", "undated", None), + ] + monkeypatch.setattr(tools, "fetch_headlines_fast", lambda spec, now, **kw: (rows, [])) + out = tools.headlines_tool(coin="BTC", hours=24) + ids = {h["id"] for h in out["headlines"]} + assert ids == {"fresh", "undated"} # stale dropped, undated kept (can't rule it out) + + +def test_headlines_tool_caps_at_25_and_reports_errors(monkeypatch): + rows = [_headline(str(i), f"h{i}", NOW) for i in range(40)] + monkeypatch.setattr(tools, "fetch_headlines_fast", lambda spec, now, **kw: (rows, ["news:x:timeout"])) + out = tools.headlines_tool(coin="HYPE") + assert len(out["headlines"]) == 25 + assert out["sources_failed"] == ["news:x:timeout"] + + +def test_headlines_tool_resolves_coin_aliases(monkeypatch): + monkeypatch.setattr(tools, "fetch_headlines_fast", lambda spec, now, **kw: ([], [])) + out = tools.headlines_tool(coin="bitcoin") + assert out["query"] == "BTC" diff --git a/services/research_mcp/tests/test_tools_levels.py b/services/research_mcp/tests/test_tools_levels.py new file mode 100644 index 00000000..ceef8ec8 --- /dev/null +++ b/services/research_mcp/tests/test_tools_levels.py @@ -0,0 +1,100 @@ +"""services/research_mcp/tools.py: levels_tool / summarize_levels. + +summarize_levels reimplements services.strategies.levels.summarize()'s math +from its pure exported building blocks instead of calling summarize_coin() +(which would import services.strategies.next_trade -> pathiel.agents.bracket, +order-placement code this server must never import -- see tools.py's +docstring). test_matches_the_real_levels_summarize proves that +reimplementation produces the SAME numbers as the original, field for +field, not just "some numbers that look plausible." +""" +from __future__ import annotations + +import pytest + +from services.research_mcp import coins, tools +from services.strategies import levels as L + +HOUR_MS = L.HOUR_MS + + +def _candle(i: int, close_ms: int, o: float, h: float, lo: float, c: float) -> dict: + return {"t": close_ms - HOUR_MS + 1, "T": close_ms, "o": o, "h": h, "l": lo, "c": c, "v": 10 + i} + + +def _candles_1h(n: int, now_ms: int, base: float = 100.0) -> list: + """n CLOSED 1h candles ending just before now_ms, prices drifting + slightly so ranges and ATR are non-trivial, highest/lowest predictable.""" + out = [] + for i in range(n): + close_ms = now_ms - (n - i) * HOUR_MS + px = base + i * 0.1 + out.append(_candle(i, close_ms, px, px + 1.0 + (i % 5) * 0.2, px - 1.0 - (i % 3) * 0.2, px + 0.05)) + return out + + +def test_summarize_levels_happy_path(monkeypatch): + now_ms = 100 * HOUR_MS + c1h = _candles_1h(50, now_ms) + monkeypatch.setattr(tools, "fetch_mid", lambda coin: 107.5) + monkeypatch.setattr(tools, "fetch_candles", + lambda coin, interval, hours, nm: c1h if interval == "1h" else c1h[-3:]) + out = tools.summarize_levels("xyz:BRENTOIL", now_ms=now_ms) + assert out["coin"] == "xyz:BRENTOIL" + assert out["mid"] == 107.5 + assert out["n_closed_1h"] == 50 + assert out["last_closed_1h"]["close"] == c1h[-1]["c"] + assert out["range_24h"]["high"] == max(c["h"] for c in c1h[-24:]) + assert out["range_24h"]["low"] == min(c["l"] for c in c1h[-24:]) + assert out["atr14_1h"] is not None and out["atr14_1h"] > 0 + assert 0.0 <= out["mid_pos_in_24h"] <= 1.0 or out["mid_pos_in_24h"] < 0 or out["mid_pos_in_24h"] > 1 + assert "breakout_24h" not in out, "must not carry next_trade's breakout field" + assert "closes_1h" not in out, "must not carry next_trade's trend-gate field" + + +def test_summarize_levels_matches_the_real_levels_summarize(monkeypatch): + """Field-for-field equality against services.strategies.levels.summarize() + on the SAME candle data, for every field both compute.""" + now_ms = 200 * HOUR_MS + c1h = _candles_1h(60, now_ms, base=4000.0) + c15 = [_candle(i, now_ms - (3 - i) * 900_000, 4000, 4001, 3999, 4000.5) for i in range(3)] + + real = L.summarize(c1h, c15, mid=4005.0, now_ms=now_ms) + monkeypatch.setattr(tools, "fetch_mid", lambda coin: 4005.0) + monkeypatch.setattr(tools, "fetch_candles", + lambda coin, interval, hours, nm: c1h if interval == "1h" else c15) + mine = tools.summarize_levels("xyz:GOLD", now_ms=now_ms) + + shared_keys = ["mid", "last_closed_1h", "range_8h", "range_24h", "range_48h", "atr14_1h", + "range_15m_last4", "n_closed_1h", "mid_pos_in_24h", "atr14_pct"] + for key in shared_keys: + assert mine.get(key) == real.get(key), f"{key} differs: mine={mine.get(key)} real={real.get(key)}" + + +def test_summarize_levels_raises_a_clear_error_with_no_mid(monkeypatch): + monkeypatch.setattr(tools, "fetch_mid", lambda coin: None) + with pytest.raises(RuntimeError, match="xyz:BRENTOIL"): + tools.summarize_levels("xyz:BRENTOIL") + + +def test_summarize_levels_handles_no_closed_candles_gracefully(monkeypatch): + monkeypatch.setattr(tools, "fetch_mid", lambda coin: 50.0) + monkeypatch.setattr(tools, "fetch_candles", lambda coin, interval, hours, nm: []) + out = tools.summarize_levels("BTC", now_ms=1_000_000) + assert out["n_closed_1h"] == 0 + assert out["last_closed_1h"] is None + assert out["atr14_1h"] is None + assert "mid_pos_in_24h" not in out + assert "atr14_pct" not in out + + +def test_levels_tool_resolves_coin_aliases(monkeypatch): + monkeypatch.setattr(tools, "fetch_mid", lambda coin: 65.0) + monkeypatch.setattr(tools, "fetch_candles", lambda coin, interval, hours, nm: []) + out = tools.levels_tool("hyperliquid") + assert out["coin"] == "HYPE" + + +def test_levels_tool_rejects_an_unsupported_coin(): + with pytest.raises(coins.UnsupportedCoinError): + tools.levels_tool("DOGE") diff --git a/services/research_mcp/tests/test_tools_predictions.py b/services/research_mcp/tests/test_tools_predictions.py new file mode 100644 index 00000000..cb515073 --- /dev/null +++ b/services/research_mcp/tests/test_tools_predictions.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +import pytest + +from contracts.strategies.models import MarketOdds +from services.research_mcp import tools + + +def _odds(id_, prob, vol): + return MarketOdds(id=id_, venue="polymarket", question=f"q {id_}", probability=prob, + volume_usd=vol, url="https://polymarket.com/x") + + +def test_prediction_odds_tool_needs_coin_or_query(): + with pytest.raises(ValueError): + tools.prediction_odds_tool() + + +def test_prediction_odds_tool_by_coin_uses_the_desks_own_queries(monkeypatch): + seen = {} + + def fake_for_spec(spec, **kw): + seen["queries"] = list(spec.prediction_market_queries) + return [_odds("a", 0.6, 100.0)], [] + monkeypatch.setattr(tools, "prediction_odds_for_spec", fake_for_spec) + out = tools.prediction_odds_tool(coin="HYPE") + assert out["query"] == "HYPE" + assert out["odds"][0]["id"] == "a" + assert seen["queries"], "the hype desk's own prediction_market_queries must be used" + + +def test_prediction_odds_tool_by_free_text_query(monkeypatch): + seen = {} + + def fake_for_spec(spec, **kw): + seen["queries"] = list(spec.prediction_market_queries) + seen["instrument_label"] = spec.instruments[0].label + return [], [] + monkeypatch.setattr(tools, "prediction_odds_for_spec", fake_for_spec) + out = tools.prediction_odds_tool(query="Fed rate cut") + assert out["query"] == "Fed rate cut" + assert seen["queries"] == ["Fed rate cut"] + assert seen["instrument_label"] == "Fed rate cut" + + +def test_prediction_odds_for_spec_dedups_and_sorts_by_volume(monkeypatch): + from contracts.strategies.models import DeskSpec, Instrument + spec = DeskSpec(id="tt", name="t", tagline="t", + instruments=[Instrument(coin="BTC", label="BTC", role="primary")]) + poly = [_odds("x", 0.5, 10.0), _odds("y", 0.4, 500.0)] + kalshi = [_odds("x", 0.5, 10.0)] # same id as poly's "x" -- must dedup, not double count + monkeypatch.setattr(tools.predictions_src, "fetch_polymarket", lambda s, **kw: (poly, None)) + monkeypatch.setattr(tools.predictions_src, "fetch_kalshi", lambda s, **kw: (kalshi, None)) + ranked, errors = tools.prediction_odds_for_spec(spec) + assert [o.id for o in ranked] == ["y", "x"] # higher volume first + assert errors == [] + + +def test_prediction_odds_for_spec_collects_source_errors(monkeypatch): + from contracts.strategies.models import DeskSpec, Instrument + spec = DeskSpec(id="tt", name="t", tagline="t", + instruments=[Instrument(coin="BTC", label="BTC", role="primary")]) + monkeypatch.setattr(tools.predictions_src, "fetch_polymarket", lambda s, **kw: ([], "predictions:polymarket:timeout")) + monkeypatch.setattr(tools.predictions_src, "fetch_kalshi", lambda s, **kw: ([_odds("z", 0.3, 1.0)], None)) + ranked, errors = tools.prediction_odds_for_spec(spec) + assert [o.id for o in ranked] == ["z"] + assert errors == ["predictions:polymarket:timeout"] diff --git a/services/research_mcp/tests/test_tools_research_brief.py b/services/research_mcp/tests/test_tools_research_brief.py new file mode 100644 index 00000000..d7d7f7d7 --- /dev/null +++ b/services/research_mcp/tests/test_tools_research_brief.py @@ -0,0 +1,106 @@ +"""services/research_mcp/tools.py: research_brief -- the one-call summary. + +Every data source is mocked at tools.py's own seam (summarize_levels, +upcoming_catalysts, fetch_headlines_fast, prediction_odds_for_spec, +latest_thesis_json); each tool's own happy/error path is covered in its own +test_tools_*.py file. These tests cover research_brief's COMPOSITION: it +must survive any one source failing, serve the stored thesis without +writing a new one, and flag the ETH/top5 special case. +""" +from __future__ import annotations + +from datetime import datetime, timezone + +import pytest + +from contracts.strategies.models import Catalyst, Headline, MarketOdds +from services.research_mcp import coins, tools + +NOW = datetime(2026, 11, 20, 12, 0, tzinfo=timezone.utc) + + +def _mock_all_sources(monkeypatch, *, levels=None, catalysts=None, headlines=None, odds=None, + thesis=None): + monkeypatch.setattr(tools, "summarize_levels", lambda coin, **kw: levels if levels is not None + else {"coin": coin, "mid": 1.0}) + monkeypatch.setattr(tools, "upcoming_catalysts", lambda spec, now, **kw: catalysts or []) + monkeypatch.setattr(tools, "fetch_headlines_fast", lambda spec, now, **kw: (headlines or [], [])) + monkeypatch.setattr(tools, "prediction_odds_for_spec", lambda spec, **kw: (odds or [], [])) + monkeypatch.setattr(tools, "latest_thesis_json", lambda desk_id: thesis) + + +def test_research_brief_happy_path(monkeypatch): + cat = Catalyst(id="c1", kind="fomc", title="FOMC", at=NOW, importance=3, source="Fed") + hl = Headline(id="h1", title="Brent news", url="https://x", source="Test", relevance=0.9) + odd = MarketOdds(id="o1", venue="polymarket", question="q", probability=0.5, + volume_usd=10.0, url="https://x") + _mock_all_sources(monkeypatch, catalysts=[cat], headlines=[hl], odds=[odd], + thesis={"id": "t1", "desk_id": "oil"}) + out = tools.research_brief("BRENTOIL", now=NOW) + assert out["coin"] == "xyz:BRENTOIL" + assert out["desk_id"] == "oil" + assert out["levels"]["mid"] == 1.0 + assert out["catalysts"][0]["id"] == "c1" + assert out["headlines"][0]["id"] == "h1" + assert out["odds"][0]["id"] == "o1" + assert out["thesis"] == {"id": "t1", "desk_id": "oil"} + assert out["note"] is None + assert out["sources_failed"] == [] + + +def test_research_brief_with_no_stored_thesis_is_null_not_an_error(monkeypatch): + _mock_all_sources(monkeypatch, thesis=None) + out = tools.research_brief("HYPE", now=NOW) + assert out["thesis"] is None + assert out["sources_failed"] == [] + + +def test_research_brief_survives_every_source_failing(monkeypatch): + def boom(*a, **kw): + raise RuntimeError("dead source") + monkeypatch.setattr(tools, "summarize_levels", boom) + monkeypatch.setattr(tools, "upcoming_catalysts", boom) + monkeypatch.setattr(tools, "fetch_headlines_fast", boom) + monkeypatch.setattr(tools, "prediction_odds_for_spec", boom) + monkeypatch.setattr(tools, "latest_thesis_json", boom) + out = tools.research_brief("BTC", now=NOW) + assert out["levels"] is None + assert out["catalysts"] == [] + assert out["headlines"] == [] + assert out["odds"] == [] + assert out["thesis"] is None + assert len(out["sources_failed"]) == 5 + assert any("levels:" in e for e in out["sources_failed"]) + assert any("thesis:" in e for e in out["sources_failed"]) + + +def test_research_brief_one_dead_source_does_not_sink_the_others(monkeypatch): + hl = Headline(id="h1", title="t", url="https://x", source="s", relevance=0.5) + + def boom(*a, **kw): + raise RuntimeError("odds API down") + _mock_all_sources(monkeypatch, headlines=[hl]) + monkeypatch.setattr(tools, "prediction_odds_for_spec", boom) + out = tools.research_brief("SP500", now=NOW) + assert out["headlines"][0]["id"] == "h1" + assert out["odds"] == [] + assert out["sources_failed"] == ["odds:odds API down"] + + +def test_research_brief_eth_notes_the_top5_basket_desk(monkeypatch): + _mock_all_sources(monkeypatch) + out = tools.research_brief("ETH", now=NOW) + assert out["desk_id"] == "top5" + assert out["note"] is not None and "top5" in out["note"] and "ETH" in out["note"] + + +def test_research_brief_other_coins_get_no_note(monkeypatch): + _mock_all_sources(monkeypatch) + for coin in ("BRENTOIL", "HYPE", "BTC", "SP500"): + assert tools.research_brief(coin, now=NOW)["note"] is None + + +def test_research_brief_rejects_an_unsupported_coin(monkeypatch): + _mock_all_sources(monkeypatch) + with pytest.raises(coins.UnsupportedCoinError): + tools.research_brief("DOGE", now=NOW) diff --git a/services/research_mcp/tests/test_usage.py b/services/research_mcp/tests/test_usage.py new file mode 100644 index 00000000..dfec6636 --- /dev/null +++ b/services/research_mcp/tests/test_usage.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +import json +import threading +from datetime import datetime, timezone + +from services.research_mcp import usage + + +def test_record_call_creates_the_file_under_the_state_dir(tmp_path): + path = str(tmp_path / "usage.json") + usage.record_call("levels", path=path) + assert (tmp_path / "usage.json").exists() + data = json.loads((tmp_path / "usage.json").read_text()) + assert data["levels"]["calls"] == 1 + + +def test_record_call_increments_and_keeps_first_called_at(tmp_path): + path = str(tmp_path / "usage.json") + t0 = datetime(2026, 11, 20, 10, 0, tzinfo=timezone.utc) + t1 = datetime(2026, 11, 20, 10, 5, tzinfo=timezone.utc) + row1 = usage.record_call("headlines", path=path, now=t0) + row2 = usage.record_call("headlines", path=path, now=t1) + assert row1["calls"] == 1 and row2["calls"] == 2 + assert row2["first_called_at"] == t0.isoformat() + assert row2["last_called_at"] == t1.isoformat() + + +def test_record_call_tracks_each_tool_separately(tmp_path): + path = str(tmp_path / "usage.json") + usage.record_call("levels", path=path) + usage.record_call("levels", path=path) + usage.record_call("events", path=path) + data = usage.read_usage(path) + assert data["levels"]["calls"] == 2 + assert data["events"]["calls"] == 1 + + +def test_read_usage_on_a_missing_file_is_empty_not_an_error(tmp_path): + assert usage.read_usage(str(tmp_path / "nope.json")) == {} + + +def test_record_call_contains_no_arguments_or_identity_fields(tmp_path): + """Privacy-preserving by construction: the row this writes has exactly + three keys, none of which could carry a coin, a query, a result or a + caller identity.""" + path = str(tmp_path / "usage.json") + row = usage.record_call("research_brief", path=path) + assert set(row.keys()) == {"calls", "first_called_at", "last_called_at"} + + +def test_record_call_is_thread_safe_under_concurrent_calls(tmp_path): + path = str(tmp_path / "usage.json") + n_threads, calls_each = 8, 10 + + def hammer(): + for _ in range(calls_each): + usage.record_call("levels", path=path) + + threads = [threading.Thread(target=hammer) for _ in range(n_threads)] + for t in threads: + t.start() + for t in threads: + t.join() + assert usage.read_usage(path)["levels"]["calls"] == n_threads * calls_each + + +def test_usage_path_defaults_to_the_state_dir(monkeypatch, tmp_path): + from services.research_mcp import state + monkeypatch.setenv(state.ENV_STATE_DIR, str(tmp_path)) + assert usage.usage_path() == str(tmp_path / usage.USAGE_FILE_NAME) diff --git a/services/research_mcp/tools.py b/services/research_mcp/tools.py new file mode 100644 index 00000000..8ac44ffd --- /dev/null +++ b/services/research_mcp/tools.py @@ -0,0 +1,315 @@ +"""The six research MCP tools' implementations, as plain functions that +take/return JSON-serializable Python values. server.py wraps these as MCP +tools/call handlers; tests call them directly. + +Every tool composes PUBLIC functions from services/intel, services/thesis +and services/strategies -- never a private (`_`-prefixed) internal, and +never services.strategies.next_trade / pathiel.agents.bracket / pathiel. +client.exchange (order-placement and signing code; see +tests/test_no_trading_imports.py) or anything that reads PATHIEL_STATE_DIR's +.env.local / the repo's own .env.local / ~/.pathiel (see coins.py's and +scheduled_events.load()'s docstrings for exactly which call would do that +and how each tool here avoids it with use_overlay=False). + +Every tool catches its own data sources' failures and reports them in +`sources_failed` instead of raising -- same "never silently empty" contract +services/intel/api.py's build_packet uses, so one dead feed never takes +down the whole response. A tool only raises for a genuinely bad call (an +unsupported coin, neither coin nor query given); server.py turns that into +a clean tool error, never a crash. +""" +from __future__ import annotations + +import time +from datetime import datetime, timedelta, timezone +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from contracts.strategies.models import Catalyst, DeskSpec, Headline, Instrument, MarketOdds +from services.intel import scheduled_events +from services.intel.sources import catalysts as catalysts_src +from services.intel.sources import fred as fred_src +from services.intel.sources import news as news_src +from services.intel.sources import predictions as predictions_src +from services.research_mcp import coins as coins_mod +from services.research_mcp.concurrent import fetch_many +from services.strategies import journal +from services.strategies.levels import DEFAULT_HOURS_1H, atr, closed_only, fetch_candles, fetch_mid, price_range + +# ── coins the data behind every COIN_GROUPS-aware tool actually covers ────── +_CURATED_CALENDAR_COINS = frozenset().union(*scheduled_events.COIN_GROUPS.values()) + +FRED_KEY_HELP = ("fred_series needs the user's own FRED_API_KEY in the environment. Get a free " + "key at https://fred.stlouisfed.org/docs/api/api_key.html (no credit card), " + "then export FRED_API_KEY=... before starting this server.") + + +# ── levels ──────────────────────────────────────────────────────────────── + +def summarize_levels(coin: str, now_ms: Optional[int] = None) -> Dict[str, Any]: + """mid, the last closed 1h candle, 8h/24h/48h range, ATR14 (1h) and the + last four closed 15m candles' range, for `coin` -- public Hyperliquid + candle math, no key needed. + + This is services.strategies.levels.summarize()/summarize_coin()'s own + math, reimplemented here from levels.py's PURE exported building blocks + (fetch_candles, fetch_mid, closed_only, atr, price_range) instead of + calling summarize_coin() directly, because summarize_coin() -> summarize() + -> _breakout_levels()/hours_1h_for() import services.strategies. + next_trade, which imports pathiel.agents.bracket -- the module that ALSO + defines place_bracket/close_position/set_stop/set_target/sweep (its own + docstring: "the operator's direct-trade path"). This server must never + import order-placement code, so it skips next_trade's breakout_24h/ + closes_1h fields (never part of this tool's advertised output) and + builds the rest from the same public pieces levels.py exports for this. + + Raises RuntimeError if the venue has no live mid for `coin` (no reads + failed; there is simply no live level to show), same contract + summarize_coin() uses.""" + now_ms = now_ms if now_ms is not None else int(time.time() * 1000) + mid = fetch_mid(coin) + if mid is None: + raise RuntimeError(f"could not read a live mid for {coin}") + c1h = fetch_candles(coin, "1h", DEFAULT_HOURS_1H, now_ms) + c15 = fetch_candles(coin, "15m", 3, now_ms) + closed = closed_only(c1h, now_ms) + last = closed[-1] if closed else None + r24 = price_range(closed[-24:]) + out: Dict[str, Any] = { + "coin": coin, + "mid": mid, + "last_closed_1h": ({"open": float(last["o"]), "high": float(last["h"]), + "low": float(last["l"]), "close": float(last["c"]), + "closed_at_utc": time.strftime( + "%Y-%m-%dT%H:%M", time.gmtime((int(last["T"]) + 1) / 1000))} + if last else None), + "range_8h": price_range(closed[-8:]), + "range_24h": r24, + "range_48h": price_range(closed[-48:]), + "atr14_1h": atr(closed), + "range_15m_last4": price_range(closed_only(c15, now_ms)[-4:]), + "n_closed_1h": len(closed), + } + if r24 and r24["high"] > r24["low"]: + out["mid_pos_in_24h"] = round((mid - r24["low"]) / (r24["high"] - r24["low"]), 3) + if out["atr14_1h"]: + out["atr14_pct"] = round(out["atr14_1h"] / mid * 100, 3) + return out + + +def levels_tool(coin: str) -> Dict[str, Any]: + canon = coins_mod.canonical_coin(coin) + return summarize_levels(canon) + + +# ── catalysts / scheduled events ───────────────────────────────────────── + +def upcoming_catalysts(spec: DeskSpec, now: datetime, *, within_days: Optional[float] = None, + limit: int = 8) -> List[Catalyst]: + """calendar_catalysts(..., use_overlay=False): see that function's + docstring for why this server always passes use_overlay=False.""" + rows = catalysts_src.calendar_catalysts(spec, now, use_overlay=False) + rows = [c for c in rows if c.at >= now] + if within_days is not None: + cutoff = now + timedelta(days=within_days) + rows = [c for c in rows if c.at <= cutoff] + rows.sort(key=lambda c: c.at) + return rows[:limit] + + +def _event_row_json(r: Dict[str, Any]) -> Dict[str, Any]: + out = dict(r) + coins_field = out.get("coins") + if isinstance(coins_field, (set, frozenset)): + out["coins"] = sorted(coins_field) + return out + + +def scheduled_calendar(canon_coin: str, now: datetime, *, days: float = 7.0) -> Dict[str, Any]: + """The curated scheduled-event calendar plus the active blackout flag + for `canon_coin`, or an explicit note when this coin has no curated + calendar group yet (BTC/ETH today -- only oil/metals/sp500/hype coins + do; calendar_catalysts still carries FOMC/CPI for every coin). + use_overlay=False throughout: see scheduled_events.load()'s docstring.""" + if canon_coin not in _CURATED_CALENDAR_COINS: + return {"events": [], "active_blackout": None, + "note": (f"{canon_coin} has no curated scheduled-event calendar group yet " + "(only oil/metals/sp500/hype coins do today); calendar_catalysts " + "still carries FOMC/CPI for every coin.")} + now_ms = int(now.timestamp() * 1000) + end_ms = now_ms + int(days * 24 * 3_600_000) + rows = scheduled_events.market_events(now_ms, end_ms, canon_coin, use_overlay=False) + active_blackout = scheduled_events.blackout(canon_coin, now_ms, use_overlay=False) + return {"events": [_event_row_json(r) for r in rows], "active_blackout": active_blackout} + + +def events_tool(coins: Optional[Sequence[str]] = None, days: float = 7.0) -> Dict[str, Any]: + now = datetime.now(timezone.utc) + days = max(1.0, min(float(days if days is not None else 7.0), 60.0)) + targets = list(coins) if coins else list(coins_mod.SUPPORTED_COINS) + out: Dict[str, Any] = {} + errors: List[str] = [] + for raw in targets: + try: + canon = coins_mod.canonical_coin(raw) + except coins_mod.UnsupportedCoinError as exc: + errors.append(str(exc)) + continue + out[canon] = scheduled_calendar(canon, now, days=days) + return {"as_of": now.isoformat(), "window_days": days, "coins": out, "sources_failed": errors} + + +# ── headlines ───────────────────────────────────────────────────────────── + +def fetch_headlines_fast(spec: DeskSpec, now: datetime, *, deadline_s: float = 10.0 + ) -> Tuple[List[Headline], List[str]]: + """news.ATOMIC_FETCHERS fanned across threads (services/intel/api.py's + own pattern -- see concurrent.py's docstring), then news.score_and_dedup + once over everything that came back. Never raises.""" + raw, errors = fetch_many([(lambda fn=fn: fn(spec)) for fn in news_src.ATOMIC_FETCHERS], + deadline_s=deadline_s) + return news_src.score_and_dedup(raw, spec, now), errors + + +def _adhoc_spec(id_: str, *, news_queries: Optional[List[str]] = None, + prediction_market_queries: Optional[List[str]] = None, label: str = "") -> DeskSpec: + label = (label or "").strip()[:60] or "query" + return DeskSpec(id=id_, name="Ad hoc", tagline="services/research_mcp free-text query", + instruments=[Instrument(coin="ADHOC", label=label, role="primary")], + news_queries=news_queries or [], prediction_market_queries=prediction_market_queries or []) + + +def headlines_tool(coin: Optional[str] = None, topic: Optional[str] = None, + hours: float = 24.0) -> Dict[str, Any]: + if not coin and not topic: + raise ValueError("headlines needs either coin or topic") + now = datetime.now(timezone.utc) + hours = max(1.0, min(float(hours if hours is not None else 24.0), 168.0)) + if coin: + canon = coins_mod.canonical_coin(coin) + spec = coins_mod.desk_spec_for(canon) + query_label = canon + else: + spec = _adhoc_spec("adhoc_news", news_queries=[topic], label=topic or "") + query_label = topic + rows, errors = fetch_headlines_fast(spec, now) + cutoff = now - timedelta(hours=hours) + rows = [h for h in rows if h.published_at is None or h.published_at >= cutoff] + return {"query": query_label, "hours": hours, + "headlines": [h.model_dump(mode="json") for h in rows[:25]], + "sources_failed": errors} + + +# ── prediction odds ─────────────────────────────────────────────────────── + +def prediction_odds_for_spec(spec: DeskSpec, *, deadline_s: float = 10.0 + ) -> Tuple[List[MarketOdds], List[str]]: + rows, errors = fetch_many( + [lambda: predictions_src.fetch_polymarket(spec), lambda: predictions_src.fetch_kalshi(spec)], + deadline_s=deadline_s) + by_id = {o.id: o for o in rows} + ranked = sorted(by_id.values(), key=lambda o: o.volume_usd or 0.0, reverse=True) + return ranked, errors + + +def prediction_odds_tool(query: Optional[str] = None, coin: Optional[str] = None) -> Dict[str, Any]: + if not query and not coin: + raise ValueError("prediction_odds needs either coin or query") + if coin: + canon = coins_mod.canonical_coin(coin) + spec = coins_mod.desk_spec_for(canon) + query_label = canon + else: + spec = _adhoc_spec("adhoc_odds", prediction_market_queries=[query], label=query or "") + query_label = query + odds, errors = prediction_odds_for_spec(spec) + return {"query": query_label, "odds": [o.model_dump(mode="json") for o in odds[:25]], + "sources_failed": errors} + + +# ── FRED series ─────────────────────────────────────────────────────────── + +def fred_series_tool(series_id: str, start: Optional[str] = None, + end: Optional[str] = None) -> Dict[str, Any]: + data, err = fred_src.fetch_observations(series_id, start=start, end=end) + if err == "FRED_API_KEY_missing": + return {"error": "FRED_API_KEY_missing", "series_id": series_id, "help": FRED_KEY_HELP} + if err: + return {"error": err, "series_id": series_id} + return {"series_id": series_id, "start": start, "end": end, "observations": data} + + +# ── the latest stored thesis ────────────────────────────────────────────── + +def latest_thesis_json(desk_id: str) -> Optional[Dict[str, Any]]: + """The desk's newest saved Thesis (services.strategies.journal. + latest_thesis), or None if it has never been refreshed. Serves what is + already on disk only -- writing a NEW thesis needs an LLM call, which + this read-only server never makes (CLAUDE.md: no hosted LLM API, and + the local-Claude-Code route belongs to the trading server, not this + one).""" + thesis = journal.latest_thesis(desk_id) + return thesis.model_dump(mode="json") if thesis else None + + +# ── research_brief: the one-call summary ───────────────────────────────── + +def research_brief(coin: str, *, now: Optional[datetime] = None) -> Dict[str, Any]: + canon = coins_mod.canonical_coin(coin) + desk_id = coins_mod.desk_id_for(canon) + spec = coins_mod.desk_spec_for(canon) + now = now or datetime.now(timezone.utc) + errors: List[str] = [] + + try: + levels = summarize_levels(canon) + except Exception as exc: # noqa: BLE001 - one dead source must not sink the brief + levels = None + errors.append(f"levels:{exc}") + + try: + catalysts_out = [c.model_dump(mode="json") + for c in upcoming_catalysts(spec, now, within_days=30, limit=8)] + except Exception as exc: # noqa: BLE001 + catalysts_out = [] + errors.append(f"catalysts:{exc}") + + try: + headline_rows, herrs = fetch_headlines_fast(spec, now) + errors.extend(herrs) + headlines_out = [h.model_dump(mode="json") for h in headline_rows[:10]] + except Exception as exc: # noqa: BLE001 + headlines_out = [] + errors.append(f"headlines:{exc}") + + try: + odds_rows, oerrs = prediction_odds_for_spec(spec) + errors.extend(oerrs) + odds_out = [o.model_dump(mode="json") for o in odds_rows[:10]] + except Exception as exc: # noqa: BLE001 + odds_out = [] + errors.append(f"odds:{exc}") + + try: + thesis_out = latest_thesis_json(desk_id) + except Exception as exc: # noqa: BLE001 + thesis_out = None + errors.append(f"thesis:{exc}") + + note = None + if desk_id == "top5": + note = (f"{canon} has no standalone desk in pathiel; catalysts, headlines, odds and " + f"the stored thesis above reflect the top5 basket desk's coverage (BTC, ETH, " + f"SOL, HYPE, ZEC), not {canon} specifically.") + + return { + "coin": canon, "desk_id": desk_id, "as_of": now.isoformat(), + "levels": levels, "catalysts": catalysts_out, "headlines": headlines_out, + "odds": odds_out, "thesis": thesis_out, "note": note, "sources_failed": errors, + } + + +__all__ = [ + "levels_tool", "summarize_levels", "events_tool", "scheduled_calendar", "upcoming_catalysts", + "headlines_tool", "fetch_headlines_fast", "prediction_odds_tool", "prediction_odds_for_spec", + "fred_series_tool", "latest_thesis_json", "research_brief", "FRED_KEY_HELP", +] diff --git a/services/research_mcp/usage.py b/services/research_mcp/usage.py new file mode 100644 index 00000000..9d29ddf9 --- /dev/null +++ b/services/research_mcp/usage.py @@ -0,0 +1,67 @@ +"""Local, privacy-preserving usage counter: how many times each tool was +called, ever, on this machine, and when it was last called. + +No arguments, no results, no caller identity, no IP -- counting calls is the +whole job. Telemetry (sending this, or anything else, off this machine) is +off by default and not implemented at all in v1: see +docs/design/RESEARCH_MCP_PAID_TIER.md for the opt-in, off-box plan for +later. The file lives under state.state_dir() (never ~/.pathiel). +""" +from __future__ import annotations + +import json +import os +import threading +from datetime import datetime, timezone +from typing import Any, Dict, Optional + +from pathiel.agents.atomic_io import write_json_atomic +from services.research_mcp import state + +USAGE_FILE_NAME = "usage.json" +_LOCK = threading.Lock() + + +def usage_path() -> str: + return os.path.join(state.state_dir(), USAGE_FILE_NAME) + + +def _read(path: str) -> Dict[str, Dict[str, Any]]: + try: + with open(path) as fh: + data = json.load(fh) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def record_call(tool_name: str, *, path: Optional[str] = None, + now: Optional[datetime] = None) -> Dict[str, Any]: + """Increment `tool_name`'s call count by 1 and bump its last_called_at. + Thread-safe (one process-wide lock -- call volume here never justifies + anything fancier) and never raises: a counter write that fails is a + feature nobody lost, where a tool call failing because ITS OWN counter + write failed would be a much worse trade. Returns the row just written, + or a null row on a write failure.""" + path = path or usage_path() + now = now or datetime.now(timezone.utc) + with _LOCK: + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + data = _read(path) + row = dict(data.get(tool_name) or {"calls": 0, "first_called_at": None, + "last_called_at": None}) + row["calls"] = int(row.get("calls") or 0) + 1 + if not row.get("first_called_at"): + row["first_called_at"] = now.isoformat() + row["last_called_at"] = now.isoformat() + data[tool_name] = row + write_json_atomic(path, data) + return dict(row) + except OSError: + return {"calls": None, "first_called_at": None, "last_called_at": None} + + +def read_usage(path: Optional[str] = None) -> Dict[str, Dict[str, Any]]: + """The counter file as it stands. {} if nothing has been recorded yet.""" + return _read(path or usage_path()) diff --git a/site/index.html b/site/index.html index 2c299e96..0ae4d3f8 100644 --- a/site/index.html +++ b/site/index.html @@ -26,7 +26,7 @@ "description": "AI trading agent for Hyperliquid: a free, open-source MCP server and Claude Code plugin. Claude trades perpetual futures with an exact stop-loss and take-profit on every order.", "applicationCategory": "FinanceApplication", "operatingSystem": "macOS, Linux", - "softwareVersion": "0.8.0", + "softwareVersion": "0.9.0", "license": "https://opensource.org/licenses/MIT", "url": "https://julian-dev28.github.io/pathiel/", "codeRepository": "https://github.com/Julian-dev28/pathiel", @@ -341,7 +341,7 @@

Before you trade

GitHub MIT license - Version 0.8.0 + Version 0.9.0 Privacy Top
diff --git a/site/privacy.html b/site/privacy.html index c2f190a0..c73d9b45 100644 --- a/site/privacy.html +++ b/site/privacy.html @@ -118,8 +118,8 @@

What stays on your machine

The research pool (opt-in)

Off by default. If you join, pathiel reads your address's already-public Hyperliquid fills on the pool coins and publishes a graded summary at least 24 hours late: your address, the date you joined, your trade counts, and a win rate, mean result, label and luck score. It never publishes your balance, open positions, single trade prices or sizes, or any key. Leaving removes your rows from the next build. Full terms: docs/PRIVACY.md.

-

Coming next (0.9)

-

A keyless research server is built and lands in the next release: macro series, the event calendar, headlines and prediction-market odds, with no account and no key required to read it.

+

The research server

+

The separate pathiel-research server needs no account and no key, and cannot place an order. It reads public data: Hyperliquid's public market endpoint, news RSS feeds, Polymarket and Kalshi odds, and FRED macro series with your own free FRED key if you set one. It keeps a local count of how many times each tool was called (no arguments, no results, no identity) under ~/.pathiel-research, and sends nothing off your machine.

Questions or a problem

Open a GitHub issue, or report a security problem privately through a security advisory. More detail on how keys are handled: SECURITY.md.

@@ -129,7 +129,7 @@

Questions or a problem

GitHub MIT license - Version 0.8.0 + Version 0.9.0 Home Top
diff --git a/tests/test_deploy_config.py b/tests/test_deploy_config.py index fd4d1071..3fb77aaf 100644 --- a/tests/test_deploy_config.py +++ b/tests/test_deploy_config.py @@ -45,7 +45,12 @@ # so their imports must not force a COPY line into it. # pathiel_data_api own Dockerfile + Postgres deps # boot a server against a built file, not the image -EXCLUDE_PREFIXES = ("services/pathiel_data_api",) +# research_mcp its own Claude Code plugin + launcher +# (scripts/pathiel-research-mcp.{py,sh}), v1 ships local +# stdio only, no hosting, no container of its own yet — +# never bundled into THIS image either way +EXCLUDE_PREFIXES = ("services/pathiel_data_api", "services/research_mcp", + "scripts/pathiel-research-mcp.py") # ── helpers ────────────────────────────────────────────────────────────────── @@ -218,6 +223,18 @@ def test_dockerfile_does_not_bundle_pathiel_data_api(): assert not any("pathiel_data_api" in c for c in copies) +def test_dockerfile_does_not_bundle_research_mcp(): + """services/research_mcp is its own deploy unit too: v1 ships as a + second Claude Code plugin with its own launcher (scripts/pathiel- + research-mcp.sh, its own venv under its own data directory), not a + container, and never runs inside this image (the trading server's + Dockerfile/Dockerfile.mcp). Bundling it here would ship dead weight for + no running process to ever import.""" + copies = _dockerfile_copy_sources() + assert not any("research_mcp" in c for c in copies) + assert "pathiel-research-mcp.py" not in _dockerfile_text() + + def test_dockerfile_installs_the_package_before_copying_source(): """Layer-caching sanity: `pip install -e .` must run before the bulk `COPY pathiel/ ...` / `COPY services/...` lines, or every source diff --git a/tests/test_listing_metadata.py b/tests/test_listing_metadata.py index 3bbe5bdc..f85932bd 100644 --- a/tests/test_listing_metadata.py +++ b/tests/test_listing_metadata.py @@ -186,7 +186,7 @@ def network_defaults() -> List[Tuple[str, bool]]: def test_versions_agree_everywhere(): sources = version_sources() - assert {v for _, v in sources} == {"0.8.0"}, sources + assert {v for _, v in sources} == {"0.9.0"}, sources assert oci_package()["identifier"].endswith(":" + package_version()) @@ -269,10 +269,14 @@ def test_manifests_carry_discovery_keywords_and_category(): def test_manifest_key_set_unchanged(): + """Two entries since 2026-11-20 (the research MCP plugin joined the + trading one): every entry still has exactly MARKET_ENTRY_KEYS, whatever + the count.""" plugin, market = _json(PLUGIN_JSON), _json(MARKET_JSON) assert set(plugin) == PLUGIN_KEYS assert set(market) == MARKET_KEYS - assert len(market["plugins"]) == 1 and set(market["plugins"][0]) == MARKET_ENTRY_KEYS + assert len(market["plugins"]) == 2 + assert all(set(entry) == MARKET_ENTRY_KEYS for entry in market["plugins"]) assert plugin["mcpServers"] == {"pathiel": {"command": "bash", "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/pathiel-mcp.sh"]}} assert sorted(p.name for p in (ROOT / ".claude-plugin").iterdir()) == \ diff --git a/tests/test_plugin.py b/tests/test_plugin.py index b31a8b5f..69a20b28 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -40,17 +40,36 @@ def _marketplace() -> dict: def test_the_plugin_and_marketplace_names_agree_and_the_version_is_the_packages(): """The install id is @; a mismatch between - the entry and the manifest is the documented way an install fails.""" + the entry and the manifest is the documented way an install fails. + + Two plugins live in this one marketplace (2026-11-20): "pathiel" (the + trading server, this repo's root) and "pathiel-research" (the research + server, services/research_mcp/ — its own deploy unit, see + tests/test_deploy_config.py::test_dockerfile_does_not_bundle_research_mcp). + Only the trading plugin's version tracks pathiel/__init__.py; the + research plugin is a genuinely separate product with its own version.""" from pathiel import __version__ m, mk = _manifest(), _marketplace() assert m["name"] == "pathiel" assert mk["name"] == "pathiel" entries = mk["plugins"] - assert len(entries) == 1 and entries[0]["name"] == m["name"] - assert entries[0]["source"] in ("./", "."), "this repo is the plugin; the source is its own root" + assert len(entries) == 2 + by_name = {e["name"]: e for e in entries} + assert set(by_name) == {"pathiel", "pathiel-research"} + + assert by_name["pathiel"]["name"] == m["name"] + assert by_name["pathiel"]["source"] in ("./", "."), "this repo is the plugin; the source is its own root" assert m["version"] == __version__, "bump plugin.json with pathiel/__init__.py" assert m["author"]["name"] and mk["owner"]["name"] + research_source = by_name["pathiel-research"]["source"] + assert research_source == "./services/research_mcp" + research_manifest = json.loads((ROOT / research_source.removeprefix("./") / + ".claude-plugin" / "plugin.json").read_text()) + assert research_manifest["name"] == "pathiel-research" == by_name["pathiel-research"]["name"] + assert re.fullmatch(r"\d+\.\d+\.\d+", research_manifest["version"]) + assert research_manifest["author"]["name"] + def test_the_plugin_manifest_has_no_component_paths_outside_the_defaults(): """Skills, commands and the MCP wrapper all sit in their default diff --git a/tests/test_public_copy.py b/tests/test_public_copy.py index 32bdbc1c..984e844b 100644 --- a/tests/test_public_copy.py +++ b/tests/test_public_copy.py @@ -326,7 +326,7 @@ def test_readme_badges_are_static_or_point_at_a_real_workflow(): m = re.match(r"https://github\.com/Julian-dev28/pathiel/actions/workflows/([\w.-]+)/badge\.svg", url) assert m, f"badge that may not resolve: {url}" assert (ROOT / ".github" / "workflows" / m.group(1)).is_file(), url - assert "version-0.8.0" in readme + assert "version-0.9.0" in readme def test_faq_has_five_to_seven_questions(): From 830e3a509601400bead2524154417b06c972a4e3 Mon Sep 17 00:00:00 2001 From: Julian Martinez Date: Sat, 21 Nov 2026 14:06:30 -0800 Subject: [PATCH 2/2] fix(research-mcp): FRED help-link test compares the parsed host, not a substring CodeQL py/incomplete-url-substring-sanitization (high) flagged '"fred.stlouisfed.org" in out["help"]' on PR #34. The test now parses every URL in the help text and requires one whose hostname is exactly fred.stlouisfed.org and whose path ends in /api_key.html. Co-Authored-By: Claude Opus 5.5 --- services/research_mcp/tests/test_tools_fred.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/services/research_mcp/tests/test_tools_fred.py b/services/research_mcp/tests/test_tools_fred.py index 2bf7b7e3..1cd60a0c 100644 --- a/services/research_mcp/tests/test_tools_fred.py +++ b/services/research_mcp/tests/test_tools_fred.py @@ -1,5 +1,8 @@ from __future__ import annotations +import re +from urllib.parse import urlparse + from services.intel import http_client from services.research_mcp import tools @@ -8,8 +11,11 @@ def test_fred_series_tool_refuses_cleanly_without_a_key(monkeypatch): monkeypatch.delenv("FRED_API_KEY", raising=False) out = tools.fred_series_tool("DGS10") assert out["error"] == "FRED_API_KEY_missing" - assert "fred.stlouisfed.org" in out["help"] - assert "api_key.html" in out["help"] + # Parse the link and compare its host exactly: a substring check on a + # URL is what CodeQL's py/incomplete-url-substring-sanitization flags. + urls = [urlparse(u) for u in re.findall(r"https?://\S+", out["help"])] + assert any(u.hostname == "fred.stlouisfed.org" and u.path.endswith("/api_key.html") + for u in urls), out["help"] def test_fred_series_tool_never_logs_the_key(monkeypatch, capsys):