alphasift 0.3.1__py3-none-any.whl

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.
Files changed (86) hide show
  1. alphasift/__init__.py +52 -0
  2. alphasift/__main__.py +7 -0
  3. alphasift/audit.py +191 -0
  4. alphasift/candidate_context.py +738 -0
  5. alphasift/cli.py +2797 -0
  6. alphasift/config.py +705 -0
  7. alphasift/context.py +672 -0
  8. alphasift/daily.py +1256 -0
  9. alphasift/daily_brief.py +593 -0
  10. alphasift/daily_report.py +1115 -0
  11. alphasift/daily_report_html.py +1257 -0
  12. alphasift/doctor.py +1123 -0
  13. alphasift/dsa.py +302 -0
  14. alphasift/dsa_adapter.py +178 -0
  15. alphasift/dsa_provider.py +192 -0
  16. alphasift/evaluate.py +2418 -0
  17. alphasift/filter.py +517 -0
  18. alphasift/hotspot.py +1713 -0
  19. alphasift/industry.py +959 -0
  20. alphasift/llm_client.py +349 -0
  21. alphasift/market_digest.py +284 -0
  22. alphasift/market_news.py +446 -0
  23. alphasift/market_regime.py +578 -0
  24. alphasift/markets.py +160 -0
  25. alphasift/mcp.py +720 -0
  26. alphasift/models.py +315 -0
  27. alphasift/normalize.py +113 -0
  28. alphasift/notify.py +2608 -0
  29. alphasift/overview.py +225 -0
  30. alphasift/pack.py +1470 -0
  31. alphasift/pack_features.py +431 -0
  32. alphasift/pattern_replay.py +1449 -0
  33. alphasift/patterns/bottom_volume_yang.yaml +32 -0
  34. alphasift/patterns/box_breakout.yaml +36 -0
  35. alphasift/patterns/double_bottom_breakout.yaml +38 -0
  36. alphasift/patterns/ma20_shrink_pullback.yaml +37 -0
  37. alphasift/patterns/shooting_star_confirm.yaml +49 -0
  38. alphasift/patterns/single_yang_hold.yaml +44 -0
  39. alphasift/patterns/steady_trend_breakout.yaml +39 -0
  40. alphasift/patterns/three_white_soldiers.yaml +72 -0
  41. alphasift/patterns/three_white_soldiers_pullback.yaml +91 -0
  42. alphasift/patterns.py +1233 -0
  43. alphasift/performance_history.py +297 -0
  44. alphasift/pipeline.py +1010 -0
  45. alphasift/post_analysis.py +337 -0
  46. alphasift/ranker.py +990 -0
  47. alphasift/report.py +379 -0
  48. alphasift/result_schema.py +179 -0
  49. alphasift/risk.py +452 -0
  50. alphasift/run_history.py +164 -0
  51. alphasift/scorer.py +597 -0
  52. alphasift/server.py +680 -0
  53. alphasift/snapshot.py +1025 -0
  54. alphasift/snapshot_us.py +280 -0
  55. alphasift/snapshot_yahoo.py +358 -0
  56. alphasift/source_guard.py +70 -0
  57. alphasift/source_history.py +306 -0
  58. alphasift/store.py +294 -0
  59. alphasift/strategies/balanced_alpha.yaml +76 -0
  60. alphasift/strategies/blue_chip_income.yaml +87 -0
  61. alphasift/strategies/capital_heat.yaml +74 -0
  62. alphasift/strategies/dual_low.yaml +80 -0
  63. alphasift/strategies/global_value.yaml +65 -0
  64. alphasift/strategies/low_volatility_quality.yaml +95 -0
  65. alphasift/strategies/momentum_quality.yaml +81 -0
  66. alphasift/strategies/oversold_reversal.yaml +75 -0
  67. alphasift/strategies/quality_value.yaml +80 -0
  68. alphasift/strategies/shrink_pullback.yaml +77 -0
  69. alphasift/strategies/us_momentum_quality.yaml +74 -0
  70. alphasift/strategies/volume_breakout.yaml +78 -0
  71. alphasift/strategy.py +1090 -0
  72. alphasift/strategy_cards.py +424 -0
  73. alphasift/strategy_templates.py +291 -0
  74. alphasift/timeutil.py +38 -0
  75. alphasift/valuation_kr.py +149 -0
  76. alphasift/workbench_ui.py +1051 -0
  77. alphasift-0.3.1.data/data/.env.example +151 -0
  78. alphasift-0.3.1.data/data/LICENSE +184 -0
  79. alphasift-0.3.1.data/data/SKILL.md +190 -0
  80. alphasift-0.3.1.data/data/agents/openai.yaml +7 -0
  81. alphasift-0.3.1.dist-info/METADATA +312 -0
  82. alphasift-0.3.1.dist-info/RECORD +86 -0
  83. alphasift-0.3.1.dist-info/WHEEL +5 -0
  84. alphasift-0.3.1.dist-info/entry_points.txt +2 -0
  85. alphasift-0.3.1.dist-info/licenses/LICENSE +184 -0
  86. alphasift-0.3.1.dist-info/top_level.txt +1 -0
