stock-analysis-plugin 0.2.11 → 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +234 -382
- package/docs/mcp.md +60 -0
- package/hermes/__init__.py +35 -0
- package/hermes/plugin.yaml +132 -0
- package/hermes/schemas.py +6 -0
- package/hermes/tools.py +647 -0
- package/mcp_host/__init__.py +1 -0
- package/mcp_host/__main__.py +3 -0
- package/mcp_host/server.py +222 -0
- package/package.json +7 -1
- package/pi/index.ts +52 -2906
- package/scripts/cli-json.mjs +23 -0
- package/scripts/exec-process.mjs +89 -0
- package/scripts/setup-python.mjs +37 -4
- package/scripts/tool-calls.mjs +493 -0
- package/skills/bull-trend/SKILL.md +2 -2
- package/skills/bull-trend/references/fat-tails.md +76 -3
- package/skills/bull-trend/scripts/tail_analysis.py +92 -3
- package/skills/event-driven/SKILL.md +2 -2
- package/skills/growth-quality/SKILL.md +1 -1
- package/skills/market-review/SKILL.md +1 -0
- package/skills/stock-analysis/SKILL.md +12 -7
- package/skills/stock-analysis/references/stateless-analysis.md +9 -1
- package/skills/stock-screener/SKILL.md +1 -1
- package/skills/strategy-backtest/SKILL.md +1 -1
- package/tools/_cache.py +13 -0
- package/tools/_subproc.py +46 -0
- package/tools/alert_rules.py +2 -2
- package/tools/backtest.py +3 -3
- package/tools/capabilities.py +33 -9
- package/tools/cli_budgets.json +1 -0
- package/tools/credit_data.py +293 -0
- package/tools/diagnostics.py +3 -4
- package/tools/gather.py +2 -6
- package/tools/import_parser.py +3 -4
- package/tools/lixinger.py +119 -27
- package/tools/market_regime.py +5 -2
- package/tools/market_review.py +5 -6
- package/tools/name_resolver.py +45 -33
- package/tools/report_renderer.py +3 -3
- package/tools/requirements.txt +5 -4
- package/tools/risk_screening.py +3 -2
- package/tools/screener.py +41 -30
- package/tools/search_intel.py +79 -10
- package/tools/sec_edgar.py +268 -1
- package/tools/sec_holders.py +6 -0
- package/tools/signal_tracker.py +5 -5
- package/tools/stateless_analysis.py +132 -19
- package/tools/stock_data.py +1020 -817
- package/tools/tiaa_disclosures.py +4 -0
- package/tools/tool_schemas.json +2734 -0
- package/tools/trading_calendar.py +65 -30
- package/tools/value_data.py +423 -175
- package/tools/watchlist.py +43 -5
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""MCP stdio server for the stock-analysis tools: newline-delimited JSON-RPC 2.0, stdlib only.
|
|
3
|
+
|
|
4
|
+
Reuses the Hermes adapter (tools/tool_schemas.json via hermes/schemas.py + hermes/tools.py argv mapping), so the
|
|
5
|
+
tools stay identical to the other hosts. stdout carries only JSON-RPC messages; anything else
|
|
6
|
+
goes to stderr.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import json
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
from importlib import metadata
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
18
|
+
if str(ROOT) not in sys.path:
|
|
19
|
+
sys.path.insert(0, str(ROOT))
|
|
20
|
+
|
|
21
|
+
from hermes import _without_nulls, schemas, tools # noqa: E402
|
|
22
|
+
|
|
23
|
+
PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
|
|
24
|
+
SCHEMAS = {schema["name"]: schema for schema in schemas.TOOL_SCHEMAS}
|
|
25
|
+
TOOL_LIST = [
|
|
26
|
+
{"name": s["name"], "description": s["description"], "inputSchema": s["parameters"]} for s in schemas.TOOL_SCHEMAS
|
|
27
|
+
]
|
|
28
|
+
_current = threading.local()
|
|
29
|
+
# Each call is a Python process that loads pandas; parallel model calls must not fan out unbounded.
|
|
30
|
+
_SLOTS = threading.BoundedSemaphore(4)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _version() -> str:
|
|
34
|
+
# Wheels carry no package.json; a source checkout is not pip-installed.
|
|
35
|
+
with contextlib.suppress(metadata.PackageNotFoundError):
|
|
36
|
+
return metadata.version("stock-analysis-plugin")
|
|
37
|
+
try:
|
|
38
|
+
return json.loads((tools.PROJECT_ROOT / "package.json").read_text(encoding="utf-8"))["version"]
|
|
39
|
+
except Exception:
|
|
40
|
+
return "unknown"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _Call:
|
|
44
|
+
"""One in-flight tools/call; cancel() kills its running CLI child."""
|
|
45
|
+
|
|
46
|
+
def __init__(self):
|
|
47
|
+
self.lock = threading.Lock()
|
|
48
|
+
self.cancelled = False
|
|
49
|
+
self.proc = None
|
|
50
|
+
|
|
51
|
+
def cancel(self):
|
|
52
|
+
with self.lock:
|
|
53
|
+
self.cancelled = True
|
|
54
|
+
if self.proc is not None:
|
|
55
|
+
tools.terminate_tree(self.proc)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _run(script: str, argv: list) -> str:
|
|
59
|
+
# hermes.tools._run, but the child must not inherit the JSON-RPC stdin, and cancellation kills it.
|
|
60
|
+
call = getattr(_current, "call", None) or _Call()
|
|
61
|
+
with _SLOTS:
|
|
62
|
+
return _run_slot(call, script, argv)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _run_slot(call, script: str, argv: list) -> str:
|
|
66
|
+
try:
|
|
67
|
+
with call.lock:
|
|
68
|
+
if call.cancelled:
|
|
69
|
+
return json.dumps({"error": "Cancelled"})
|
|
70
|
+
proc = call.proc = subprocess.Popen(
|
|
71
|
+
[tools._find_python(), str(tools.TOOLS_DIR / script), *map(str, argv)],
|
|
72
|
+
stdin=subprocess.DEVNULL,
|
|
73
|
+
stdout=subprocess.PIPE,
|
|
74
|
+
stderr=subprocess.DEVNULL,
|
|
75
|
+
text=True,
|
|
76
|
+
encoding="utf-8",
|
|
77
|
+
**tools.TREE_POPEN,
|
|
78
|
+
)
|
|
79
|
+
except Exception:
|
|
80
|
+
return json.dumps({"error": "Python command failed; check interpreter/dependencies"})
|
|
81
|
+
try:
|
|
82
|
+
stdout, _ = proc.communicate(timeout=tools.command_timeout(script, argv) + 30)
|
|
83
|
+
except subprocess.TimeoutExpired:
|
|
84
|
+
tools.terminate_tree(proc)
|
|
85
|
+
proc.communicate()
|
|
86
|
+
return json.dumps({"error": "Python command timed out"})
|
|
87
|
+
failure = None
|
|
88
|
+
if proc.returncode != 0:
|
|
89
|
+
failure = f"Python command failed (exit {proc.returncode}); check interpreter/dependencies"
|
|
90
|
+
return tools._cli_json(stdout or "", failure)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class RpcError(Exception):
|
|
94
|
+
def __init__(self, code: int, message: str):
|
|
95
|
+
super().__init__(message)
|
|
96
|
+
self.code = code
|
|
97
|
+
self.message = message
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def call_tool(params: dict) -> dict:
|
|
101
|
+
name = params.get("name")
|
|
102
|
+
schema = SCHEMAS.get(name) if isinstance(name, str) else None
|
|
103
|
+
if schema is None:
|
|
104
|
+
raise RpcError(-32602, f"Unknown tool: {name}")
|
|
105
|
+
args = params.get("arguments", {})
|
|
106
|
+
if not isinstance(args, dict):
|
|
107
|
+
raise RpcError(-32602, "Tool arguments must be an object")
|
|
108
|
+
missing = [key for key in schema["parameters"].get("required", []) if args.get(key) is None]
|
|
109
|
+
if missing:
|
|
110
|
+
text = json.dumps({"error": f"missing required argument: {', '.join(missing)}"})
|
|
111
|
+
else:
|
|
112
|
+
# Binds the cancellable runner to this tools/call only; Hermes itself keeps its default runner.
|
|
113
|
+
token = tools._RUN_OVERRIDE.set(_run)
|
|
114
|
+
try:
|
|
115
|
+
text = _without_nulls(getattr(tools, name))(args)
|
|
116
|
+
except Exception:
|
|
117
|
+
text = json.dumps({"error": "Tool handler failed; check arguments"})
|
|
118
|
+
finally:
|
|
119
|
+
tools._RUN_OVERRIDE.reset(token)
|
|
120
|
+
try:
|
|
121
|
+
payload = json.loads(text)
|
|
122
|
+
except ValueError:
|
|
123
|
+
payload = None
|
|
124
|
+
is_error = isinstance(payload, dict) and isinstance(payload.get("error"), str)
|
|
125
|
+
return {"content": [{"type": "text", "text": text}], "isError": is_error}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def handle(method: str, params: dict) -> dict:
|
|
129
|
+
if method == "initialize":
|
|
130
|
+
requested = params.get("protocolVersion")
|
|
131
|
+
return {
|
|
132
|
+
"protocolVersion": requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0],
|
|
133
|
+
"capabilities": {"tools": {"listChanged": False}},
|
|
134
|
+
"serverInfo": {"name": "stock-analysis", "version": _version()},
|
|
135
|
+
}
|
|
136
|
+
if method == "ping":
|
|
137
|
+
return {}
|
|
138
|
+
if method == "tools/list":
|
|
139
|
+
return {"tools": TOOL_LIST}
|
|
140
|
+
raise RpcError(-32601, f"Method not found: {method}")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def serve(stdin, stdout) -> None:
|
|
144
|
+
write_lock = threading.Lock()
|
|
145
|
+
calls: dict = {}
|
|
146
|
+
workers: list = []
|
|
147
|
+
|
|
148
|
+
def send(message: dict) -> None:
|
|
149
|
+
data = (json.dumps(message, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8")
|
|
150
|
+
with write_lock:
|
|
151
|
+
stdout.write(data)
|
|
152
|
+
stdout.flush()
|
|
153
|
+
|
|
154
|
+
def reply(request_id, work, *args) -> dict:
|
|
155
|
+
try:
|
|
156
|
+
return {"jsonrpc": "2.0", "id": request_id, "result": work(*args)}
|
|
157
|
+
except RpcError as exc:
|
|
158
|
+
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": exc.code, "message": exc.message}}
|
|
159
|
+
|
|
160
|
+
def run_call(request_id, params, call):
|
|
161
|
+
_current.call = call
|
|
162
|
+
message = reply(request_id, call_tool, params)
|
|
163
|
+
with call.lock:
|
|
164
|
+
if calls.get(request_id) is call:
|
|
165
|
+
del calls[request_id]
|
|
166
|
+
if not call.cancelled: # cancellation and response are ordered by the same lock
|
|
167
|
+
send(message)
|
|
168
|
+
|
|
169
|
+
for line in stdin:
|
|
170
|
+
if not line.strip():
|
|
171
|
+
continue
|
|
172
|
+
try:
|
|
173
|
+
msg = json.loads(line)
|
|
174
|
+
except ValueError:
|
|
175
|
+
send({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}})
|
|
176
|
+
continue
|
|
177
|
+
if isinstance(msg, dict) and "method" not in msg and ("result" in msg or "error" in msg):
|
|
178
|
+
continue # responses to server requests; this server sends none
|
|
179
|
+
params = msg.get("params") if isinstance(msg, dict) else None
|
|
180
|
+
if (
|
|
181
|
+
not isinstance(msg, dict)
|
|
182
|
+
or msg.get("jsonrpc") != "2.0"
|
|
183
|
+
or not isinstance(msg.get("method"), str)
|
|
184
|
+
or not isinstance(params if params is not None else {}, dict)
|
|
185
|
+
or type(msg.get("id")) not in (str, int, type(None)) # type(), not isinstance: JSON true is not an id
|
|
186
|
+
):
|
|
187
|
+
request_id = msg.get("id") if isinstance(msg, dict) and type(msg.get("id")) in (str, int) else None
|
|
188
|
+
send({"jsonrpc": "2.0", "id": request_id, "error": {"code": -32600, "message": "Invalid Request"}})
|
|
189
|
+
continue
|
|
190
|
+
method, params = msg["method"], params or {}
|
|
191
|
+
if method == "notifications/cancelled":
|
|
192
|
+
target = params.get("requestId")
|
|
193
|
+
call = calls.get(target) if isinstance(target, (str, int)) else None
|
|
194
|
+
if call is not None:
|
|
195
|
+
call.cancel()
|
|
196
|
+
continue
|
|
197
|
+
if "id" not in msg:
|
|
198
|
+
continue # other notifications (initialized, ...) need no reply
|
|
199
|
+
request_id = msg["id"]
|
|
200
|
+
if method == "tools/call":
|
|
201
|
+
call = calls[request_id] = _Call()
|
|
202
|
+
worker = threading.Thread(target=run_call, args=(request_id, params, call), daemon=True)
|
|
203
|
+
worker.start()
|
|
204
|
+
workers = [w for w in workers if w.is_alive()] + [worker]
|
|
205
|
+
continue
|
|
206
|
+
send(reply(request_id, handle, method, params))
|
|
207
|
+
|
|
208
|
+
for call in list(calls.values()): # client closed stdin: stop outstanding work
|
|
209
|
+
call.cancel()
|
|
210
|
+
for worker in workers:
|
|
211
|
+
worker.join()
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def main() -> None:
|
|
215
|
+
stdout = sys.stdout.buffer
|
|
216
|
+
sys.stdout = sys.stderr # stray prints must never corrupt the JSON-RPC stream
|
|
217
|
+
with contextlib.suppress(KeyboardInterrupt):
|
|
218
|
+
serve(sys.stdin.buffer, stdout)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
if __name__ == "__main__":
|
|
222
|
+
main()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stock-analysis-plugin",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.13",
|
|
4
4
|
"description": "Pi Agent extension for stock analysis, screening, and strategy backtesting across A/HK/US/JP/KR/TW markets",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./pi/index.ts",
|
|
@@ -34,8 +34,14 @@
|
|
|
34
34
|
},
|
|
35
35
|
"files": [
|
|
36
36
|
"pi/",
|
|
37
|
+
"mcp_host/",
|
|
38
|
+
"hermes/",
|
|
39
|
+
"!hermes/**/__pycache__/**",
|
|
40
|
+
"!mcp_host/**/__pycache__/**",
|
|
41
|
+
"docs/mcp.md",
|
|
37
42
|
"tools/**/*.py",
|
|
38
43
|
"tools/cli_budgets.json",
|
|
44
|
+
"tools/tool_schemas.json",
|
|
39
45
|
"tools/requirements.txt",
|
|
40
46
|
"skills/",
|
|
41
47
|
"!skills/**/__pycache__/**",
|