alphasift/mcp.py ADDED
@@ -0,0 +1,720 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Zero-dependency STDIO Model Context Protocol (MCP 2024-11-05) server for AlphaSift."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Callable
7
+ from contextlib import redirect_stdout
8
+ from dataclasses import asdict
9
+ from datetime import date, datetime
10
+ import json
11
+ import math
12
+ import os
13
+ from pathlib import Path
14
+ import site
15
+ import sys
16
+ from typing import Any, BinaryIO
17
+
18
+ from alphasift import __version__
19
+ from alphasift.config import Config
20
+ from alphasift.doctor import doctor_data_sources
21
+ from alphasift.markets import get_market
22
+ from alphasift.notify import notify_readiness
23
+ from alphasift.overview import build_overview
24
+ from alphasift.pack import PackError, load_pack, pack_dir
25
+ from alphasift.patterns import list_patterns, scan_patterns
26
+ from alphasift.pipeline import screen
27
+ from alphasift.store import list_saved_runs
28
+ from alphasift.strategy import compare_strategies, list_strategies, load_all_strategies
29
+
30
+ MCP_PROTOCOL_VERSION = "2024-11-05"
31
+ _MAX_CONTENT_LENGTH = 16 * 1024 * 1024
32
+ _MAX_HEADER_LINES = 32
33
+ _MAX_HEADER_BYTES = 8192
34
+ _MAX_PATTERN_SELECTION = 32
35
+ _PROJECT_ROOT = Path(__file__).resolve().parent.parent
36
+
37
+
38
+ def _clamp_int(value: Any, *, default: int, minimum: int, maximum: int) -> int:
39
+ if value is None:
40
+ return default
41
+ if isinstance(value, bool) or not isinstance(value, int):
42
+ raise ValueError(f"Expected integer parameter, got {type(value).__name__}")
43
+ return max(minimum, min(value, maximum))
44
+
45
+
46
+ def _optional_bool(args: dict[str, Any], key: str, default: bool) -> bool:
47
+ if key not in args or args[key] is None:
48
+ return default
49
+ val = args[key]
50
+ if not isinstance(val, bool):
51
+ raise ValueError(f"Parameter {key!r} must be a boolean")
52
+ return val
53
+
54
+
55
+ def _optional_str(args: dict[str, Any], key: str) -> str:
56
+ if key not in args or args[key] is None:
57
+ return ""
58
+ val = args[key]
59
+ if not isinstance(val, str):
60
+ raise ValueError(f"Parameter {key!r} must be a string")
61
+ return val.strip()
62
+
63
+
64
+ def _require_str(args: dict[str, Any], key: str) -> str:
65
+ raw = args.get(key)
66
+ if not isinstance(raw, str) or not raw.strip():
67
+ raise ValueError(f"Missing or invalid required string parameter: {key!r}")
68
+ return raw.strip()
69
+
70
+
71
+ def _json_safe(obj: Any) -> Any:
72
+ """Normalize NaN/Inf floats, NumPy scalars/arrays, and dates before strict JSON serialization."""
73
+ if obj is None or isinstance(obj, (bool, int)):
74
+ return obj
75
+ if isinstance(obj, float):
76
+ return obj if math.isfinite(obj) else None
77
+ if isinstance(obj, str):
78
+ return obj
79
+ if type(obj).__name__ == "NaTType":
80
+ return None
81
+ if isinstance(obj, (date, datetime)):
82
+ return obj.isoformat()
83
+ if isinstance(obj, Path):
84
+ return str(obj)
85
+ ndim = getattr(obj, "ndim", None)
86
+ if isinstance(ndim, int) and ndim > 0 and hasattr(obj, "tolist") and callable(getattr(obj, "tolist")):
87
+ try:
88
+ return _json_safe(obj.tolist())
89
+ except Exception:
90
+ pass
91
+ if hasattr(obj, "item") and callable(getattr(obj, "item")):
92
+ try:
93
+ return _json_safe(obj.item())
94
+ except Exception:
95
+ pass
96
+ if hasattr(obj, "tolist") and callable(getattr(obj, "tolist")):
97
+ try:
98
+ return _json_safe(obj.tolist())
99
+ except Exception:
100
+ pass
101
+ if isinstance(obj, dict):
102
+ return {str(k): _json_safe(v) for k, v in obj.items()}
103
+ if isinstance(obj, (list, tuple, set)):
104
+ return [_json_safe(v) for v in obj]
105
+ return str(obj)
106
+
107
+
108
+ class _RPCParamError(Exception):
109
+ """Raised on JSON-RPC protocol/param errors (-32602 / -32601 / -32600)."""
110
+
111
+ def __init__(self, code: int, message: str) -> None:
112
+ super().__init__(message)
113
+ self.code = code
114
+ self.message = message
115
+
116
+
117
+ def _tool_definitions() -> list[dict[str, Any]]:
118
+ return [
119
+ {
120
+ "name": "alphasift_list_strategies",
121
+ "description": "List available quantitative stock screening strategies and metadata.",
122
+ "inputSchema": {
123
+ "type": "object",
124
+ "properties": {
125
+ "market": {
126
+ "type": "string",
127
+ "description": "Optional market filter: cn, us, hk, jp, kr, tw, in.",
128
+ },
129
+ },
130
+ "additionalProperties": False,
131
+ },
132
+ },
133
+ {
134
+ "name": "alphasift_get_strategy",
135
+ "description": "Get full YAML-derived configuration and factor weights for a named strategy.",
136
+ "inputSchema": {
137
+ "type": "object",
138
+ "properties": {
139
+ "name": {"type": "string", "description": "Strategy identifier (e.g. balanced_alpha)."},
140
+ },
141
+ "required": ["name"],
142
+ "additionalProperties": False,
143
+ },
144
+ },
145
+ {
146
+ "name": "alphasift_compare_strategies",
147
+ "description": "Compare two strategies across style, data requirements, hard filters, and factor weights.",
148
+ "inputSchema": {
149
+ "type": "object",
150
+ "properties": {
151
+ "base": {"type": "string", "description": "Base strategy name."},
152
+ "target": {"type": "string", "description": "Target strategy name."},
153
+ },
154
+ "required": ["base", "target"],
155
+ "additionalProperties": False,
156
+ },
157
+ },
158
+ {
159
+ "name": "alphasift_screen",
160
+ "description": (
161
+ "Run stock screening for a strategy and return structured ScreenResult JSON. "
162
+ "Defaults to use_llm=false unless explicitly enabled."
163
+ ),
164
+ "inputSchema": {
165
+ "type": "object",
166
+ "properties": {
167
+ "strategy": {"type": "string", "description": "Strategy identifier."},
168
+ "market": {"type": "string", "default": "cn", "description": "Target market (cn/us/hk/jp/kr/tw/in)."},
169
+ "max_output": {"type": "integer", "minimum": 1, "maximum": 50, "description": "Max picks (1-50)."},
170
+ "use_llm": {"type": "boolean", "default": False, "description": "Enable L2 LLM ranking."},
171
+ "explain_filters": {"type": "boolean", "default": False, "description": "Include L1 waterfall diagnostics."},
172
+ "llm_context": {"type": "string", "description": "Optional market/theme context for L2 LLM ranking."},
173
+ },
174
+ "required": ["strategy"],
175
+ "additionalProperties": False,
176
+ },
177
+ },
178
+ {
179
+ "name": "alphasift_list_patterns",
180
+ "description": "List declarative CN daily-matrix technical pattern definitions.",
181
+ "inputSchema": {
182
+ "type": "object",
183
+ "properties": {
184
+ "include_experimental": {"type": "boolean", "default": False},
185
+ },
186
+ "additionalProperties": False,
187
+ },
188
+ },
189
+ {
190
+ "name": "alphasift_scan_patterns",
191
+ "description": "Scan the local CN DailyPack for matching chart/volume patterns.",
192
+ "inputSchema": {
193
+ "type": "object",
194
+ "properties": {
195
+ "patterns": {
196
+ "type": "array",
197
+ "items": {"type": "string"},
198
+ "description": "Optional list of built-in pattern names.",
199
+ },
200
+ "trade_date": {"type": "string", "description": "Optional YYYY-MM-DD trade date."},
201
+ "include_experimental": {"type": "boolean", "default": False},
202
+ },
203
+ "additionalProperties": False,
204
+ },
205
+ },
206
+ {
207
+ "name": "alphasift_overview",
208
+ "description": "Build the AlphaSift operational overview (strategies, source health, history, performance).",
209
+ "inputSchema": {
210
+ "type": "object",
211
+ "properties": {
212
+ "strategy": {"type": "string", "description": "Optional strategy focus."},
213
+ "runs_limit": {"type": "integer", "minimum": 1, "maximum": 50, "default": 5},
214
+ "live_data_check": {"type": "boolean", "default": False},
215
+ },
216
+ "additionalProperties": False,
217
+ },
218
+ },
219
+ {
220
+ "name": "alphasift_doctor_data_sources",
221
+ "description": "Inspect snapshot & daily K data source health and strategy field readiness.",
222
+ "inputSchema": {
223
+ "type": "object",
224
+ "properties": {
225
+ "strategy": {"type": "string"},
226
+ "market": {"type": "string"},
227
+ "run_live": {"type": "boolean", "default": False},
228
+ "check_daily": {"type": "boolean", "default": True},
229
+ },
230
+ "additionalProperties": False,
231
+ },
232
+ },
233
+ {
234
+ "name": "alphasift_notify_status",
235
+ "description": "Inspect configured notification channels and ledger path (never exposes secrets).",
236
+ "inputSchema": {
237
+ "type": "object",
238
+ "properties": {},
239
+ "additionalProperties": False,
240
+ },
241
+ },
242
+ {
243
+ "name": "alphasift_list_runs",
244
+ "description": "List saved screening runs stored under ALPHASIFT_DATA_DIR/runs.",
245
+ "inputSchema": {
246
+ "type": "object",
247
+ "properties": {
248
+ "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20},
249
+ "strategy": {"type": "string"},
250
+ "market": {"type": "string"},
251
+ },
252
+ "additionalProperties": False,
253
+ },
254
+ },
255
+ ]
256
+
257
+
258
+ class MCPServer:
259
+ """Stateless JSON-RPC 2.0 dispatcher implementing the AlphaSift MCP interface."""
260
+
261
+ def __init__(self, config: Config | None = None) -> None:
262
+ self.config = config or Config.from_env()
263
+ self._tools: list[dict[str, Any]] = _tool_definitions()
264
+ self._tool_props: dict[str, set[str]] = {
265
+ t["name"]: set((t.get("inputSchema") or {}).get("properties", {}).keys())
266
+ for t in self._tools
267
+ }
268
+ self._handlers: dict[str, Callable[[dict[str, Any]], Any]] = {
269
+ "alphasift_list_strategies": self._handle_list_strategies,
270
+ "alphasift_get_strategy": self._handle_get_strategy,
271
+ "alphasift_compare_strategies": self._handle_compare_strategies,
272
+ "alphasift_screen": self._handle_screen,
273
+ "alphasift_list_patterns": self._handle_list_patterns,
274
+ "alphasift_scan_patterns": self._handle_scan_patterns,
275
+ "alphasift_overview": self._handle_overview,
276
+ "alphasift_doctor_data_sources": self._handle_doctor_data_sources,
277
+ "alphasift_notify_status": self._handle_notify_status,
278
+ "alphasift_list_runs": self._handle_list_runs,
279
+ }
280
+
281
+ def _handle_list_strategies(self, args: dict[str, Any]) -> Any:
282
+ market = _optional_str(args, "market").lower()
283
+ if market:
284
+ get_market(market)
285
+ items = [asdict(item) for item in list_strategies(self.config.strategies_dir)]
286
+ if market:
287
+ items = [item for item in items if market in (item.get("market_scope") or [])]
288
+ return {"strategies": items}
289
+
290
+ def _handle_get_strategy(self, args: dict[str, Any]) -> Any:
291
+ name = _require_str(args, "name")
292
+ if "/" in name or "\\" in name or ".." in name:
293
+ raise ValueError(f"Unsafe strategy name: {name!r}")
294
+ catalog = load_all_strategies(self.config.strategies_dir)
295
+ strategy = catalog.get(name)
296
+ if strategy is None:
297
+ raise KeyError(f"Strategy not found: {name!r}")
298
+ return asdict(strategy)
299
+
300
+ def _handle_compare_strategies(self, args: dict[str, Any]) -> Any:
301
+ base = _require_str(args, "base")
302
+ target = _require_str(args, "target")
303
+ if "/" in base or "\\" in base or ".." in base or "/" in target or "\\" in target or ".." in target:
304
+ raise ValueError("Unsafe strategy name")
305
+ return compare_strategies(base, target, self.config.strategies_dir)
306
+
307
+ def _handle_screen(self, args: dict[str, Any]) -> Any:
308
+ strategy = _require_str(args, "strategy")
309
+ if "/" in strategy or "\\" in strategy or ".." in strategy:
310
+ raise ValueError(f"Unsafe strategy name: {strategy!r}")
311
+ market = (_optional_str(args, "market") or "cn").lower()
312
+ get_market(market)
313
+ raw_max_output = args.get("max_output")
314
+ max_output = (
315
+ _clamp_int(raw_max_output, default=10, minimum=1, maximum=50)
316
+ if raw_max_output is not None
317
+ else None
318
+ )
319
+ use_llm = _optional_bool(args, "use_llm", False)
320
+ explain_filters = _optional_bool(args, "explain_filters", False)
321
+ raw_ctx = args.get("llm_context")
322
+ if raw_ctx is not None and not isinstance(raw_ctx, str):
323
+ raise ValueError("Parameter 'llm_context' must be a string")
324
+ llm_context = raw_ctx[:4000] if raw_ctx is not None else None
325
+ result = screen(
326
+ strategy,
327
+ market=market,
328
+ max_output=max_output,
329
+ use_llm=use_llm,
330
+ llm_context=llm_context,
331
+ explain_filters=explain_filters,
332
+ post_analyzers=["scorecard"],
333
+ config=self.config,
334
+ )
335
+ return asdict(result)
336
+
337
+ def _handle_list_patterns(self, args: dict[str, Any]) -> Any:
338
+ include_exp = _optional_bool(args, "include_experimental", False)
339
+ return {"patterns": [asdict(item) for item in list_patterns(include_experimental=include_exp)]}
340
+
341
+ def _handle_scan_patterns(self, args: dict[str, Any]) -> Any:
342
+ raw_patterns = args.get("patterns")
343
+ patterns: list[str] | None = None
344
+ if raw_patterns is not None:
345
+ if not isinstance(raw_patterns, list) or not all(isinstance(p, str) for p in raw_patterns):
346
+ raise ValueError("Parameter 'patterns' must be a list of strings.")
347
+ known = {spec.name for spec in list_patterns(include_experimental=True)}
348
+ selected: list[str] = []
349
+ seen: set[str] = set()
350
+ for raw_item in raw_patterns:
351
+ cleaned = raw_item.strip()
352
+ if not cleaned:
353
+ continue
354
+ if "/" in cleaned or "\\" in cleaned or ".." in cleaned or cleaned not in known:
355
+ raise ValueError(f"Unknown or unsafe pattern name: {cleaned!r}")
356
+ if cleaned not in seen:
357
+ seen.add(cleaned)
358
+ selected.append(cleaned)
359
+ if len(selected) > _MAX_PATTERN_SELECTION:
360
+ raise ValueError(f"Too many patterns requested (max {_MAX_PATTERN_SELECTION})")
361
+ patterns = selected or None
362
+
363
+ trade_date = _optional_str(args, "trade_date") or None
364
+ include_exp = _optional_bool(args, "include_experimental", False)
365
+ try:
366
+ daily_pack = load_pack(pack_dir(self.config))
367
+ except (OSError, PackError, ValueError) as exc:
368
+ raise RuntimeError(
369
+ f"CN DailyPack unavailable: {type(exc).__name__}. "
370
+ "Build a pack with `alphasift pack build` first."
371
+ ) from exc
372
+ return scan_patterns(
373
+ daily_pack,
374
+ patterns=patterns,
375
+ trade_date=trade_date,
376
+ include_experimental=include_exp,
377
+ ).to_dict()
378
+
379
+ def _handle_overview(self, args: dict[str, Any]) -> Any:
380
+ strategy = _optional_str(args, "strategy") or None
381
+ runs_limit = _clamp_int(args.get("runs_limit"), default=5, minimum=1, maximum=50)
382
+ live = _optional_bool(args, "live_data_check", False)
383
+ return build_overview(
384
+ self.config,
385
+ strategy_name=strategy,
386
+ runs_limit=runs_limit,
387
+ live_data_check=live,
388
+ )
389
+
390
+ def _handle_doctor_data_sources(self, args: dict[str, Any]) -> Any:
391
+ strategy = _optional_str(args, "strategy") or None
392
+ market = _optional_str(args, "market").lower() or None
393
+ if market:
394
+ get_market(market)
395
+ run_live = _optional_bool(args, "run_live", False)
396
+ check_daily = _optional_bool(args, "check_daily", True)
397
+ return doctor_data_sources(
398
+ self.config,
399
+ strategy_name=strategy,
400
+ market=market,
401
+ run_live=run_live,
402
+ check_daily=check_daily,
403
+ ).to_dict()
404
+
405
+ def _handle_notify_status(self, args: dict[str, Any]) -> Any:
406
+ return notify_readiness(self.config)
407
+
408
+ def _handle_list_runs(self, args: dict[str, Any]) -> Any:
409
+ limit = _clamp_int(args.get("limit"), default=20, minimum=1, maximum=100)
410
+ strategy = _optional_str(args, "strategy") or None
411
+ market = _optional_str(args, "market").lower() or None
412
+ return {
413
+ "runs": list_saved_runs(
414
+ data_dir=self.config.data_dir,
415
+ limit=limit,
416
+ strategy=strategy,
417
+ market=market,
418
+ )
419
+ }
420
+
421
+ def _read_skill_markdown(self) -> str:
422
+ candidates = [
423
+ _PROJECT_ROOT / "SKILL.md",
424
+ Path(__file__).resolve().parent / "SKILL.md",
425
+ Path(sys.prefix) / "SKILL.md",
426
+ Path(site.USER_BASE) / "SKILL.md",
427
+ Path.cwd() / "SKILL.md",
428
+ ]
429
+ for path in candidates:
430
+ if path.is_file():
431
+ return path.read_text(encoding="utf-8")
432
+ raise FileNotFoundError("SKILL.md not found")
433
+
434
+ def handle_request(self, request: dict[str, Any]) -> dict[str, Any] | None:
435
+ if not isinstance(request, dict):
436
+ return {
437
+ "jsonrpc": "2.0",
438
+ "id": None,
439
+ "error": {"code": -32600, "message": "Invalid JSON-RPC 2.0 request"},
440
+ }
441
+ raw_id = request.get("id")
442
+ valid_id = raw_id is None or (isinstance(raw_id, (str, int)) and not isinstance(raw_id, bool))
443
+ req_id = raw_id if valid_id else None
444
+
445
+ if request.get("jsonrpc") != "2.0" or not isinstance(request.get("method"), str) or not valid_id:
446
+ return {
447
+ "jsonrpc": "2.0",
448
+ "id": req_id,
449
+ "error": {"code": -32600, "message": "Invalid JSON-RPC 2.0 request"},
450
+ }
451
+
452
+ is_notification = "id" not in request
453
+ method = request["method"]
454
+ params = request.get("params")
455
+ if params is None:
456
+ params = {}
457
+ elif not isinstance(params, dict):
458
+ if is_notification:
459
+ return None
460
+ return {
461
+ "jsonrpc": "2.0",
462
+ "id": req_id,
463
+ "error": {"code": -32602, "message": "Invalid params: expected JSON object"},
464
+ }
465
+
466
+ if method.startswith("notifications/"):
467
+ return None
468
+
469
+ try:
470
+ with redirect_stdout(sys.stderr):
471
+ result = self._dispatch_method(method, params)
472
+ except _RPCParamError as exc:
473
+ if is_notification:
474
+ return None
475
+ return {
476
+ "jsonrpc": "2.0",
477
+ "id": req_id,
478
+ "error": {"code": exc.code, "message": exc.message},
479
+ }
480
+ except Exception as exc: # noqa: BLE001
481
+ if is_notification:
482
+ return None
483
+ return {
484
+ "jsonrpc": "2.0",
485
+ "id": req_id,
486
+ "error": {"code": -32603, "message": f"Internal error: {type(exc).__name__}"},
487
+ }
488
+
489
+ if is_notification:
490
+ return None
491
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
492
+
493
+ def _dispatch_method(self, method: str, params: dict[str, Any]) -> Any:
494
+ if method == "initialize":
495
+ return {
496
+ "protocolVersion": MCP_PROTOCOL_VERSION,
497
+ "capabilities": {
498
+ "tools": {"listChanged": False},
499
+ "resources": {"subscribe": False, "listChanged": False},
500
+ },
501
+ "serverInfo": {"name": "alphasift", "version": __version__},
502
+ }
503
+ if method == "ping":
504
+ return {}
505
+ if method == "tools/list":
506
+ return {"tools": self._tools}
507
+ if method == "tools/call":
508
+ tool_name = params.get("name")
509
+ if not isinstance(tool_name, str) or not tool_name.strip():
510
+ raise _RPCParamError(-32602, "Invalid params: missing tool name")
511
+ handler = self._handlers.get(tool_name)
512
+ if handler is None:
513
+ raise _RPCParamError(-32602, f"Unknown tool: {tool_name}")
514
+ arguments = params.get("arguments")
515
+ if arguments is None:
516
+ arguments = {}
517
+ elif not isinstance(arguments, dict):
518
+ raise _RPCParamError(-32602, "Invalid params: tool arguments must be an object")
519
+ allowed_props = self._tool_props.get(tool_name, set())
520
+ unknown_props = sorted(set(arguments.keys()) - allowed_props)
521
+ if unknown_props:
522
+ raise _RPCParamError(
523
+ -32602,
524
+ f"Unknown arguments for {tool_name}: {', '.join(unknown_props)}",
525
+ )
526
+ try:
527
+ payload = handler(arguments)
528
+ safe_text = json.dumps(
529
+ _json_safe(payload),
530
+ ensure_ascii=False,
531
+ indent=2,
532
+ allow_nan=False,
533
+ )
534
+ return {
535
+ "content": [{"type": "text", "text": safe_text}],
536
+ "isError": False,
537
+ }
538
+ except Exception as exc: # noqa: BLE001
539
+ return {
540
+ "content": [{"type": "text", "text": f"{type(exc).__name__}: {str(exc)[:300]}"}],
541
+ "isError": True,
542
+ }
543
+ if method == "resources/list":
544
+ return {
545
+ "resources": [
546
+ {
547
+ "uri": "alphasift://skill",
548
+ "name": "AlphaSift SKILL.md",
549
+ "description": "Agent workflow and CLI specification for AlphaSift.",
550
+ "mimeType": "text/markdown",
551
+ },
552
+ {
553
+ "uri": "alphasift://strategies",
554
+ "name": "AlphaSift Strategy Catalog",
555
+ "description": "Complete catalog of built-in screening strategies.",
556
+ "mimeType": "application/json",
557
+ },
558
+ ]
559
+ }
560
+ if method == "resources/read":
561
+ uri = params.get("uri")
562
+ if not isinstance(uri, str) or not uri.strip():
563
+ raise _RPCParamError(-32602, "Invalid params: missing resource uri")
564
+ if uri == "alphasift://skill":
565
+ text = self._read_skill_markdown()
566
+ return {"contents": [{"uri": uri, "mimeType": "text/markdown", "text": text}]}
567
+ if uri == "alphasift://strategies":
568
+ payload = {"strategies": [asdict(item) for item in list_strategies(self.config.strategies_dir)]}
569
+ return {
570
+ "contents": [
571
+ {
572
+ "uri": uri,
573
+ "mimeType": "application/json",
574
+ "text": json.dumps(_json_safe(payload), ensure_ascii=False, indent=2, allow_nan=False),
575
+ }
576
+ ]
577
+ }
578
+ raise _RPCParamError(-32602, f"Unknown resource URI: {uri}")
579
+ raise _RPCParamError(-32601, f"Method not found: {method}")
580
+
581
+
582
+ def _read_bounded_line(stream: BinaryIO, limit: int = _MAX_CONTENT_LENGTH) -> bytes:
583
+ line = stream.readline(limit + 1)
584
+ if len(line) > limit:
585
+ raise ValueError("MCP frame line exceeds maximum length")
586
+ return line
587
+
588
+
589
+ class _FramingError(ValueError):
590
+ """Raised when reading a framed STDIO message fails after framing mode is known."""
591
+
592
+ def __init__(self, message: str, *, framing: str = "line") -> None:
593
+ super().__init__(message)
594
+ self.framing = framing
595
+
596
+
597
+ def _read_exact_bytes(stream: BinaryIO, length: int, *, framing: str = "headers") -> bytes:
598
+ chunks: list[bytes] = []
599
+ remaining = length
600
+ while remaining > 0:
601
+ chunk = stream.read(remaining)
602
+ if not chunk:
603
+ raise _FramingError("Truncated Content-Length body", framing=framing)
604
+ chunks.append(chunk)
605
+ remaining -= len(chunk)
606
+ return b"".join(chunks)
607
+
608
+
609
+ def read_stdio_message(stream: BinaryIO) -> tuple[str, bytes] | None:
610
+ """Read either a Content-Length framed body or a newline-delimited JSON line."""
611
+ while True:
612
+ first_line = _read_bounded_line(stream)
613
+ if not first_line:
614
+ return None
615
+ if not first_line.strip():
616
+ continue
617
+ break
618
+
619
+ stripped = first_line.lstrip()
620
+ if stripped.startswith((b"{", b"[")):
621
+ return "line", first_line
622
+
623
+ headers: dict[str, str] = {}
624
+ line = first_line
625
+ header_bytes = 0
626
+ header_lines = 0
627
+ while True:
628
+ if line in (b"\r\n", b"\n", b""):
629
+ break
630
+ header_lines += 1
631
+ header_bytes += len(line)
632
+ if header_lines > _MAX_HEADER_LINES or header_bytes > _MAX_HEADER_BYTES:
633
+ raise _FramingError("MCP headers exceed maximum limits", framing="headers")
634
+ decoded = line.decode("ascii", errors="replace").rstrip("\r\n")
635
+ if ":" in decoded:
636
+ k, v = decoded.split(":", 1)
637
+ key_lower = k.strip().lower()
638
+ val_clean = v.strip()
639
+ if key_lower == "content-length" and key_lower in headers and headers[key_lower] != val_clean:
640
+ raise _FramingError("Conflicting Content-Length headers", framing="headers")
641
+ headers[key_lower] = val_clean
642
+ line = _read_bounded_line(stream, limit=_MAX_HEADER_BYTES)
643
+ if not line:
644
+ return None
645
+
646
+ raw_len = headers.get("content-length")
647
+ if raw_len is None or not raw_len.isdigit():
648
+ raise _FramingError("Missing or invalid Content-Length header", framing="headers")
649
+ length = int(raw_len)
650
+ if length < 0 or length > _MAX_CONTENT_LENGTH:
651
+ raise _FramingError(f"Invalid Content-Length: {length}", framing="headers")
652
+ body = _read_exact_bytes(stream, length, framing="headers")
653
+ return "headers", body
654
+
655
+
656
+ def write_stdio_message(stream: BinaryIO, payload: dict[str, Any], *, framing: str = "line") -> None:
657
+ """Serialize one JSON-RPC response in either header-framed or line-delimited mode."""
658
+ encoded = json.dumps(_json_safe(payload), ensure_ascii=False, allow_nan=False).encode(
659
+ "utf-8", errors="replace"
660
+ )
661
+ if framing == "headers":
662
+ header = f"Content-Length: {len(encoded)}\r\n\r\n".encode("ascii")
663
+ stream.write(header + encoded)
664
+ else:
665
+ stream.write(encoded + b"\n")
666
+ stream.flush()
667
+
668
+
669
+ def serve_mcp(
670
+ config: Config | None = None,
671
+ *,
672
+ in_stream: BinaryIO | None = None,
673
+ out_stream: BinaryIO | None = None,
674
+ ) -> None:
675
+ """Run blocking STDIO JSON-RPC loop for MCP clients."""
676
+ server = MCPServer(config or Config.from_env())
677
+ reader = in_stream or sys.stdin.buffer
678
+ owned_writer: BinaryIO | None = None
679
+
680
+ if out_stream is not None:
681
+ writer = out_stream
682
+ else:
683
+ try:
684
+ protocol_fd = os.dup(sys.stdout.fileno())
685
+ os.dup2(sys.stderr.fileno(), sys.stdout.fileno())
686
+ owned_writer = os.fdopen(protocol_fd, "wb")
687
+ writer = owned_writer
688
+ except (OSError, ValueError, AttributeError):
689
+ writer = sys.stdout.buffer
690
+
691
+ try:
692
+ while True:
693
+ try:
694
+ frame = read_stdio_message(reader)
695
+ except ValueError as exc:
696
+ err_framing = exc.framing if isinstance(exc, _FramingError) else "line"
697
+ write_stdio_message(
698
+ writer,
699
+ {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}},
700
+ framing=err_framing,
701
+ )
702
+ break
703
+ if frame is None:
704
+ break
705
+ framing, body = frame
706
+ try:
707
+ request = json.loads(body.decode("utf-8"))
708
+ except (ValueError, RecursionError):
709
+ write_stdio_message(
710
+ writer,
711
+ {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}},
712
+ framing=framing,
713
+ )
714
+ continue
715
+ response = server.handle_request(request)
716
+ if response is not None:
717
+ write_stdio_message(writer, response, framing=framing)
718
+ finally:
719
+ if owned_writer is not None:
720
+ owned_writer.close()