@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.10

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 (203) hide show
  1. package/CHANGELOG.md +601 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.md +13 -0
  4. package/README.en.md +116 -0
  5. package/README.md +115 -2
  6. package/chart_service.py +687 -0
  7. package/config/basic-symbols.json +570 -0
  8. package/config/dsh-kline.patch.yml +4 -0
  9. package/config/dsh-tool-catalog.json +3875 -0
  10. package/cordis.patch.yml +33 -0
  11. package/core/__init__.py +0 -0
  12. package/core/adjustment.py +16 -0
  13. package/core/calc.py +691 -0
  14. package/core/rows.py +228 -0
  15. package/core/ta_engine.py +99 -0
  16. package/docs/anonymous-market-support.md +33 -0
  17. package/docs/automatic-drawing.md +24 -0
  18. package/docs/chart-functions.md +136 -0
  19. package/docs/drawing-examples.en.md +13 -0
  20. package/docs/drawing-examples.md +13 -0
  21. package/docs/embedding.md +43 -0
  22. package/docs/fixtures/price-pattern-real-v1.json +1 -0
  23. package/docs/free-foreign-daily.md +44 -0
  24. package/docs/guide.en.md +232 -0
  25. package/docs/guide.md +248 -0
  26. package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
  27. package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
  28. package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
  29. package/docs/images/dsh-kline-tab-workspace.png +0 -0
  30. package/docs/images/dsh-market.png +0 -0
  31. package/docs/images/kline-news.png +0 -0
  32. package/docs/images/kline-range-stats.png +0 -0
  33. package/docs/images/kline-support.png +0 -0
  34. package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
  35. package/docs/images/market-overview-v0.6.9.png +0 -0
  36. package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
  37. package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
  38. package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
  39. package/docs/npm-release.md +33 -0
  40. package/docs/price-pattern-rules-v1.md +40 -0
  41. package/docs/price-pattern-samples-v1.md +42 -0
  42. package/docs/provider-adaptation.md +73 -0
  43. package/docs/release-acceptance-v0.4.0.md +46 -0
  44. package/docs/release-acceptance-v0.4.1.md +43 -0
  45. package/docs/release-acceptance-v0.5.0.md +40 -0
  46. package/docs/release-acceptance-v0.6.0.md +33 -0
  47. package/docs/release-acceptance-v0.6.1.md +19 -0
  48. package/docs/release-acceptance-v0.6.10.md +21 -0
  49. package/docs/release-acceptance-v0.6.2.md +31 -0
  50. package/docs/release-acceptance-v0.6.3.md +25 -0
  51. package/docs/release-acceptance-v0.6.4.md +24 -0
  52. package/docs/release-acceptance-v0.6.5.md +21 -0
  53. package/docs/release-acceptance-v0.6.6.md +21 -0
  54. package/docs/release-acceptance-v0.6.7.md +18 -0
  55. package/docs/release-acceptance-v0.6.8.md +18 -0
  56. package/docs/release-acceptance-v0.6.9.md +98 -0
  57. package/docs/release-notes-v0.5.0.md +23 -0
  58. package/docs/release-notes-v0.6.0.md +11 -0
  59. package/docs/release-notes-v0.6.1.md +20 -0
  60. package/docs/release-notes-v0.6.10.md +11 -0
  61. package/docs/release-notes-v0.6.2.md +14 -0
  62. package/docs/release-notes-v0.6.3.md +26 -0
  63. package/docs/release-notes-v0.6.4.md +12 -0
  64. package/docs/release-notes-v0.6.5.md +13 -0
  65. package/docs/release-notes-v0.6.6.md +13 -0
  66. package/docs/release-notes-v0.6.7.md +17 -0
  67. package/docs/release-notes-v0.6.8.md +10 -0
  68. package/docs/release-notes-v0.6.9.md +16 -0
  69. package/lib/candle-sequence.js +15 -0
  70. package/lib/chart-adjustment.js +7 -0
  71. package/lib/chart-annotations.js +33 -0
  72. package/lib/chart-applications.js +171 -0
  73. package/lib/chart-context.js +164 -0
  74. package/lib/chart-observation.js +251 -0
  75. package/lib/chart-service-status.js +82 -0
  76. package/lib/chart-source-status.js +39 -0
  77. package/lib/chart-sources.js +354 -0
  78. package/lib/client/BetterSidebarTab.js +70 -0
  79. package/lib/client/ClassicShell.js +254 -0
  80. package/lib/client/KlineContent.js +155 -0
  81. package/lib/client/chart-apply.js +73 -0
  82. package/lib/client/chart-context.js +233 -0
  83. package/lib/client/chart-handoff.js +34 -0
  84. package/lib/client/chart-session-resolver.js +74 -0
  85. package/lib/client/client-context.js +1 -0
  86. package/lib/client/conversation.js +88 -0
  87. package/lib/client/default-tab.js +83 -0
  88. package/lib/client/embed.js +50 -0
  89. package/lib/client/generated-view.js +12983 -0
  90. package/lib/client/horizontal-lines.js +19 -0
  91. package/lib/client/index.js +62 -0
  92. package/lib/client/mode-preferences.js +28 -0
  93. package/lib/client/native-sidebar-contract.js +45 -0
  94. package/lib/client/native-sidebar-register.js +133 -0
  95. package/lib/client/native-sidebar-services.js +1 -0
  96. package/lib/client/native-sidebar.js +96 -0
  97. package/lib/client/sidebar-integration.js +93 -0
  98. package/lib/client/ui-onboarding.js +42 -0
  99. package/lib/client/version.js +14 -0
  100. package/lib/client.js +17382 -0
  101. package/lib/client.js.map +1 -0
  102. package/lib/drawing-feedback.js +284 -0
  103. package/lib/fibonacci.js +18 -0
  104. package/lib/ftshare-settings-bridge.js +159 -0
  105. package/lib/index.js +279 -0
  106. package/lib/labeled-polyline.js +17 -0
  107. package/lib/pattern-groups.js +91 -0
  108. package/lib/price-bands.js +55 -0
  109. package/lib/price-series.js +47 -0
  110. package/lib/price-sticks.js +32 -0
  111. package/lib/types/candle-sequence.d.ts +2 -0
  112. package/lib/types/chart-adjustment.d.ts +2 -0
  113. package/lib/types/chart-annotations.d.ts +4 -0
  114. package/lib/types/chart-applications.d.ts +26 -0
  115. package/lib/types/chart-context.d.ts +14 -0
  116. package/lib/types/chart-observation.d.ts +8 -0
  117. package/lib/types/chart-service-status.d.ts +22 -0
  118. package/lib/types/chart-source-status.d.ts +47 -0
  119. package/lib/types/chart-sources.d.ts +25 -0
  120. package/lib/types/client/BetterSidebarTab.d.ts +12 -0
  121. package/lib/types/client/ClassicShell.d.ts +4 -0
  122. package/lib/types/client/KlineContent.d.ts +37 -0
  123. package/lib/types/client/chart-apply.d.ts +13 -0
  124. package/lib/types/client/chart-context.d.ts +23 -0
  125. package/lib/types/client/chart-handoff.d.ts +5 -0
  126. package/lib/types/client/chart-session-resolver.d.ts +2 -0
  127. package/lib/types/client/client-context.d.ts +14 -0
  128. package/lib/types/client/conversation.d.ts +43 -0
  129. package/lib/types/client/default-tab.d.ts +3 -0
  130. package/lib/types/client/embed.d.ts +37 -0
  131. package/lib/types/client/generated-view.d.ts +2 -0
  132. package/lib/types/client/horizontal-lines.d.ts +1 -0
  133. package/lib/types/client/index.d.ts +4 -0
  134. package/lib/types/client/mode-preferences.d.ts +13 -0
  135. package/lib/types/client/native-sidebar-contract.d.ts +52 -0
  136. package/lib/types/client/native-sidebar-register.d.ts +46 -0
  137. package/lib/types/client/native-sidebar-services.d.ts +45 -0
  138. package/lib/types/client/native-sidebar.d.ts +47 -0
  139. package/lib/types/client/sidebar-integration.d.ts +12 -0
  140. package/lib/types/client/ui-onboarding.d.ts +6 -0
  141. package/lib/types/client/version.d.ts +1 -0
  142. package/lib/types/drawing-feedback.d.ts +5 -0
  143. package/lib/types/fibonacci.d.ts +5 -0
  144. package/lib/types/ftshare-settings-bridge.d.ts +50 -0
  145. package/lib/types/index.d.ts +26 -0
  146. package/lib/types/labeled-polyline.d.ts +11 -0
  147. package/lib/types/pattern-groups.d.ts +2 -0
  148. package/lib/types/price-bands.d.ts +3 -0
  149. package/lib/types/price-series.d.ts +5 -0
  150. package/lib/types/price-sticks.d.ts +3 -0
  151. package/package.json +153 -4
  152. package/requirements.txt +6 -0
  153. package/screenshots.json +11 -0
  154. package/scripts/bootstrap.sh +5 -0
  155. package/scripts/dsh-bootstrap.mjs +179 -0
  156. package/scripts/dsh-mcp-plugin.mjs +27 -0
  157. package/scripts/run-dsh-kline.mjs +658 -0
  158. package/scripts/run-dsh-kline.sh +5 -0
  159. package/server.py +1755 -0
  160. package/tools/__init__.py +0 -0
  161. package/tools/annotations.py +119 -0
  162. package/tools/automatic_analysis.py +158 -0
  163. package/tools/baostock_source.py +176 -0
  164. package/tools/calc.py +39 -0
  165. package/tools/channel_candidates.py +260 -0
  166. package/tools/channel_preview.py +82 -0
  167. package/tools/channels.py +104 -0
  168. package/tools/chart_applications.py +204 -0
  169. package/tools/chart_context.py +186 -0
  170. package/tools/chart_edits.py +363 -0
  171. package/tools/chart_functions.py +451 -0
  172. package/tools/chart_indicators.py +65 -0
  173. package/tools/chart_measurements.py +84 -0
  174. package/tools/chart_source_status.py +32 -0
  175. package/tools/chart_sources.py +31 -0
  176. package/tools/closed_daily.py +68 -0
  177. package/tools/draw.py +410 -0
  178. package/tools/drawing_feedback.py +45 -0
  179. package/tools/drawing_interaction.py +117 -0
  180. package/tools/drawing_verification.py +141 -0
  181. package/tools/fetch.py +4680 -0
  182. package/tools/fibonacci.py +83 -0
  183. package/tools/foreign_daily.py +185 -0
  184. package/tools/free_sources.py +483 -0
  185. package/tools/lines.py +91 -0
  186. package/tools/nine_count.py +66 -0
  187. package/tools/pattern_groups.py +103 -0
  188. package/tools/pivots.py +60 -0
  189. package/tools/polylines.py +131 -0
  190. package/tools/price_bands.py +165 -0
  191. package/tools/price_patterns.py +311 -0
  192. package/tools/price_series.py +162 -0
  193. package/tools/price_sticks.py +114 -0
  194. package/tools/range_candidates.py +170 -0
  195. package/tools/recent_drawing_candidates.py +123 -0
  196. package/tools/rectangles.py +76 -0
  197. package/tools/regression_channels.py +87 -0
  198. package/tools/ta_functions.py +228 -0
  199. package/tools/trend_lines.py +106 -0
  200. package/tools/watchlist.py +149 -0
  201. package/view/ft-logo.jpg +0 -0
  202. package/view/kline.html +12436 -0
  203. package/view/vendor/klinecharts.min.js +7 -0
package/server.py ADDED
@@ -0,0 +1,1755 @@
1
+ #!/usr/bin/env python3
2
+ """Standalone DeepSeek Harness K-line MCP server.
3
+
4
+ This server owns the optional FTShare fetch adapter and deterministic indicator layer.
5
+ It does not spawn, import, or discover another MCP server.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import asyncio
12
+ import json
13
+ import math
14
+ import re
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Annotated, Any, Literal
18
+
19
+ # Embedded Windows Python's ._pth excludes the script directory. Resolve
20
+ # sibling modules from this package, independently of cwd and PYTHONPATH.
21
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
22
+
23
+ from mcp import types
24
+ from mcp.server.fastmcp import FastMCP
25
+ from pydantic import Field
26
+
27
+ from core.calc import (
28
+ AVAILABLE_METRICS,
29
+ DEFAULT_ATR_PERIOD,
30
+ DEFAULT_BOLL_PERIOD,
31
+ DEFAULT_BOLL_STD,
32
+ DEFAULT_KDJ,
33
+ DEFAULT_MA_PERIODS,
34
+ DEFAULT_RSI_PERIOD,
35
+ DEFAULT_VOLUME_MA,
36
+ series_atr,
37
+ series_boll,
38
+ series_kdj,
39
+ series_ma,
40
+ series_macd,
41
+ series_rsi,
42
+ series_vwap,
43
+ series_vol_ma,
44
+ )
45
+ from chart_service import publish_chart, read_chart_snapshot, start_chart_service
46
+ from tools.drawing_interaction import edit_change, edit_interaction, error_interaction
47
+ from core.rows import RowsValidationError, validate_rows
48
+ from core.adjustment import AdjustmentInput, ADJUSTMENT_DESCRIPTION, normalize_adjustment, adjustment_error
49
+ from tools.calc import run_calc_metrics
50
+ from tools.draw import draw_kline
51
+ from tools.lines import ColorInput, LineError, edit_horizontal_line, horizontal_lines
52
+ from tools.trend_lines import edit_trend_line, trend_lines
53
+ from tools.channels import channels, edit_channel
54
+ from tools.rectangles import rectangles, edit_rectangle
55
+ from tools.drawing_verification import DrawingExpectation, verify_drawings
56
+ from tools.chart_context import read_chart_context
57
+ from tools.chart_edits import ChartEdit, prepare_chart_edit as prepare_guarded_chart_edit
58
+ from tools.chart_functions import ChartFunctionParameters, FunctionName, list_functions, run_function
59
+ from tools.ta_functions import list_ta_catalog, run_ta, read_ta
60
+ from tools.chart_applications import request_chart_apply, read_edit_status
61
+ from tools.fetch import (
62
+ _canonical_market_symbol,
63
+ configure_ftshare_api_key,
64
+ data_source_capability_contract,
65
+ fetch_candles,
66
+ fetch_market_board_detail,
67
+ fetch_market_pulse,
68
+ fetch_security_intelligence,
69
+ ftshare_capabilities,
70
+ ftshare_index_kline_available,
71
+ ftshare_status,
72
+ search_symbols as search_symbol_directory,
73
+ test_ftshare_connection,
74
+ )
75
+ from tools.watchlist import get_watchlist_state, save_watchlist_state
76
+ try: # Built-in free fallback feeds (optional; independent of FTShare)
77
+ from tools.free_sources import free_source_status as builtin_free_source_status
78
+ except Exception: # noqa: BLE001
79
+ builtin_free_source_status = None
80
+
81
+
82
+ mcp = FastMCP(
83
+ "dsh_kline",
84
+ instructions=(
85
+ "IMPORTANT workflow policy: For ordinary K-line requests, call analyze_kline "
86
+ "exactly once. It performs one configured-source fetch, deterministic calculations, "
87
+ "and chart generation against one row set. FTShare is optional: when another tool "
88
+ "or application already has OHLCV rows, call analyze_kline_rows exactly once. "
89
+ "Never call health, fetch_candles, "
90
+ "or calc_metrics as a preflight or follow-up; never use shell, filesystem, "
91
+ "scripts, web probes, or another chart generator for the same request. Do "
92
+ "not switch providers or reconstruct market rows. If the provider rejects a "
93
+ "symbol or interval, explain that error and stop; do not probe other symbols "
94
+ "or substitute another interval unless the user explicitly asks. Use "
95
+ "fetch_candles only when raw OHLCV rows are explicitly requested, and use "
96
+ "calc_metrics only for caller-supplied rows. analyze_kline_rows accepts OHLCV rows "
97
+ "from any user-selected data source without persisting provider state. Only calculate and annotate support "
98
+ "and resistance when the user explicitly requests it: pass metrics including "
99
+ "support_resistance or set mark_support_resistance=true. "
100
+ " In DeepSeek Harness, say that the interactive chart is open in the right "
101
+ "sidebar only when chart_ready is true; otherwise explain that the chart "
102
+ "service is unavailable. Do not create files or claim that a chart was "
103
+ "rendered based on a script or URL. Report count, interval, latest, and "
104
+ "indicator values exactly as returned; do not infer a different bar count "
105
+ "from the selected timeframe. Keep support/resistance labels from the "
106
+ "metrics, but describe whether each level is above or below the latest "
107
+ "close instead of calling an above-price support a current support. "
108
+ "Use data_source_status, configure_ftshare, or test_ftshare_connection only "
109
+ "when the user explicitly asks to inspect or configure a data source. "
110
+ "Use market_pulse for an explicit whole-market overview, and use "
111
+ "security_intelligence for an explicit request about a mainland stock's "
112
+ "sector linkage, capital flows, or trading events; neither tool replaces "
113
+ "analyze_kline for chart analysis. "
114
+ "For the chart currently on screen, use get_chart_context with context_ref "
115
+ "from THIS conversation's current runtime context. Never guess a reference, "
116
+ "borrow another conversation or treat an older chart_session as live UI state. "
117
+ "The context reports browser observations, separate loaded/visible ranges and "
118
+ "stored drawing objects, not visual proof. "
119
+ "After analyze_kline opens a chart, use the newly injected current-view reference "
120
+ "to read its candles; an earlier launcher reference can become inactive during mounting. "
121
+ "An inactive/loading reference is NOT a reason to call fetch_candles or analyze_kline again. "
122
+ "Re-read a fresh reference when available, or report that the view is not ready. "
123
+ "Context references are read-only "
124
+ "and are NOT chart_session tokens. For ALL current-view drawing creates/updates/deletes, "
125
+ "including literal requests, use get_chart_context -> prepare_chart_edit -> apply_chart_edit "
126
+ "-> get_chart_edit_status, never legacy snapshot mutations. "
127
+ "For Fibonacci, labeled paths or reusable geometry, discover list_chart_functions and run_chart_function "
128
+ "against fresh context, then pass edit.result_ref into that same guarded workflow. "
129
+ "Functions calculate; candidate functions find recent rule-based geometry but never apply it. "
130
+ "A direct request to DRAW a named tool or automatic shape authorizes the host to select "
131
+ "the newest valid candidate and finish prepare/apply/status in the same turn, without "
132
+ "another save or confirmation step. Check its type, dates, status and data quality; "
133
+ "if none fits, report that rather than invent geometry. Requests to analyze or propose "
134
+ "only remain read-only. User-specified anchors or candidate numbers take precedence. "
135
+ "Use price_pattern_candidates for reversal shapes, nine_count for Nine Count, "
136
+ "recent_drawing_candidates for ordinary horizontal/trend/Fibonacci/ABC, and "
137
+ "channel_candidates/range_candidates for automatic channel/range drawings. "
138
+ "For standard technical indicators on the current loaded chart, discover list_ta_functions, "
139
+ "then run_ta_function and optionally read_ta_result. These TA-Lib results are analysis_only, "
140
+ "may have null/no-finite outputs, and do not draw by themselves. Only when the user explicitly "
141
+ "requests a price-pane drawing may a finite SMA/EMA(close, 2..200) result be selected as "
142
+ "kind=series_line, or a finite BBANDS(close, SMA middle) result as one kind=price_band "
143
+ "three-line group, but only when selectable_render_targets advertises that kind. Pass the "
144
+ "result_ref as edit.ta_result_ref into prepare_chart_edit; other TA results remain read-only. "
145
+ "Never copy long output arrays into edit parameters. "
146
+ "prepare_chart_edit prepares one guarded candidate using the observed revision and aligned source "
147
+ "chart_session; supply a stable request_id for retries. Preparation does NOT apply "
148
+ "to the browser. Then apply_chart_edit queues that exact candidate to its owning view; "
149
+ "get_chart_edit_status reads its acknowledgment. queued/delivered are NOT applied. "
150
+ "applied confirms view STATE, not screen pixels. Unknown results must not be automatically "
151
+ "resent or bypassed with old snapshot-only tools. Read fresh current context before the next edit. "
152
+ "For pending status use one bounded wait_ms=3000 query; if still pending explain it, "
153
+ "do not tightly poll. expired/needs_attention is not an acknowledgment or permission to resend. "
154
+ "drawing_feedback reports browser chart-object API observations, not screen pixels. "
155
+ "created means registered object with matched shape/style; time_range_overlap only checks "
156
+ "the reported time-axis span (current in get_chart_context, historical in get_chart_edit_status), "
157
+ "NOT price-axis visibility or screen pixels. "
158
+ "outside_time_viewport is geometric scope only, and outside_loaded_price_envelope is a warning, "
159
+ "NOT proof the line is hidden. The edit interaction describes only its target object; "
160
+ "other drawing_feedback items may need separate review. "
161
+ "Explain hidden/failed/unknown items and their reasons; never turn apply_status=applied or "
162
+ "created into a claim of visual verification. get_chart_context feedback is current-view "
163
+ "observation; get_chart_edit_status feedback is historical for that application. "
164
+ "Do not silently apply snapshot-only tools to a different "
165
+ "symbol/period/range shown in the browser. If context is stale, ambiguous or "
166
+ "unavailable explain that state instead of re-fetching market data to guess it. "
167
+ "The create/update/delete_horizontal_line and create/update/delete_trend_line tools "
168
+ "are LEGACY SNAPSHOT ONLY, for explicitly requested snapshot editing, not charts on screen. "
169
+ "get_horizontal_lines/get_trend_lines read named snapshots only. Execution tools do not choose "
170
+ "anchors. Two-point segments require two explicit "
171
+ "times and prices; date-only anchors use Asia/Shanghai and must match existing "
172
+ "bars. Intraday anchors require exact bar-close ISO times with timezone or Unix "
173
+ "seconds. Never fabricate unavailable anchors, snap dates, or substitute automatic levels. "
174
+ "Distinguish literal drawing from analysis-assisted drawing. For literal requests, "
175
+ "preserve the original USER-requested fields and ask about missing or ambiguous coordinates. "
176
+ "For a direct automatic drawing request with no coordinates, use the appropriate candidate "
177
+ "function on this current chart and apply its newest suitable result without another prompt. "
178
+ "The host reviews the result first; a candidate on another symbol, period or source is unusable. "
179
+ "When the user explicitly asks you to find/analyze a region or propose a drawing, "
180
+ "YOU, the host, may derive a candidate from this conversation's actual chart candles; "
181
+ "read fresh current context before making the proposal, not just old conversation rows. "
182
+ "execution tools do not choose anchors or assess pattern quality. Do not ask the user "
183
+ "to supply every coordinate merely because the execution tool needs explicit parameters. "
184
+ "If the user asks for a proposal first, do not prepare, queue or mutate drawings before "
185
+ "their confirmation. Give one preferred candidate with exact existing-bar dates, prices, "
186
+ "a short data-grounded reason and a limitation; offer alternatives only when materially useful. "
187
+ "Treat the user's confirmation as approval of THAT stated proposal plus their overrides. "
188
+ "After confirmation read fresh context; if instrument/period/rows or relevant objects "
189
+ "have changed, reassess and seek confirmation rather than silently moving the approved bounds. "
190
+ "Numerical claims must agree with the candles; do not call volume monotonically declining "
191
+ "when an intervening bar increases, or describe a subjective candidate as uniquely correct. "
192
+ "For a chosen region, get_chart_context with region_start_time/region_end_time returns "
193
+ "deterministic region_measurements without fetching or changing charts. body_envelope "
194
+ "contains all open/close bodies; body_overlap is their common intersection, not the same range. "
195
+ "Use boundary_evidence for the actual date and open/close field of each extremum. "
196
+ "An empty intersection has no price shared by EVERY body; a point intersection shares exactly one. "
197
+ "Never reinterpret relation=empty/exists=false as a shared zero-width point. "
198
+ "Empty common intersection does NOT imply a gap uncovered by ANY body. The candidate "
199
+ "difference is not an uncovered gap; union coverage is not measured. State only the "
200
+ "measured result and its evidence, without extra coverage claims. "
201
+ "Use volume_changes to distinguish a net decline from a monotonic decline. These measurements "
202
+ "do NOT classify the region as a platform. Check chosen bounds with this before asking approval. "
203
+ "If the data do not support a consolidation region, say so; do not force a platform, "
204
+ "invent prices or imply a profitable prediction. Keep ordinary replies concise: proposal "
205
+ "or changed object, reason/limitation, and one useful next action; omit internal IDs, "
206
+ "revisions and protocol fields unless the user requests them or they explain a failure. "
207
+ "For current-view parallel channels use prepare_chart_edit with kind=channel; "
208
+ "create/update/delete_channel are LEGACY SNAPSHOT ONLY. Geometry requires "
209
+ "two baseline anchors and a third time/price on the other boundary, within the "
210
+ "start/end window. In literal mode ask for missing anchors; in authorized analysis mode "
211
+ "derive and explain all three from real data under the proposal rules above. Geometry uses candle indices and "
212
+ "linear prices, not elapsed calendar time. "
213
+ "Before proposing a host-chosen channel, use read-only preview_chart_channel with three explicit "
214
+ "anchors to check parallel geometry and full-region per-bar deviations. It never selects/fits "
215
+ "anchors, draws, scores pattern quality or extends beyond the chosen dates. Horizontal body "
216
+ "intersection is not a necessary criterion for a sloped channel. "
217
+ "For current-view platform/range boxes use prepare_chart_edit with kind=rectangle; "
218
+ "create/update/delete_rectangle are LEGACY SNAPSHOT ONLY. Specify start/end bar times and lower/upper "
219
+ "prices. These draw finite rectangles, not automatic consolidation detection "
220
+ "or flat channels. Ask for missing bounds in literal mode; an authorized host analysis "
221
+ "may propose bounds from actual candles, but the execution tool always needs explicit values. "
222
+ "Never swap reversed times/prices or replace "
223
+ "a rectangle with two horizontal lines. "
224
+ "Preserve the user's FULL requested label, without abbreviating T or U. Honor "
225
+ "explicit colors: blue/蓝色=info, green/绿色=success, orange/橙色=warning, "
226
+ "red/红色=danger. The token success in drawing style requests means green, "
227
+ "not a generic success status. After each mutation call verify_chart_drawings "
228
+ "with the original USER-requested fields, or the user-approved proposal and overrides, "
229
+ "and the returned stable ID, NOT fields copied from the mutation result. Keep those "
230
+ "expectations independently of the execution result. Verify exists=false after deletion; include "
231
+ "requested name/color/anchors on create/update. If mismatched, correct only "
232
+ "those requested fields using latest chart_session and verify again. Do not "
233
+ "claim a name/color was applied merely because publication succeeded. A matched "
234
+ "snapshot check is not visual verification. "
235
+ "Perform drawing mutations sequentially, using each returned new chart_session; "
236
+ "parallel edits of the same parent snapshot create branches, not a merged chart. "
237
+ "Drawing tools never "
238
+ "fetch candles; always use the latest chart_session returned in this "
239
+ "conversation and its exact symbol. A mutation publishes a NEW immutable "
240
+ "chart snapshot. It does not include manual browser edits. Do not re-run "
241
+ "analyze_kline just to edit a line. Published commands are not proof of "
242
+ "visible rendering: when render_verified is false say they were published, "
243
+ "not visually verified. "
244
+ "Market data may be delayed, incomplete, or unavailable; results and indicators "
245
+ "are informational and do not constitute investment advice."
246
+ ),
247
+ json_response=True,
248
+ )
249
+
250
+
251
+ _SUPPORTED_INDICATORS = frozenset({"ma", "ema", "vol", "macd", "kdj", "boll", "rsi", "atr", "vwap"})
252
+ _SYMBOL_PATTERN = re.compile(r"^[A-Z0-9][A-Z0-9_-]{0,15}(?:\.[A-Z]{2,6})?$", re.IGNORECASE)
253
+ _SUPPORTED_INTERVALS = ("minute", "day", "week", "month", "quarter", "year")
254
+
255
+
256
+ def _validate_interval(value: Any) -> tuple[str | None, dict[str, Any] | None]:
257
+ """Return a normalized interval and a user-facing error without Pydantic internals."""
258
+ raw = str(value or "").strip().lower()
259
+ if raw in _SUPPORTED_INTERVALS:
260
+ return raw, None
261
+ return None, {
262
+ "error": "unsupported_interval",
263
+ "message": f"不支持的 K 线周期“{value}”。请选择:{'、'.join(_SUPPORTED_INTERVALS)}。",
264
+ "supported_intervals": list(_SUPPORTED_INTERVALS),
265
+ }
266
+
267
+
268
+ def _resolve_symbol_input(value: Any) -> tuple[str | None, str | None, dict[str, Any] | None]:
269
+ """Resolve a local-directory name/code without making a provider request."""
270
+ raw = str(value or "").strip()
271
+ if not raw:
272
+ return None, None, {
273
+ "error": "invalid_symbol",
274
+ "message": "请输入标的代码或名称,例如 600519.SH、00700.HK、NVDA.US。",
275
+ }
276
+ directory = search_symbol_directory(raw, limit=8)
277
+ results = directory.get("results") if isinstance(directory, dict) else None
278
+ if isinstance(results, list) and results:
279
+ exact_codes = [item for item in results if str(item.get("symbol", "")).split(".")[0] == raw]
280
+ if len(exact_codes) > 1:
281
+ return None, None, {"error": "ambiguous_symbol", "message": "该代码对应多个市场或标的,请选择完整代码。", "candidates": exact_codes}
282
+ folded = raw.casefold()
283
+ exact = next(
284
+ (item for item in results if str(item.get("symbol") or "").casefold() == folded
285
+ or str(item.get("name") or "").casefold() == folded),
286
+ results[0],
287
+ )
288
+ symbol = str(exact.get("symbol") or "").strip().upper()
289
+ if symbol:
290
+ return symbol, str(exact.get("name") or symbol), None
291
+ normalized = _canonical_market_symbol(raw)
292
+ # Keep provider-specific symbols usable even when the local directory has
293
+ # not been refreshed yet; reject unresolved natural-language names with a
294
+ # useful, actionable message instead of a cryptic upstream error.
295
+ if _SYMBOL_PATTERN.fullmatch(normalized):
296
+ return normalized, None, None
297
+ return None, None, {
298
+ "error": "invalid_symbol",
299
+ "message": f"未找到标的“{raw}”。" + (str(directory.get("message")) if directory.get("message") else "请使用完整代码,例如 600519.SH、00700.HK、NVDA.US。"),
300
+ "query": raw,
301
+ "candidates": results[:5] if isinstance(results, list) else [],
302
+ }
303
+
304
+
305
+ def _normalized_indicators(values: list[str] | None) -> tuple[list[str], list[str]]:
306
+ # Calm default stack: MA + VOL + MACD on the main chart. RSI, BOLL, KDJ,
307
+ # ATR and VWAP are added only when explicitly requested.
308
+ requested = [str(value).strip().lower() for value in (values or ["ma", "vol", "macd"])]
309
+ active = list(dict.fromkeys(value for value in requested if value in _SUPPORTED_INDICATORS))
310
+ unknown = list(dict.fromkeys(value for value in requested if value not in _SUPPORTED_INDICATORS))
311
+ return active, unknown
312
+
313
+
314
+ def _normalized_ma_periods(values: list[int] | None) -> list[int]:
315
+ periods = [int(value) for value in (values or DEFAULT_MA_PERIODS)]
316
+ if not 1 <= len(periods) <= 8 or any(period < 2 or period > 400 for period in periods):
317
+ raise ValueError("ma_periods must contain 1-8 values between 2 and 400")
318
+ return list(dict.fromkeys(periods))
319
+
320
+
321
+ def _result(payload: dict[str, Any], text: str, *, error: bool = False) -> types.CallToolResult:
322
+ return types.CallToolResult(
323
+ content=[types.TextContent(type="text", text=text)],
324
+ structuredContent=payload,
325
+ isError=error,
326
+ )
327
+
328
+
329
+ def _error_text(payload: dict[str, Any], fallback: str) -> str:
330
+ code = str(payload.get("error") or "").strip()
331
+ message = str(payload.get("message") or code or fallback).strip()
332
+ return f"{code}: {message}" if code and code not in message else message
333
+
334
+
335
+ def _latest(mapping: dict[int, float], timestamp: int) -> float | None:
336
+ value = mapping.get(timestamp)
337
+ return float(value) if value is not None else None
338
+
339
+
340
+ def _indicator_last(
341
+ rows: list[dict[str, Any]],
342
+ indicators: list[str],
343
+ *,
344
+ ma_periods: list[int],
345
+ rsi_period: int,
346
+ boll_period: int,
347
+ boll_std: float,
348
+ volume_ma: int,
349
+ atr_period: int,
350
+ ) -> dict[str, Any]:
351
+ timestamp = int(rows[-1]["time"])
352
+ result: dict[str, Any] = {}
353
+ if "ma" in indicators:
354
+ result["ma"] = {
355
+ name: value
356
+ for name, values in series_ma(rows, ma_periods).items()
357
+ if (value := _latest(values, timestamp)) is not None
358
+ }
359
+ if "vol" in indicators:
360
+ result["volume"] = float(rows[-1].get("volume") or 0.0)
361
+ result["volume_ma"] = _latest(series_vol_ma(rows, volume_ma), timestamp)
362
+ if "macd" in indicators:
363
+ result["macd"] = {
364
+ name: _latest(values, timestamp)
365
+ for name, values in series_macd(rows).items()
366
+ }
367
+ if "kdj" in indicators:
368
+ result["kdj"] = {
369
+ name: _latest(values, timestamp)
370
+ for name, values in series_kdj(rows, *DEFAULT_KDJ).items()
371
+ }
372
+ if "boll" in indicators:
373
+ result["boll"] = {
374
+ name: _latest(values, timestamp)
375
+ for name, values in series_boll(rows, boll_period, boll_std).items()
376
+ }
377
+ if "rsi" in indicators:
378
+ result["rsi"] = _latest(series_rsi(rows, rsi_period), timestamp)
379
+ if "atr" in indicators:
380
+ result["atr"] = _latest(series_atr(rows, atr_period), timestamp)
381
+ if "vwap" in indicators:
382
+ result["vwap"] = _latest(series_vwap(rows), timestamp)
383
+ return result
384
+
385
+
386
+ def _support_resistance_marks(metrics: dict[str, Any]) -> list[dict[str, Any]]:
387
+ levels = metrics.get("support_resistance")
388
+ if not isinstance(levels, dict):
389
+ return []
390
+
391
+ marks: list[dict[str, Any]] = []
392
+ for kind, label, color in (
393
+ ("support", "支撑", "success"),
394
+ ("resistance", "压力", "danger"),
395
+ ):
396
+ candidates = levels.get(kind)
397
+ if not isinstance(candidates, list):
398
+ continue
399
+ for index, level in enumerate(candidates[:5]):
400
+ if not isinstance(level, dict):
401
+ continue
402
+ try:
403
+ price = float(level["price"])
404
+ timestamp = int(level["last_time"])
405
+ touches = max(0, int(level.get("touches") or 0))
406
+ except (KeyError, TypeError, ValueError):
407
+ continue
408
+ if not math.isfinite(price) or timestamp <= 0:
409
+ continue
410
+ display_price = round(price, 2)
411
+ text = f"{label} {display_price:.2f}"
412
+ if touches:
413
+ text += f" · 邻近{touches}根"
414
+ marks.append(
415
+ {
416
+ "id": f"{kind}:{timestamp}:{index}",
417
+ "time": timestamp,
418
+ "price": display_price,
419
+ "text": text,
420
+ "color": color,
421
+ }
422
+ )
423
+ return marks
424
+
425
+
426
+ def _chart_spec(
427
+ rows: list[dict[str, Any]],
428
+ indicators: list[str],
429
+ ma_periods: list[int],
430
+ interval: str,
431
+ marks: list[dict[str, Any]] | None = None,
432
+ ) -> dict[str, Any]:
433
+ """Return provider-neutral chart data for future dsh-native UI support."""
434
+ return {
435
+ "type": "kline",
436
+ "interval": interval,
437
+ "rows": rows,
438
+ "indicators": indicators,
439
+ "ma_periods": ma_periods,
440
+ "marks": list(marks or []),
441
+ "range": {"start": int(rows[0]["time"]), "end": int(rows[-1]["time"])},
442
+ }
443
+
444
+
445
+ def _analysis_from_rows(
446
+ rows: list[dict[str, Any]],
447
+ *,
448
+ symbol: str,
449
+ name: str | None,
450
+ interval: str,
451
+ limit: int,
452
+ adjust: str,
453
+ indicators: list[str] | None,
454
+ metrics: list[str] | None,
455
+ mark_support_resistance: bool,
456
+ ma_periods: list[int] | None,
457
+ rsi_period: int,
458
+ boll_period: int,
459
+ boll_std: float,
460
+ volume_ma: int,
461
+ atr_period: int,
462
+ data_source: str | None,
463
+ data_source_url: str | None,
464
+ security_workspace: dict[str, Any] | None,
465
+ ) -> dict[str, Any]:
466
+ """Run the complete chart workflow on caller-supplied rows."""
467
+ canonical_adjust = normalize_adjustment(adjust)
468
+ if canonical_adjust is None:
469
+ return adjustment_error()
470
+ adjust = canonical_adjust
471
+ normalized = validate_rows(rows, min_len=2)
472
+ selected = normalized[-max(2, min(int(limit), 4000)):]
473
+ active_indicators, unknown_indicators = _normalized_indicators(indicators)
474
+ periods = _normalized_ma_periods(ma_periods)
475
+ requested_metrics = [str(value).lower() for value in metrics] if metrics is not None else ["rsi"]
476
+ should_mark_levels = mark_support_resistance or "support_resistance" in requested_metrics
477
+ if mark_support_resistance and "support_resistance" not in requested_metrics:
478
+ requested_metrics.append("support_resistance")
479
+ metric_data = run_calc_metrics(
480
+ selected,
481
+ metrics=requested_metrics,
482
+ rsi_period=rsi_period,
483
+ boll_period=boll_period,
484
+ boll_std=boll_std,
485
+ atr_period=atr_period,
486
+ volume_ma=volume_ma,
487
+ ma_periods=periods,
488
+ )
489
+ analysis_marks = _support_resistance_marks(metric_data) if should_mark_levels else []
490
+ previous = float(selected[-2]["close"])
491
+ latest = dict(selected[-1])
492
+ latest["change"] = round(float(latest["close"]) - previous, 6)
493
+ latest["change_pct"] = round((float(latest["close"]) / previous - 1) * 100, 4) if previous else None
494
+ source = str(data_source or "external").strip()[:120] or "external"
495
+ chart_payload = draw_kline(
496
+ selected,
497
+ indicators=active_indicators,
498
+ indicators_explicit=indicators is not None,
499
+ ma_periods=periods,
500
+ marks=analysis_marks,
501
+ security_workspace=security_workspace,
502
+ symbol=symbol,
503
+ name=name or symbol,
504
+ data_source=source,
505
+ data_source_url=data_source_url,
506
+ interval=interval,
507
+ boll_period=boll_period,
508
+ boll_std=boll_std,
509
+ volume_ma=volume_ma,
510
+ rsi_period=rsi_period,
511
+ atr_period=atr_period,
512
+ )
513
+ chart_payload["adjust"] = adjust
514
+ chart = _chart_spec(selected, active_indicators, periods, interval, analysis_marks)
515
+ chart_session: str | None = None
516
+ chart_service_status: dict[str, Any]
517
+ try:
518
+ chart_session, _service_url = publish_chart(chart_payload)
519
+ chart["session_id"] = chart_session
520
+ chart_service_status = {"ok": True}
521
+ except Exception as exc: # noqa: BLE001
522
+ chart_service_status = {"ok": False, "error": "chart_service_unavailable", "message": str(exc)}
523
+ return {
524
+ "ok": True,
525
+ "workflow": "provided_rows_analyze_chart_session",
526
+ "provider_mode": "external",
527
+ "symbol": symbol,
528
+ "name": name or symbol,
529
+ "interval": interval,
530
+ "adjust": adjust,
531
+ "source": source,
532
+ "status": "provided",
533
+ "count": len(selected),
534
+ "fetched_count": len(normalized),
535
+ "freshness": "provided_by_caller",
536
+ "chart_session": chart_session,
537
+ "chart_ready": bool(chart_session and chart_service_status.get("ok")),
538
+ "chart_service": chart_service_status,
539
+ "latest": latest,
540
+ "indicator_last": _indicator_last(
541
+ selected,
542
+ active_indicators,
543
+ ma_periods=periods,
544
+ rsi_period=rsi_period,
545
+ boll_period=boll_period,
546
+ boll_std=boll_std,
547
+ volume_ma=volume_ma,
548
+ atr_period=atr_period,
549
+ ),
550
+ "metrics": metric_data,
551
+ "chart": chart,
552
+ "warnings": ([f"ignored unsupported indicators: {', '.join(unknown_indicators)}"] if unknown_indicators else []),
553
+ }
554
+
555
+
556
+ @mcp.tool(name="health")
557
+ async def health() -> types.CallToolResult:
558
+ """Check runtime health only when the user explicitly asks for a health check."""
559
+ ftshare = ftshare_status()
560
+ data = {
561
+ "ok": True,
562
+ "server": "dsh_kline",
563
+ "capabilities": {"external_rows": True, "ftshare_adapter": bool(ftshare.get("available"))},
564
+ "ftshare": ftshare,
565
+ }
566
+ state = "available" if data["capabilities"]["ftshare_adapter"] else "optional/missing"
567
+ return _result(data, f"health ok · external_rows=available · ftshare={state}")
568
+
569
+
570
+ @mcp.tool(name="data_source_status")
571
+ async def data_source_status() -> types.CallToolResult:
572
+ """Return safe data-source capability/configuration status for the UI."""
573
+ ftshare = ftshare_status()
574
+ providers: dict[str, Any] = {
575
+ "ftshare": {
576
+ "available": bool(ftshare.get("available")),
577
+ "configured": bool(ftshare.get("configured")),
578
+ "persistent": bool(ftshare.get("persistent")),
579
+ "credential_source": ftshare.get("credential_source", "none"),
580
+ "can_clear": bool(ftshare.get("can_clear")),
581
+ "capabilities": ftshare_capabilities(),
582
+ "index_kline": ftshare_index_kline_available(),
583
+ "sdk_version": ftshare.get("sdk_version"),
584
+ "contracts": ftshare.get("contracts", {}),
585
+ "optional_capabilities": ["minute_candles", "news", "market_data", "company_data"],
586
+ }
587
+ }
588
+ if builtin_free_source_status is not None:
589
+ try:
590
+ providers["builtin_free"] = builtin_free_source_status()
591
+ except Exception: # noqa: BLE001
592
+ providers["builtin_free"] = {"available": False, "source": "builtin_free"}
593
+ data = {
594
+ "ok": True,
595
+ "external_rows": True,
596
+ "providers": providers,
597
+ "capability_contract": data_source_capability_contract(),
598
+ }
599
+ return _result(data, "data_source_status ok")
600
+
601
+
602
+ @mcp.tool(name="search_symbols")
603
+ async def search_symbols_tool(
604
+ query: Annotated[str, Field(description="标的代码、名称或常用简称")],
605
+ limit: Annotated[int, Field(ge=1, le=20, description="最多返回的候选数量")] = 8,
606
+ ) -> types.CallToolResult:
607
+ """Search the local symbol directory; this does not call a market provider."""
608
+ data = search_symbol_directory(query, limit=limit)
609
+ if not data.get("ok"):
610
+ return _result(data, str(data.get("message") or data.get("error") or "搜索失败"), error=True)
611
+ candidates = ";".join(f"{item['name']} ({item['symbol']})" for item in data.get("results", [])[:5])
612
+ return _result(data, f"search_symbols · {candidates or data.get('message') or '未找到匹配标的'}")
613
+
614
+
615
+ @mcp.tool(name="configure_ftshare")
616
+ async def configure_ftshare(
617
+ api_key: Annotated[str | None, Field(description="FTShare API Key;留空可清除当前配置")]=None,
618
+ test_connection: Annotated[bool, Field(description="配置后是否发起一次最小连接测试")]=True,
619
+ persist: Annotated[bool, Field(description="是否保存到本机,默认保存")]=True,
620
+ ) -> types.CallToolResult:
621
+ """Configure FTShare without returning the key; results include safe capability status."""
622
+ data = configure_ftshare_api_key(api_key, test_connection=test_connection, persist=persist)
623
+ if not data.get("ok"):
624
+ return _result(data, str(data.get("message") or data.get("error") or "FTShare 配置失败"), error=True)
625
+ return _result(data, str(data.get("message") or "FTShare 配置已更新"))
626
+
627
+
628
+ @mcp.tool(name="test_ftshare_connection")
629
+ async def test_ftshare_connection_tool() -> types.CallToolResult:
630
+ """Test the current anonymous/API-key FTShare connection without changing it."""
631
+ data = test_ftshare_connection()
632
+ if not data.get("ok"):
633
+ return _result(data, str(data.get("message") or data.get("error") or "FTShare 连接失败"), error=True)
634
+ return _result(data, str(data.get("message") or "FTShare 连接成功"))
635
+
636
+
637
+ @mcp.tool(name="market_pulse")
638
+ async def market_pulse(
639
+ refresh: Annotated[bool, Field(description="是否绕过短时缓存并重新拉取")] = False,
640
+ sections: Annotated[list[str] | None, Field(description="可选:仅加载 breadth、flows、sectors、concepts、rankings、events 中指定分组")]=None,
641
+ ) -> types.CallToolResult:
642
+ """Read selected market-intelligence sections; callers can load groups progressively."""
643
+ data = fetch_market_pulse(refresh=refresh, sections=sections)
644
+ if not data.get("ok"):
645
+ return _result(data, str(data.get("message") or data.get("error") or "市场脉搏加载失败"), error=True)
646
+ pulse = data.get("market_pulse") or {}
647
+ return _result(data, f"market_pulse · {pulse.get('as_of') or 'latest'} · sectors={len(pulse.get('hot_sectors') or [])}")
648
+
649
+
650
+ @mcp.tool(name="market_board_detail")
651
+ async def market_board_detail(
652
+ name: Annotated[str, Field(description="行业或概念板块名称")],
653
+ board_code: Annotated[str | None, Field(description="市场快照返回的板块代码")] = None,
654
+ kind: Annotated[Literal["industry", "concept"], Field(description="板块类型")] = "industry",
655
+ ) -> types.CallToolResult:
656
+ """Read a market board snapshot and available funding history."""
657
+ data = fetch_market_board_detail(name, board_code=board_code, kind=kind)
658
+ if not data.get("ok"):
659
+ return _result(data, str(data.get("message") or data.get("error") or "板块详情加载失败"), error=True)
660
+ board = data.get("board") or {}
661
+ return _result(data, f"market_board_detail · {board.get('name') or name} · history={len(board.get('history') or [])}")
662
+
663
+
664
+ @mcp.tool(name="security_intelligence")
665
+ async def security_intelligence(
666
+ symbol: Annotated[str, Field(description="沪深北股票代码,例如 600519.XSHG")],
667
+ refresh: Annotated[bool, Field(description="是否绕过短时缓存并重新拉取")] = False,
668
+ ) -> types.CallToolResult:
669
+ """Read sector linkage, stock capital flow and trading-event context independently from charts."""
670
+ resolved_symbol, resolved_name, symbol_error = _resolve_symbol_input(symbol)
671
+ if symbol_error:
672
+ return _result({"ok": False, **symbol_error}, symbol_error["message"], error=True)
673
+ data = fetch_security_intelligence(resolved_symbol or symbol, name=resolved_name, refresh=refresh)
674
+ if not data.get("ok"):
675
+ return _result(data, str(data.get("message") or data.get("error") or "标的情报加载失败"), error=True)
676
+ intel = data.get("security_intelligence") or {}
677
+ return _result(data, f"security_intelligence · {data.get('symbol')} · flows={len(intel.get('flows') or [])} · events={len(intel.get('events') or [])}")
678
+
679
+
680
+ @mcp.tool(name="get_watchlist")
681
+ async def get_watchlist() -> types.CallToolResult:
682
+ """Read the user's persistent dsh_kline watchlist, shared across conversations."""
683
+ data = {"ok": True, "watchlist": get_watchlist_state()}
684
+ return _result(data, f"get_watchlist · {len(data['watchlist'].get('items') or [])} symbols")
685
+
686
+
687
+ @mcp.tool(name="save_watchlist")
688
+ async def save_watchlist(
689
+ watchlist: Annotated[dict[str, Any], Field(description="完整自选状态:groups、items、activeGroupId、sort")],
690
+ ) -> types.CallToolResult:
691
+ """Replace the user's persistent watchlist with a validated complete state."""
692
+ data = save_watchlist_state(watchlist)
693
+ if not data.get("ok"):
694
+ return _result(data, str(data.get("message") or "自选保存失败"), error=True)
695
+ saved = data.get("watchlist") or {}
696
+ return _result(data, f"save_watchlist · {len(saved.get('items') or [])} symbols")
697
+
698
+
699
+ @mcp.tool(name="fetch_candles")
700
+ async def fetch_candles_tool(
701
+ symbol: Annotated[str, Field(description="标的代码,如 00700.HK / 600519.XSHG / NVDA.US")],
702
+ interval: Annotated[str, Field(description="K 线周期:minute / day / week / month / quarter / year")] = "day",
703
+ interval_value: Annotated[int, Field(ge=1, le=240, description="分钟粒度")] = 1,
704
+ session_count: Annotated[int | None, Field(ge=1, le=10, description="分钟 K 的交易日数量")] = None,
705
+ limit: Annotated[int, Field(ge=2, le=4000, description="回看窗口")] = 220,
706
+ adjust: Annotated[AdjustmentInput, Field(description=ADJUSTMENT_DESCRIPTION)] = "none",
707
+ ) -> types.CallToolResult:
708
+ """Fetch raw OHLCV rows only when the user explicitly requests raw candle data."""
709
+ canonical_adjust = normalize_adjustment(adjust)
710
+ if canonical_adjust is None:
711
+ data = adjustment_error()
712
+ return _result(data, data["message"], error=True)
713
+ adjust = canonical_adjust
714
+ normalized_interval, interval_error = _validate_interval(interval)
715
+ if interval_error:
716
+ return _result({"ok": False, **interval_error}, interval_error["message"], error=True)
717
+ resolved_symbol, _resolved_name, symbol_error = _resolve_symbol_input(symbol)
718
+ if symbol_error:
719
+ return _result({"ok": False, **symbol_error}, symbol_error["message"], error=True)
720
+ data = fetch_candles(
721
+ resolved_symbol or symbol,
722
+ interval=normalized_interval or "day",
723
+ interval_value=interval_value,
724
+ session_count=session_count,
725
+ limit=limit,
726
+ adjust=adjust,
727
+ )
728
+ if not data.get("ok"):
729
+ return _result(data, _error_text(data, "fetch failed"), error=True)
730
+ return _result(
731
+ data,
732
+ f"fetch_candles · {data.get('symbol')} · {data.get('count')} bars · source={data.get('source')}",
733
+ )
734
+
735
+
736
+ @mcp.tool(name="calc_metrics")
737
+ async def calc_metrics(
738
+ rows: Annotated[list[dict[str, Any]], Field(description="canonical OHLCV rows with unix-second time")],
739
+ metrics: Annotated[list[str] | None, Field(description="指标子集:" + ", ".join(AVAILABLE_METRICS))] = None,
740
+ rsi_period: Annotated[int, Field(ge=2, le=100)] = DEFAULT_RSI_PERIOD,
741
+ boll_period: Annotated[int, Field(ge=2, le=200)] = DEFAULT_BOLL_PERIOD,
742
+ boll_std: Annotated[float, Field(ge=0.5, le=5.0)] = DEFAULT_BOLL_STD,
743
+ atr_period: Annotated[int, Field(ge=2, le=100)] = DEFAULT_ATR_PERIOD,
744
+ volume_ma: Annotated[int, Field(ge=2, le=200)] = DEFAULT_VOLUME_MA,
745
+ ) -> types.CallToolResult:
746
+ """Calculate metrics only for rows explicitly supplied by the caller."""
747
+ if not isinstance(rows, list):
748
+ data = {"ok": False, "error": "invalid_external_rows", "message": "rows must be a list"}
749
+ return _result(data, data["message"], error=True)
750
+ if len(rows) > 12000:
751
+ data = {"ok": False, "error": "too_many_rows", "message": "rows exceeds the 12000-item input safety limit"}
752
+ return _result(data, data["message"], error=True)
753
+ try:
754
+ data = run_calc_metrics(
755
+ rows,
756
+ metrics=metrics,
757
+ rsi_period=rsi_period,
758
+ boll_period=boll_period,
759
+ boll_std=boll_std,
760
+ atr_period=atr_period,
761
+ volume_ma=volume_ma,
762
+ )
763
+ except Exception as exc: # noqa: BLE001
764
+ return _result({"ok": False, "error": "calc_failed", "message": str(exc)}, str(exc), error=True)
765
+ unknown = data.get("metrics_unknown") or []
766
+ warning = f" · warnings=ignored unsupported metrics: {','.join(unknown)}" if unknown else ""
767
+ return _result(data, f"calc_metrics ok · bars={data['count']} · computed={','.join(data['metrics_computed'])}{warning}")
768
+
769
+
770
+ @mcp.tool(name="analyze_kline_rows")
771
+ async def analyze_kline_rows(
772
+ rows: Annotated[list[dict[str, Any]], Field(description="来自任意数据源的 OHLCV 行;time 可为 Unix 秒或毫秒")],
773
+ symbol: Annotated[str, Field(description="标的代码或名称")],
774
+ name: Annotated[str | None, Field(description="标的名称")] = None,
775
+ interval: Annotated[str, Field(description="K 线周期:minute / day / week / month / quarter / year")] = "day",
776
+ limit: Annotated[int, Field(ge=2, le=4000, description="最终分析使用的最近 K 线根数")] = 60,
777
+ adjust: Annotated[AdjustmentInput, Field(description=ADJUSTMENT_DESCRIPTION + ";只标记调用方已有数据,不重新复权")] = "none",
778
+ indicators: Annotated[list[str] | None, Field(description="ma / ema / vol / macd / kdj / boll / rsi / atr / vwap")] = None,
779
+ metrics: Annotated[list[str] | None, Field(description="指标摘要子集,可选:" + ", ".join(AVAILABLE_METRICS))] = None,
780
+ mark_support_resistance: Annotated[bool, Field(description="仅在用户明确要求支撑位/压力位时设为 true")] = False,
781
+ ma_periods: Annotated[list[int] | None, Field(description=f"MA 周期,默认 {DEFAULT_MA_PERIODS}")] = None,
782
+ rsi_period: Annotated[int, Field(ge=2, le=100)] = DEFAULT_RSI_PERIOD,
783
+ boll_period: Annotated[int, Field(ge=2, le=200)] = DEFAULT_BOLL_PERIOD,
784
+ boll_std: Annotated[float, Field(ge=0.5, le=5.0)] = DEFAULT_BOLL_STD,
785
+ volume_ma: Annotated[int, Field(ge=2, le=200)] = DEFAULT_VOLUME_MA,
786
+ atr_period: Annotated[int, Field(ge=2, le=100)] = DEFAULT_ATR_PERIOD,
787
+ data_source: Annotated[str | None, Field(description="数据源名称,不要放 API key 或其他秘密")] = None,
788
+ data_source_url: Annotated[str | None, Field(description="可选的 HTTPS 数据源说明链接")] = None,
789
+ security_workspace: Annotated[dict[str, Any] | None, Field(description="可选的标准化新闻/简况数据")] = None,
790
+ ) -> types.CallToolResult:
791
+ """Analyze caller-supplied OHLCV rows and open the native chart sidebar."""
792
+ canonical_adjust = normalize_adjustment(adjust)
793
+ if canonical_adjust is None:
794
+ data = adjustment_error()
795
+ return _result(data, data["message"], error=True)
796
+ adjust = canonical_adjust
797
+ normalized_interval, interval_error = _validate_interval(interval)
798
+ if interval_error:
799
+ return _result({"ok": False, **interval_error}, interval_error["message"], error=True)
800
+ if not isinstance(rows, list):
801
+ data = {"ok": False, "error": "invalid_external_rows", "message": "rows must be a list"}
802
+ return _result(data, data["message"], error=True)
803
+ if len(rows) > 12000:
804
+ data = {"ok": False, "error": "too_many_rows", "message": "rows exceeds the 12000-item input safety limit"}
805
+ return _result(data, data["message"], error=True)
806
+ try:
807
+ # In external-rows mode the symbol is only a display label. Do not
808
+ # resolve it through the local directory: BTC, TEST.X, backtest labels,
809
+ # and custom Chinese names must remain completely provider-independent.
810
+ resolved_symbol = str(symbol or "external").strip() or "external"
811
+ resolved_name = name or resolved_symbol
812
+ data = _analysis_from_rows(
813
+ rows,
814
+ symbol=resolved_symbol or symbol,
815
+ name=name or resolved_name,
816
+ interval=normalized_interval or "day",
817
+ limit=limit,
818
+ adjust=adjust,
819
+ indicators=indicators,
820
+ metrics=metrics,
821
+ mark_support_resistance=mark_support_resistance,
822
+ ma_periods=ma_periods,
823
+ rsi_period=rsi_period,
824
+ boll_period=boll_period,
825
+ boll_std=boll_std,
826
+ volume_ma=volume_ma,
827
+ atr_period=atr_period,
828
+ data_source=data_source,
829
+ data_source_url=data_source_url,
830
+ security_workspace=security_workspace,
831
+ )
832
+ except (RowsValidationError, TypeError, ValueError) as exc:
833
+ data = {"ok": False, "error": "invalid_external_rows", "message": str(exc)}
834
+ return _result(data, data["message"], error=True)
835
+ return _result(data, f"analyze_kline_rows ok · {data['symbol']} · {data['count']} bars · source={data['source']} · chart_session={data['chart_session']}")
836
+
837
+
838
+ @mcp.tool(name="analyze_kline")
839
+ async def analyze_kline(
840
+ symbol: Annotated[str, Field(description="标的代码,如 00700.HK / 600519.XSHG / NVDA.US")],
841
+ interval: Annotated[str, Field(description="K 线周期:minute / day / week / month / quarter / year")] = "day",
842
+ interval_value: Annotated[int, Field(ge=1, le=240, description="分钟粒度;非分钟周期通常为 1")] = 1,
843
+ session_count: Annotated[int | None, Field(ge=1, le=10, description="分钟 K 的最近交易日数量")] = None,
844
+ limit: Annotated[int, Field(ge=2, le=4000, description="最终分析使用的最近 K 线根数")] = 60,
845
+ adjust: Annotated[AdjustmentInput, Field(description=ADJUSTMENT_DESCRIPTION)] = "none",
846
+ indicators: Annotated[list[str] | None, Field(description="ma / ema / vol / macd / kdj / boll / rsi / atr / vwap")] = None,
847
+ metrics: Annotated[list[str] | None, Field(description="指标摘要子集,可选:" + ", ".join(AVAILABLE_METRICS))] = None,
848
+ mark_support_resistance: Annotated[bool, Field(description="仅在用户明确要求支撑位/压力位时设为 true;默认不标注")] = False,
849
+ ma_periods: Annotated[list[int] | None, Field(description=f"MA 周期,默认 {DEFAULT_MA_PERIODS}")] = None,
850
+ rsi_period: Annotated[int, Field(ge=2, le=100)] = DEFAULT_RSI_PERIOD,
851
+ boll_period: Annotated[int, Field(ge=2, le=200)] = DEFAULT_BOLL_PERIOD,
852
+ boll_std: Annotated[float, Field(ge=0.5, le=5.0)] = DEFAULT_BOLL_STD,
853
+ volume_ma: Annotated[int, Field(ge=2, le=200)] = DEFAULT_VOLUME_MA,
854
+ atr_period: Annotated[int, Field(ge=2, le=100)] = DEFAULT_ATR_PERIOD,
855
+ ) -> types.CallToolResult:
856
+ """Use this single call for ordinary K-line analysis; it also opens the native chart sidebar."""
857
+ canonical_adjust = normalize_adjustment(adjust)
858
+ if canonical_adjust is None:
859
+ data = adjustment_error()
860
+ return _result(data, data["message"], error=True)
861
+ adjust = canonical_adjust
862
+ normalized_interval, interval_error = _validate_interval(interval)
863
+ if interval_error:
864
+ return _result({"ok": False, **interval_error}, interval_error["message"], error=True)
865
+ resolved_symbol, resolved_name, symbol_error = _resolve_symbol_input(symbol)
866
+ if symbol_error:
867
+ return _result({"ok": False, **symbol_error}, symbol_error["message"], error=True)
868
+ requested = max(2, min(int(limit), 4000))
869
+ fetch_limit = requested if normalized_interval == "minute" else min(4000, max(requested, int(requested * 1.8)))
870
+ fetched = fetch_candles(
871
+ resolved_symbol or symbol,
872
+ interval=normalized_interval or "day",
873
+ interval_value=interval_value,
874
+ session_count=session_count,
875
+ limit=fetch_limit,
876
+ adjust=adjust,
877
+ )
878
+ if not fetched.get("ok"):
879
+ return _result(fetched, _error_text(fetched, "analysis failed"), error=True)
880
+ effective_adjust = normalize_adjustment(fetched.get("adjust"))
881
+ if effective_adjust is None:
882
+ data = adjustment_error(metadata=True)
883
+ return _result(data, data["message"], error=True)
884
+
885
+ rows = list(fetched.get("rows") or [])[-requested:]
886
+ if len(rows) < 2:
887
+ data = {"ok": False, "error": "insufficient_candles", "message": "fewer than two candles", "symbol": symbol}
888
+ return _result(data, data["message"], error=True)
889
+
890
+ active_indicators, unknown_indicators = _normalized_indicators(indicators)
891
+ periods = _normalized_ma_periods(ma_periods)
892
+ requested_metrics = [str(value).lower() for value in metrics] if metrics is not None else ["rsi"]
893
+ should_mark_levels = mark_support_resistance or "support_resistance" in requested_metrics
894
+ if mark_support_resistance and "support_resistance" not in requested_metrics:
895
+ requested_metrics.append("support_resistance")
896
+ metric_data = run_calc_metrics(
897
+ rows,
898
+ metrics=requested_metrics,
899
+ rsi_period=rsi_period,
900
+ boll_period=boll_period,
901
+ boll_std=boll_std,
902
+ atr_period=atr_period,
903
+ volume_ma=volume_ma,
904
+ ma_periods=periods,
905
+ )
906
+ analysis_marks = _support_resistance_marks(metric_data) if should_mark_levels else []
907
+ previous = float(rows[-2]["close"])
908
+ latest = dict(rows[-1])
909
+ latest["change"] = round(float(latest["close"]) - previous, 6)
910
+ latest["change_pct"] = round((float(latest["close"]) / previous - 1) * 100, 4) if previous else None
911
+ chart_payload = draw_kline(
912
+ rows,
913
+ indicators=active_indicators,
914
+ indicators_explicit=indicators is not None,
915
+ ma_periods=periods,
916
+ marks=analysis_marks,
917
+ symbol=str(fetched.get("symbol") or resolved_symbol or symbol),
918
+ name=str(fetched.get("name") or resolved_name or symbol),
919
+ data_source=str(fetched.get("source") or "ftshare"),
920
+ interval=normalized_interval or "day",
921
+ boll_period=boll_period,
922
+ boll_std=boll_std,
923
+ volume_ma=volume_ma,
924
+ rsi_period=rsi_period,
925
+ atr_period=atr_period,
926
+ )
927
+ chart_payload["adjust"] = effective_adjust
928
+ chart_payload["interval_value"] = interval_value
929
+ provider_metadata = {key: fetched[key] for key in ("source_url", "notice", "volume_unit", "volume_adjustment", "price_adjustment", "timestamp_convention", "history_complete", "history_start", "history_end", "coverage_reason", "source_symbol", "requested_count") if key in fetched}
930
+ chart_payload.update(provider_metadata)
931
+ chart = _chart_spec(rows, active_indicators, periods, normalized_interval or "day", analysis_marks)
932
+ chart_session: str | None = None
933
+ chart_service_status: dict[str, Any]
934
+ try:
935
+ chart_session, _service_url = publish_chart(chart_payload)
936
+ chart["session_id"] = chart_session
937
+ chart_service_status = {"ok": True}
938
+ except Exception as exc: # noqa: BLE001
939
+ chart_service_status = {
940
+ "ok": False,
941
+ "error": "chart_service_unavailable",
942
+ "message": str(exc),
943
+ }
944
+ data = {
945
+ "ok": True,
946
+ "workflow": "fetch_analyze_chart_session",
947
+ **provider_metadata,
948
+ "symbol": fetched.get("symbol") or resolved_symbol or symbol,
949
+ "name": fetched.get("name") or resolved_name or symbol,
950
+ "interval": normalized_interval or "day",
951
+ "adjust": effective_adjust,
952
+ **({"adjust_requested": adjust, "adjustment_warning": fetched.get("warning") or "Requested adjustment was not applied by the provider."} if effective_adjust != adjust else {}),
953
+ "source": fetched.get("source") or "ftshare",
954
+ "status": fetched.get("status"),
955
+ "count": len(rows),
956
+ "fetched_count": len(fetched.get("rows") or []),
957
+ "history_warnings": fetched.get("warnings", []),
958
+ "as_of": fetched.get("as_of"),
959
+ "freshness": fetched.get("freshness"),
960
+ "chart_session": chart_session,
961
+ "chart_ready": bool(chart_session and chart_service_status.get("ok")),
962
+ "chart_service": chart_service_status,
963
+ "latest": latest,
964
+ "indicator_last": _indicator_last(
965
+ rows,
966
+ active_indicators,
967
+ ma_periods=periods,
968
+ rsi_period=rsi_period,
969
+ boll_period=boll_period,
970
+ boll_std=boll_std,
971
+ volume_ma=volume_ma,
972
+ atr_period=atr_period,
973
+ ),
974
+ "metrics": metric_data,
975
+ "chart": chart,
976
+ "warnings": ([f"ignored unsupported indicators: {', '.join(unknown_indicators)}"] if unknown_indicators else []),
977
+ }
978
+ summary = {
979
+ key: data[key]
980
+ for key in (
981
+ "symbol",
982
+ "name",
983
+ "interval",
984
+ "adjust",
985
+ "source",
986
+ "status",
987
+ "count",
988
+ "as_of",
989
+ "latest",
990
+ "indicator_last",
991
+ "metrics",
992
+ "chart_ready",
993
+ "chart_session",
994
+ "warnings",
995
+ "history_warnings",
996
+ )
997
+ }
998
+ summary.update({key: data[key] for key in ("adjust_requested", "adjustment_warning") if key in data})
999
+ return _result(data, "analyze_kline ok · " + json.dumps(summary, ensure_ascii=False, separators=(",", ":")))
1000
+
1001
+
1002
+ def _horizontal_line_operation(
1003
+ action: str, chart_session: str, symbol: str, **changes: Any,
1004
+ ) -> types.CallToolResult:
1005
+ return _line_operation(action, chart_session, symbol, "horizontal", **changes)
1006
+
1007
+
1008
+ def _drawing_snapshot(chart_session: str, symbol: str) -> dict[str, Any]:
1009
+ payload = read_chart_snapshot(chart_session)
1010
+ if payload is None:
1011
+ raise LineError("chart_session_not_found", "图表快照不存在或不属于当前 DSH,请使用当前对话返回的 chart_session。")
1012
+ if str(payload.get("symbol") or "").casefold() != symbol.strip().casefold():
1013
+ raise LineError("symbol_mismatch", "标的与图表快照不一致,未修改任何图形。")
1014
+ return payload
1015
+
1016
+
1017
+ def _drawing_error(exc: LineError) -> types.CallToolResult:
1018
+ # Harness may show only TextContent for isError responses, not structuredContent.
1019
+ data = {"ok": False, "error": exc.code, "message": str(exc), "interaction": error_interaction(exc.code)}
1020
+ return _result(data, f"{exc} · error={exc.code} · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")), error=True)
1021
+
1022
+
1023
+ def _chart_edit_result(data: dict) -> types.CallToolResult:
1024
+ """Add presentation metadata only; do not change preparation/application proof."""
1025
+ result = {**data}
1026
+ token = data.get("candidate_chart_session") or data.get("chart_session")
1027
+ candidate = read_chart_snapshot(token) if isinstance(token, str) else None
1028
+ guard = candidate.get("drawing_guard") if candidate else None
1029
+ if isinstance(guard, dict) and all(guard.get(key) == data.get(key) for key in
1030
+ ("context_ref", "conversation_id", "view_id", "expected_revision")):
1031
+ parent = read_chart_snapshot(candidate.get("drawing_parent_session"))
1032
+ if parent:
1033
+ change = edit_change(candidate, parent)
1034
+ if change is not None:
1035
+ result["change"] = change
1036
+ result["interaction"] = edit_interaction(data, result.get("change"))
1037
+ return _result(result, result["interaction"]["message"] + " · "
1038
+ + json.dumps(result, ensure_ascii=False, separators=(",", ":")))
1039
+
1040
+
1041
+ def _line_operation(
1042
+ action: str, chart_session: str, symbol: str, family: str, **changes: Any,
1043
+ ) -> types.CallToolResult:
1044
+ read_lines, edit_line, title = {
1045
+ "horizontal": (horizontal_lines, edit_horizontal_line, "水平线"),
1046
+ "trend": (trend_lines, edit_trend_line, "趋势线"),
1047
+ "channel": (channels, edit_channel, "通道"),
1048
+ "rectangle": (rectangles, edit_rectangle, "平台框"),
1049
+ }[family]
1050
+ collection = {"channel": "channels", "rectangle": "rectangles"}.get(family, "lines")
1051
+ try:
1052
+ payload = _drawing_snapshot(chart_session, symbol)
1053
+ except LineError as exc:
1054
+ return _drawing_error(exc)
1055
+ data = {"ok": True, "symbol": payload.get("symbol"), "interval": payload.get("interval"),
1056
+ "count": payload.get("count"), "chart_session": chart_session,
1057
+ "render_verified": False, "scope": "explicit_chart_snapshot"}
1058
+ if action == "list":
1059
+ data[collection] = read_lines(payload)
1060
+ return _result(data, title + "快照状态 · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1061
+ if payload.get("view_source_guard"):
1062
+ return _drawing_error(LineError("current_view_source_requires_guarded_edit", "这是网页当前来源凭证,请读取新上下文并使用 prepare_chart_edit / apply_chart_edit;旧快照修改接口不适用。"))
1063
+ if payload.get("drawing_guard"):
1064
+ return _drawing_error(LineError("prepared_chart_not_applied", "该快照是尚未应用的准备结果,不能用旧绘图接口绕过当前图状态检查。"))
1065
+ try:
1066
+ edited, line = edit_line(payload, action, **changes)
1067
+ except LineError as exc:
1068
+ return _drawing_error(exc)
1069
+ edited["drawing_only"] = True
1070
+ edited["drawing_parent_session"] = chart_session
1071
+ try:
1072
+ token, _url = publish_chart(edited)
1073
+ except Exception: # noqa: BLE001
1074
+ return _result({"ok": False, "error": "chart_service_unavailable"},
1075
+ "绘图快照发布失败,原图未改变。 · error=chart_service_unavailable", error=True)
1076
+ data.update(chart_session=token, parent_chart_session=chart_session, chart_ready=True,
1077
+ operation=action, operation_status="published", render_status="not_verified",
1078
+ verification_required=True)
1079
+ data[{"channel": "channel", "rectangle": "rectangle"}.get(family, "line")] = line
1080
+ data[collection] = read_lines(edited)
1081
+ rows = next((c.get("rows", []) for c in payload["chartCommands"] if c.get("type") == "SET_CANDLES"), [])
1082
+ if family == "channel":
1083
+ prices = [line[edge][point]["price"] for edge in ("upper", "lower") for point in ("from", "to")]
1084
+ elif family == "rectangle":
1085
+ prices = [line["lower_price"], line["upper_price"]]
1086
+ else:
1087
+ prices = [line["from"]["price"], line["to"]["price"]] if family == "trend" else [line["price"]]
1088
+ if rows and action != "delete":
1089
+ low, high = min(r["low"] for r in rows), max(r["high"] for r in rows)
1090
+ outside = [p for p in prices if not low <= p <= high]
1091
+ if outside:
1092
+ data["out_of_range_prices"] = outside
1093
+ data["candle_price_range"] = {"low": low, "high": high}
1094
+ price_label = "通道边界价格" if family == "channel" else "指定价格"
1095
+ data["warnings"] = [f"{price_label} {outside} 超出当前 K 线高低范围 [{low}, {high}],不是与最新收盘价比较;图形可能不在当前可见价格区间。"]
1096
+ return _result(data, title + "操作已发布,尚未核验屏幕呈现 · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1097
+
1098
+
1099
+ @mcp.tool(name="get_chart_context", annotations=types.ToolAnnotations(readOnlyHint=True))
1100
+ async def get_chart_context(
1101
+ context_ref: Annotated[str, Field(description="当前对话运行时上下文提供的32字符引用;不是chart_session,不得猜测其他对话")],
1102
+ candle_scope: Literal["visible", "loaded", "none"] = "visible",
1103
+ limit: Annotated[int, Field(ge=1, le=4000, strict=True)] = 200,
1104
+ region_start_time: Annotated[str | None, Field(strict=True, description="可选:宿主选定测量区域的已有K线起点;与region_end_time同时填写") ] = None,
1105
+ region_end_time: Annotated[str | None, Field(strict=True, description="可选:测量终点;精确时间规则同画线,不吸附、不扩充行情") ] = None,
1106
+ ) -> types.CallToolResult:
1107
+ """Read the current conversation's live browser observation without fetching or changing charts.
1108
+
1109
+ Read fresh context before analysis and again before edits if the view may have changed.
1110
+ When the user asks to find a drawing region, the HOST may choose a candidate from actual
1111
+ candles; the plugin does not choose/classify it. Before asking approval for that chosen
1112
+ region, call this with paired region_start_time/region_end_time to check numeric claims.
1113
+ A proposal-first request must not prepare/apply drawings before confirmation. A direct
1114
+ drawing request may select and apply the newest suitable candidate without another prompt. Keep ordinary
1115
+ proposals concise; avoid arbitrary universal pattern thresholds and internal IDs.
1116
+ An inactive initial reference during mounting requires a newly injected current-view
1117
+ reference, NOT another market fetch or analyze call.
1118
+ Visible candles are actual viewport-index rows, not all loaded candles; unknown viewport
1119
+ stays unknown. Limit samples the last rows with explicit truncation. Stored object inventory
1120
+ is not proof of rendering; live_view_editable=false. No old-snapshot or global-latest fallback.
1121
+ data_provenance reports provider metadata and browser-input vs displayed intervals, not
1122
+ vendor-native granularity. local_aggregation (e.g. day -> week) explains a normal interval
1123
+ difference, not stale data by itself; aggregation completeness is NOT verified. Unknown
1124
+ providers/transforms must not be guessed. This metadata is not source-snapshot alignment
1125
+ or edit authorization; guarded edits still require exact current candles and AI inventory.
1126
+ After local period/range/symbol changes the browser can seal and confirm its current
1127
+ source without fetching or drawing. A pending/unconfirmed source is not editable: wait
1128
+ for fresh context, never refetch or fall back to old snapshot tools. Source binding does
1129
+ not approve a drawing proposal or move existing objects into a different period.
1130
+ Use time_display's deterministic +08:00 ISO/date labels when reporting dates; do not
1131
+ mentally convert Unix seconds or guess dates. Minute anchors require exact ISO times.
1132
+ Optional paired region times measure the full loaded region (max 4000 bars), independently
1133
+ of returned candle sampling. source_status is allowlisted diagnostic metadata only:
1134
+ checking means wait for a fresh report, blocked means follow next_action; an uncertain
1135
+ drawing outcome must be checked via get_chart_edit_status, never resent automatically.
1136
+ Source aligned is not drawing approval, pixel proof, vendor freshness or a guard bypass.
1137
+ Recheck only republishes/checks the current browser chart; it does not fetch quotes or queue drawings.
1138
+ Body envelope != common body intersection; volume net change
1139
+ != monotonic change. Measurements do not select/classify a platform or authorize drawing.
1140
+ boundary_evidence gives an actual bar's +08:00 date/ISO, source_fields (open/close/low/high),
1141
+ price and matched_bar_count for each extreme; ties use the first matching bar, not a unique
1142
+ or preferred drawing anchor. Cite these, not guessed dates. body_overlap's candidate lower
1143
+ is max(body lows), candidate upper is min(body highs): lower>upper is EMPTY (no shared
1144
+ price shared by EVERY body), equality is a POINT, lower<upper is a RANGE. Never turn exists=false/relation=empty
1145
+ into a shared point. These diagnostic candidates are not drawable bounds when empty.
1146
+ Empty common intersection does NOT imply a gap uncovered by ANY body. The candidate
1147
+ difference is not an uncovered gap; union coverage is not measured. Report the measured
1148
+ result with its witnesses, not extra coverage claims. A claim about a specific bar must
1149
+ be checked against that bar's actual open/close values, not inferred from the intersection.
1150
+ """
1151
+ try:
1152
+ data = read_chart_context(context_ref, candle_scope=candle_scope, limit=limit,
1153
+ region_start_time=region_start_time, region_end_time=region_end_time)
1154
+ except LineError as exc:
1155
+ return _drawing_error(exc)
1156
+ return _result(data, "当前图表上下文(网页观察,只读) · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1157
+
1158
+
1159
+ @mcp.tool(name="preview_chart_channel", annotations=types.ToolAnnotations(readOnlyHint=True, idempotentHint=True))
1160
+ async def preview_chart_channel(
1161
+ context_ref: Annotated[str, Field(description="本对话运行时的当前视图引用;不是chart_session")],
1162
+ start_time: Annotated[str, Field(strict=True, description="基准线起点,必须精确对应当前图已有K线")],
1163
+ start_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True)],
1164
+ end_time: Annotated[str, Field(strict=True, description="基准线终点,必须晚于起点,不交换、不吸附")],
1165
+ end_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True)],
1166
+ parallel_time: Annotated[str, Field(strict=True, description="另一边界的第三点,须在起止区间内")],
1167
+ parallel_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True)],
1168
+ bar_limit: Annotated[int, Field(ge=1, le=4000, strict=True, description="逐根结果只返回前N根;汇总核对完整区间,最多4000根") ] = 200,
1169
+ ) -> types.CallToolResult:
1170
+ """Preview a HOST-chosen three-anchor channel against fresh current browser candles, read-only.
1171
+
1172
+ The host selects explicit anchors from fresh actual candles under user-authorized analysis;
1173
+ this tool never searches/fits/selects anchors or judges professional pattern quality. Use it
1174
+ before proposing a channel, without shell arithmetic or refetching candles. Date-only anchors
1175
+ use UTC+08:00 on daily/larger bars; minute bars need exact timezone ISO or Unix seconds.
1176
+ Geometry is identical to channel execution: candle_index_linear_price, finite inclusive
1177
+ start/end, no calendar-time slope or extrapolated bars. Returns upper/lower boundaries,
1178
+ raw signed wick/body distances, full-region exceedance counts and worst-bar witnesses.
1179
+ Positive high_minus_upper is above the upper boundary; negative low_minus_lower is below
1180
+ the lower. Body variants use max/min(open, close). Counts ignore only the disclosed floating
1181
+ roundoff allowance, NOT a market tolerance; no touch count, fit score or recognition is given.
1182
+ An empty horizontal body intersection does not disqualify a sloped channel. Containment does
1183
+ not prove a meaningful pattern, predictive power or uniqueness. Do not add unsupported claims.
1184
+ bar_limit truncates only the returned per-bar list, never the full-region summary (max4000).
1185
+ exact_matching_ohlc_fields are exact matches only; caller-supplied prices need not be extrema.
1186
+ No chart fetch, snapshot publication, prepare/apply, drawing or edit authorization occurs.
1187
+ A preview is arithmetic, NOT a visual preview or rendering receipt. Re-read fresh context
1188
+ after user confirmation and preserve the independently approved anchors for guarded execution.
1189
+ """
1190
+ try:
1191
+ observed = read_chart_context(context_ref, candle_scope="none", channel_candidate=dict(
1192
+ start_time=start_time, start_price=start_price, end_time=end_time, end_price=end_price,
1193
+ parallel_time=parallel_time, parallel_price=parallel_price, bar_limit=bar_limit))
1194
+ except LineError as exc:
1195
+ return _drawing_error(exc)
1196
+ data = {k: observed[k] for k in ("ok", "context_ref", "conversation_id", "view_id", "revision",
1197
+ "observed_at_ms", "observation_source", "source_chart_session", "symbol", "interval",
1198
+ "interval_value", "ui_interval", "source_interval", "data_provenance", "adjust", "channel_preview")}
1199
+ return _result(data, "通道几何与偏差核对(只读,不绘图) · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1200
+
1201
+
1202
+ @mcp.tool(name="list_chart_functions", annotations=types.ToolAnnotations(readOnlyHint=True))
1203
+ async def list_chart_functions() -> types.CallToolResult:
1204
+ """Discover implemented deterministic chart functions, parameters, versions and limits.
1205
+
1206
+ No market fetch, chart mutation or arbitrary code execution. Candidate functions propose
1207
+ rule-based geometry for review; they do not draw or claim professional pattern confirmation.
1208
+ Functions: fibonacci_retracement, parallel_channel, range_box, labeled_polyline,
1209
+ pivot_candidates, recent_drawing_candidates, regression_channel, channel_candidates, range_candidates, price_pattern_candidates, nine_count, price_series_line,
1210
+ conditional_annotation, price_band, price_sticks.
1211
+ pivot_candidates reports confirmed strict local extrema; regression_channel computes OLS statistics;
1212
+ channel_candidates v3 proposes bounded three-anchor geometry from confirmed pivots. Default scope=current
1213
+ requires a recent end anchor and checks the arithmetic extension through the latest bar; scope=historical
1214
+ is for past geometry only, with no current breakout inference. Zero candidates does not prove
1215
+ a lack of recent confirmed pivots; inspect pivot_scan and rejection_counts. range_candidates proposes
1216
+ horizontal boxes ending at the latest loaded bar, distinct from explicitly drawn range_box.
1217
+ Analysis functions are read-only and may validly return no candidate. price_pattern_candidates
1218
+ uses closed A/HK/US daily bars for double tops/bottoms, head-and-shoulders and frozen ranges;
1219
+ nine_count records each close-vs-four-back count without retrospective deletion.
1220
+ labeled_polyline connects 2..8 explicitly labeled anchors, not automatic Elliott wave recognition.
1221
+ price_series_line uses current loaded OHLC or SMA(close, 2..200) and an optional price comparison.
1222
+ It returns a bounded result_ref; null warmup/false-condition bars break the price-pane line.
1223
+ conditional_annotation selects only the latest loaded bar matching a required price condition;
1224
+ its result uses the existing guarded text, number or icon annotation kind, not a batch of marks.
1225
+ price_band fills between two OHLC/SMA price sources in the candle pane. Its upper boundary
1226
+ must stay strictly above the lower boundary on every eligible bar; warmup/false conditions break the band.
1227
+ price_sticks draws independent vertical strokes between two OHLC/SMA price sources on matching bars;
1228
+ zero-length endpoints are omitted. This is not a full formula interpreter.
1229
+ """
1230
+ data = list_functions()
1231
+ return _result(data, "当前可用绘图计算函数 · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1232
+
1233
+
1234
+ @mcp.tool(name="list_ta_functions", annotations=types.ToolAnnotations(readOnlyHint=True))
1235
+ async def list_ta_functions(
1236
+ group: str | None = None, query: str | None = None,
1237
+ offset: Annotated[int, Field(ge=0, strict=True)] = 0,
1238
+ limit: Annotated[int, Field(ge=1, le=50, strict=True)] = 25,
1239
+ ) -> types.CallToolResult:
1240
+ """Page/search all 201 pinned TA-Lib functions and their input/parameter/output metadata.
1241
+
1242
+ Analysis only. No data fetch or chart mutation; use run_ta_function on the current chart.
1243
+ """
1244
+ try:
1245
+ data = list_ta_catalog(group=group, query=query, offset=offset, limit=limit)
1246
+ except LineError as exc:
1247
+ return _drawing_error(exc)
1248
+ return _result(data, "TA-Lib 函数目录 · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1249
+
1250
+
1251
+ @mcp.tool(name="run_ta_function", annotations=types.ToolAnnotations(readOnlyHint=True))
1252
+ async def run_ta_function(
1253
+ context_ref: str, expected_revision: Annotated[int, Field(gt=0, strict=True)],
1254
+ chart_session: str, symbol: str, function: str,
1255
+ parameters: dict[str, int | float] | None = None,
1256
+ price_sources: dict[str, Literal["open", "high", "low", "close"]] | None = None,
1257
+ periods_constant: Annotated[int, Field(ge=2, le=4000, strict=True)] = 14,
1258
+ ) -> types.CallToolResult:
1259
+ """Run one TA-Lib function on current loaded OHLCV; returns analysis result_ref, never draws.
1260
+
1261
+ Discover parameter names with list_ta_functions. No host-supplied arrays or formula code.
1262
+ price_sources keys are the generic input names from list_ta_functions, not TA-Lib's
1263
+ low-level inReal name. For example SMA uses {"price":"close"}; omit it for default close.
1264
+ Values may only be current open/high/low/close columns.
1265
+ MAVP uses a constant per-bar periods array; periods_constant is ignored for other functions only at 14.
1266
+ Finite SMA/EMA(close, 2..200) may advertise series_line; finite BBANDS(close, SMA middle)
1267
+ may advertise price_band with upper/middle/lower as one object. If the user explicitly asks
1268
+ to draw one, pass result_ref as edit.ta_result_ref with the advertised kind to
1269
+ prepare_chart_edit, then apply_chart_edit and check status. Other TA results stay analysis-only.
1270
+ """
1271
+ try:
1272
+ data = run_ta(context_ref, expected_revision, chart_session, symbol, function,
1273
+ parameters=parameters, price_sources=price_sources, periods_constant=periods_constant)
1274
+ except LineError as exc:
1275
+ return _drawing_error(exc)
1276
+ return _result(data, "TA-Lib 只读计算 · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1277
+
1278
+
1279
+ @mcp.tool(name="read_ta_result", annotations=types.ToolAnnotations(readOnlyHint=True))
1280
+ async def read_ta_result(
1281
+ context_ref: str, expected_revision: Annotated[int, Field(gt=0, strict=True)],
1282
+ chart_session: str, symbol: str, result_ref: str, output_name: str,
1283
+ offset: Annotated[int, Field(ge=0, strict=True)] = 0,
1284
+ limit: Annotated[int, Field(ge=1, le=250, strict=True)] = 200,
1285
+ ) -> types.CallToolResult:
1286
+ """Read one TA-Lib output page from a result bound to the unchanged current chart."""
1287
+ try:
1288
+ data = read_ta(context_ref, expected_revision, chart_session, symbol,
1289
+ result_ref, output_name, offset=offset, limit=limit)
1290
+ except LineError as exc:
1291
+ return _drawing_error(exc)
1292
+ return _result(data, "TA-Lib 结果分页 · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1293
+
1294
+
1295
+ @mcp.tool(name="run_chart_function", annotations=types.ToolAnnotations(readOnlyHint=True))
1296
+ async def run_chart_function(
1297
+ context_ref: str, expected_revision: Annotated[int, Field(gt=0, strict=True)], chart_session: str,
1298
+ symbol: str, function: FunctionName, parameters: ChartFunctionParameters,
1299
+ ) -> types.CallToolResult:
1300
+ """Calculate on explicitly aligned current loaded candles; return immutable result_ref, NOT a drawing.
1301
+
1302
+ Read get_chart_context first. Preserve user-specified anchors/bounds. For a direct automatic
1303
+ drawing request select the newest suitable result after checking type and data quality; ask
1304
+ when a literal coordinate request is incomplete. pivot_candidates,
1305
+ recent_drawing_candidates, regression_channel, channel_candidates, range_candidates, price_pattern_candidates and nine_count return analysis-only results;
1306
+ never pass these refs as edit.result_ref. A direct request to draw authorizes the host to
1307
+ choose a suitable candidate; an analysis-only or proposal-first request does not. For channel,
1308
+ range and price-pattern candidates pass edit.candidate_result_ref, candidate_number (1-based)
1309
+ and user_confirmed_candidate=true after selection. Default channel scope=current may return no candidate;
1310
+ historical scope must not be described as a current channel or current breakout signal.
1311
+ If no candidate passes, report only that no anchor triple met every rule; do not infer
1312
+ that recent pivots or real-world channel structure are absent. Inspect pivot_scan for pivots.
1313
+ No market fetch, LLM coordinate arithmetic,
1314
+ confirmed pattern identification, arbitrary formula/code or chart selection.
1315
+ Fibonacci levels are B-r*(B-A), ratios 0..1, linear price, exact loaded-bar times.
1316
+ For drawing functions, pass result_ref into prepare_chart_edit's edit (no duplicate anchors/bounds/ratios), then
1317
+ apply_chart_edit and get_chart_edit_status. For analysis-only functions, inspect the result first;
1318
+ channel/range/price-pattern candidates have the selected-candidate route. A nine_count
1319
+ result_ref can create or replace one nine_count snapshot group. Recompute after data/period/adjustment changes.
1320
+ price_series_line takes value_source={kind:open/high/low/close} or {kind:sma,period:2..200},
1321
+ optional condition={left:PriceSource,op:gt/gte/lt/lte,right:{source:PriceSource}|{constant:positive_price}}.
1322
+ No host-provided price arrays or executable formulas. Zero matched bars are not drawable.
1323
+ conditional_annotation requires annotation_kind, anchor_source and condition, plus exactly one
1324
+ matching annotation_text / annotation_value / annotation_icon. It chooses the latest matching
1325
+ loaded bar and returns one guarded annotation result_ref; no match means no drawing.
1326
+ price_band requires upper_source and lower_source, with optional condition. Crossing or equal
1327
+ boundaries are rejected; no matched bars are not drawable. Full arrays remain plugin-side.
1328
+ price_sticks requires start_source and end_source, with optional condition. Each matched bar has
1329
+ one independent stroke; equal endpoints, warmup and false conditions do not draw a stroke.
1330
+ Style edits reuse the existing object ID; calculation alone never means drawn/applied.
1331
+ labeled_polyline creates a group from parameters.points (unique labels, increasing times).
1332
+ To move one labeled point, skip recalculation and use prepare_chart_edit with the current
1333
+ object_id, point_label and point_time/point_price. Do NOT copy/rewrite all points or invent anchors.
1334
+ """
1335
+ try:
1336
+ data = run_function(context_ref, expected_revision, chart_session, symbol, function, parameters)
1337
+ except LineError as exc:
1338
+ return _drawing_error(exc)
1339
+ except OSError:
1340
+ return _drawing_error(LineError("chart_function_storage_unavailable", "无法保存函数结果,未修改图表。"))
1341
+ label = ("拐点候选分析完成,未绘图" if function == "pivot_candidates" else
1342
+ "回归通道统计完成,未绘图" if function == "regression_channel" else
1343
+ "通道候选分析完成,未绘图" if function == "channel_candidates" else
1344
+ "平台区间候选分析完成,未绘图" if function == "range_candidates" else
1345
+ "近期绘图锚点候选分析完成,未绘图" if function == "recent_drawing_candidates" else
1346
+ "价格形态候选分析完成,未绘图" if function == "price_pattern_candidates" else
1347
+ "九转计数完成,未绘图" if function == "nine_count" else
1348
+ "绘图函数计算完成,尚未绘图")
1349
+ return _result(data, label + " · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1350
+
1351
+
1352
+ @mcp.tool(name="prepare_chart_edit")
1353
+ async def prepare_chart_edit(
1354
+ context_ref: Annotated[str, Field(description="本对话 get_chart_context 返回的当前视图引用")],
1355
+ expected_revision: Annotated[int, Field(gt=0, strict=True, description="刚读回的观察 revision,不猜测或递增")],
1356
+ chart_session: Annotated[str, Field(description="当前观察的 source_chart_session;必须经行情与 AI 图形核对对齐")],
1357
+ symbol: str,
1358
+ request_id: Annotated[str, Field(min_length=1, max_length=128, description="同一次准备及重试使用同一 ID;不同参数不可复用")],
1359
+ edit: ChartEdit,
1360
+ ) -> types.CallToolResult:
1361
+ """DEFAULT entry for ALL browser-chart drawing creates/updates/deletes, including Fibonacci and labeled paths.
1362
+
1363
+ Read get_chart_context first, then prepare here, apply_chart_edit, get_chart_edit_status.
1364
+ Includes literal requests; legacy create/update/delete_* tools edit snapshots, NOT the current view.
1365
+ Prepare, NOT APPLY, one current-view drawing candidate with revision/alignment guards.
1366
+
1367
+ For proposal-first requests, call only AFTER the user approves the host's stated candidate.
1368
+ For direct drawing requests, select the newest suitable result and continue without another prompt;
1369
+ read fresh current context first, and preserve independently saved approved coordinates
1370
+ and user overrides. If relevant state changed, reassess before preparing. The host reasons,
1371
+ the executor does not choose points or validate pattern quality.
1372
+ Accept edit.result_ref from run_chart_function instead of direct anchors/bounds/ratios;
1373
+ name/color and applicable display switches may accompany a result reference.
1374
+ For selected channel/range/price-pattern candidates use edit.candidate_result_ref, candidate_number
1375
+ (1-based) and user_confirmed_candidate=true with action=create or update; do not copy candidate coordinates.
1376
+ An unconfirmed or stale candidate remains analysis only and cannot create a drawing.
1377
+ For series_line, create or change source/condition using the price_series_line result_ref;
1378
+ style-only updates and delete use the stable object_id. Calculation and indicator registration
1379
+ do not prove canvas pixels visible.
1380
+ A finite SMA/EMA(close, 2..200) result may use edit.ta_result_ref for series_line; a finite
1381
+ BBANDS(close, SMA middle) result may use it for one price_band containing upper/middle/lower.
1382
+ Both require an explicit drawing request and selectable_render_targets for the chosen kind.
1383
+ Do not pass other TA outputs, manually copy series values or conflate these AI objects with
1384
+ the built-in indicator toggles.
1385
+ For conditional_annotation, create or recompute an existing text/number/icon annotation using
1386
+ its result_ref with matching edit.kind; style-only edits and deletion use object_id.
1387
+ For price_band, use its result_ref with edit.kind=price_band to create/recompute one bounded
1388
+ price-pane object; style-only updates and deletion use its stable object_id.
1389
+ For price_sticks, use its result_ref with edit.kind=price_sticks; its independent strokes share
1390
+ one stable object_id. Style-only updates and deletion do not recompute the price series.
1391
+ For Fibonacci geometry use the function result; style-only edits/delete need no recalculation.
1392
+ For labeled_polyline creation use run_chart_function and edit.result_ref. To move one point,
1393
+ pass current object_id + point_label + point_time/point_price. A new current-chart
1394
+ labeled_polyline result_ref may replace the whole group under the same object_id;
1395
+ direct copied point arrays remain disallowed for updates.
1396
+ Point labels are group-local; ambiguous group names require clarification. ABC/1..5 labels
1397
+ are user/host-specified annotations, not algorithmically recognized or validated waves.
1398
+ For explicit point labels, text_annotation uses anchor_time + anchor_price + annotation_text;
1399
+ number_annotation uses anchor_time + anchor_price + annotation_value. Both update/delete by object_id
1400
+ and display literal user-provided content; the plugin does not calculate the value or select anchors.
1401
+ icon_annotation uses anchor_time + anchor_price + annotation_icon (arrow_up, arrow_down or diamond),
1402
+ and follows the same guarded create/update/delete flow.
1403
+ Reuses deterministic AI drawing families. Reject stale/ambiguous/inactive contexts,
1404
+ unaligned snapshots, manual objects and parallel edits from a consumed revision.
1405
+ A replay returns the same candidate, never publishes another. Unknown publication outcomes
1406
+ stop retries. No fetching or automatic chart selection. Use apply_chart_edit explicitly next.
1407
+ """
1408
+ try:
1409
+ data = prepare_guarded_chart_edit(context_ref, expected_revision, chart_session, symbol, request_id, edit)
1410
+ except LineError as exc:
1411
+ return _drawing_error(exc)
1412
+ except OSError:
1413
+ return _drawing_error(LineError("chart_edit_storage_unavailable", "修改记录存储不可用,未确认准备结果;当前网页未修改。"))
1414
+ return _chart_edit_result(data)
1415
+
1416
+
1417
+ @mcp.tool(name="apply_chart_edit")
1418
+ async def apply_chart_edit(context_ref: str, candidate_chart_session: str) -> types.CallToolResult:
1419
+ """Queue exactly this prepared candidate for its owning live view, never select a global chart.
1420
+
1421
+ Idempotent for this immutable candidate. Queued/delivered do not prove application.
1422
+ Read get_chart_edit_status; applied confirms view state only, not screen pixels.
1423
+ Unknown outcomes stop automatic retries. No candle fetch or ordinary renderer bypass.
1424
+ """
1425
+ try: data = request_chart_apply(context_ref, candidate_chart_session)
1426
+ except LineError as exc: return _drawing_error(exc)
1427
+ except (OSError, ValueError, TypeError, KeyError):
1428
+ return _drawing_error(LineError("chart_application_unavailable", "应用请求未确认,请读取原候选状态,不自动创建或重发新候选。"))
1429
+ return _chart_edit_result(data)
1430
+
1431
+
1432
+ @mcp.tool(name="get_chart_edit_status", annotations=types.ToolAnnotations(readOnlyHint=True))
1433
+ async def get_chart_edit_status(
1434
+ context_ref: str, candidate_chart_session: str,
1435
+ wait_ms: Annotated[int, Field(ge=0, le=5000, strict=True)] = 0,
1436
+ ) -> types.CallToolResult:
1437
+ """Read the exact candidate's historical preparation/application state, not screen visibility.
1438
+
1439
+ A verified prepared candidate without an application request returns prepared/not_requested.
1440
+ This does not prove the current view is editable or permit applying an old candidate after refresh.
1441
+ Optional bounded wait avoids tight polling; never fetches, republishes or invents a receipt.
1442
+ Read fresh get_chart_context separately before another mutation.
1443
+ """
1444
+ try:
1445
+ data = read_edit_status(context_ref, candidate_chart_session)
1446
+ deadline = asyncio.get_running_loop().time() + wait_ms / 1000
1447
+ while data["apply_status"] in {"queued", "delivered"} and asyncio.get_running_loop().time() < deadline:
1448
+ await asyncio.sleep(min(0.2, max(0, deadline - asyncio.get_running_loop().time())))
1449
+ data = read_edit_status(context_ref, candidate_chart_session)
1450
+ except LineError as exc: return _drawing_error(exc)
1451
+ return _chart_edit_result(data)
1452
+
1453
+
1454
+ @mcp.tool(name="get_horizontal_lines", annotations=types.ToolAnnotations(readOnlyHint=True))
1455
+ async def get_horizontal_lines(
1456
+ chart_session: Annotated[str, Field(description="当前对话最近一次工具返回的 chart_session")],
1457
+ symbol: Annotated[str, Field(description="该快照的完整标的代码")],
1458
+ ) -> types.CallToolResult:
1459
+ """Read exact AI horizontal lines in the named snapshot; no market fetch or UI claim."""
1460
+ return _horizontal_line_operation("list", chart_session, symbol)
1461
+
1462
+
1463
+ @mcp.tool(name="create_horizontal_line")
1464
+ async def create_horizontal_line(
1465
+ chart_session: Annotated[str, Field(description="当前对话最近一次工具返回的 chart_session")],
1466
+ symbol: Annotated[str, Field(description="该快照的完整标的代码")],
1467
+ price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True, description="用户指定的精确价格")],
1468
+ name: Annotated[str, Field(max_length=48, description="用户指定的完整名称,原样保留,不得缩写")] = "",
1469
+ color: Annotated[ColorInput, Field(description="按用户颜色填写;蓝色/info、绿色/success、橙色/warning、红色/danger;success不是成功状态")] = "info",
1470
+ request_id: Annotated[str | None, Field(min_length=1, max_length=128, description="可选重试标识;相同操作重试使用同一值")] = None,
1471
+ ) -> types.CallToolResult:
1472
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1473
+
1474
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1475
+ Only explicit snapshot-editing requests use this tool. Creates a full-width horizontal line snapshot.
1476
+ """
1477
+ return _horizontal_line_operation("create", chart_session, symbol, price=price, name=name, color=color, request_id=request_id)
1478
+
1479
+
1480
+ @mcp.tool(name="update_horizontal_line")
1481
+ async def update_horizontal_line(
1482
+ chart_session: Annotated[str, Field(description="当前对话最新的 chart_session,不要使用旧快照")],
1483
+ symbol: str,
1484
+ line_id: Annotated[str, Field(description="create_horizontal_line 或 get_horizontal_lines 返回的 line.id")],
1485
+ price: Annotated[float | None, Field(gt=0, allow_inf_nan=False, strict=True)] = None,
1486
+ name: Annotated[str | None, Field(max_length=48, description="修改为用户完整指定名称,不缩写")] = None,
1487
+ color: Annotated[ColorInput | None, Field(description="仅在用户要求改色时填写,可直接传绿色/红色等;success=绿色")] = None,
1488
+ ) -> types.CallToolResult:
1489
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1490
+
1491
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1492
+ Only explicit snapshot-editing requests use this tool. Move/rename/recolor one snapshot AI line by ID.
1493
+ """
1494
+ return _horizontal_line_operation("update", chart_session, symbol, line_id=line_id, price=price, name=name, color=color)
1495
+
1496
+
1497
+ @mcp.tool(name="delete_horizontal_line")
1498
+ async def delete_horizontal_line(chart_session: str, symbol: str, line_id: str) -> types.CallToolResult:
1499
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1500
+
1501
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1502
+ Only explicit snapshot-editing requests use this tool. Delete one AI line from the snapshot, not the live UI.
1503
+ """
1504
+ return _horizontal_line_operation("delete", chart_session, symbol, line_id=line_id)
1505
+
1506
+
1507
+ @mcp.tool(name="create_trend_line")
1508
+ async def create_trend_line(
1509
+ chart_session: str, symbol: str,
1510
+ start_time: Annotated[str, Field(description="起点:已有K线日期 YYYY-MM-DD(上海时区),或精确带时区ISO收盘时间/Unix秒字符串")],
1511
+ start_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True)],
1512
+ end_time: Annotated[str, Field(description="终点:必须是当前图中已有K线,且晚于起点;不自动就近匹配")],
1513
+ end_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True)],
1514
+ name: Annotated[str, Field(max_length=48, description="用户指定的完整趋势线名称,不缩写、不省略前缀")] = "",
1515
+ color: Annotated[ColorInput, Field(description="用户指定颜色;蓝色/info、绿色/success、橙色/warning、红色/danger")] = "info",
1516
+ request_id: Annotated[str | None, Field(min_length=1, max_length=128)] = None,
1517
+ ) -> types.CallToolResult:
1518
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1519
+
1520
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1521
+ Only explicit snapshot-editing requests use this tool.
1522
+ Draw an exact finite two-point segment. No rays, auto anchors, channels or market fetches.
1523
+
1524
+ Use the latest chart_session in this conversation and perform mutations sequentially.
1525
+ """
1526
+ return _line_operation("create", chart_session, symbol, "trend", start_time=start_time,
1527
+ start_price=start_price, end_time=end_time, end_price=end_price,
1528
+ name=name, color=color, request_id=request_id)
1529
+
1530
+
1531
+ @mcp.tool(name="get_trend_lines", annotations=types.ToolAnnotations(readOnlyHint=True))
1532
+ async def get_trend_lines(chart_session: str, symbol: str) -> types.CallToolResult:
1533
+ """Read exact AI trend segments and stable IDs in this conversation's latest snapshot."""
1534
+ return _line_operation("list", chart_session, symbol, "trend")
1535
+
1536
+
1537
+ @mcp.tool(name="update_trend_line")
1538
+ async def update_trend_line(
1539
+ chart_session: str, symbol: str, line_id: str,
1540
+ start_time: str | None = None,
1541
+ start_price: Annotated[float | None, Field(gt=0, allow_inf_nan=False, strict=True)] = None,
1542
+ end_time: str | None = None,
1543
+ end_price: Annotated[float | None, Field(gt=0, allow_inf_nan=False, strict=True)] = None,
1544
+ name: Annotated[str | None, Field(max_length=48, description="用户指定的完整名称,不缩写")] = None,
1545
+ color: Annotated[ColorInput | None, Field(description="仅修改所请求颜色;绿色/green/success同义,红色/red/danger同义")] = None,
1546
+ ) -> types.CallToolResult:
1547
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1548
+
1549
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1550
+ Only explicit snapshot-editing requests use this tool.
1551
+ Modify only supplied anchors/name/color by AI trend line ID. Preserve all other shapes.
1552
+
1553
+ Same exact time rules as create_trend_line. Use latest chart_session, never the old parent.
1554
+ """
1555
+ return _line_operation("update", chart_session, symbol, "trend", line_id=line_id,
1556
+ start_time=start_time, start_price=start_price, end_time=end_time,
1557
+ end_price=end_price, name=name, color=color)
1558
+
1559
+
1560
+ @mcp.tool(name="delete_trend_line")
1561
+ async def delete_trend_line(chart_session: str, symbol: str, line_id: str) -> types.CallToolResult:
1562
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1563
+
1564
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1565
+ Only explicit snapshot-editing requests use this tool. Delete one AI trend segment from the snapshot.
1566
+ """
1567
+ return _line_operation("delete", chart_session, symbol, "trend", line_id=line_id)
1568
+
1569
+
1570
+ @mcp.tool(name="create_channel")
1571
+ async def create_channel(
1572
+ chart_session: Annotated[str, Field(description="当前对话最新chart_session,每次操作依次使用新快照")],
1573
+ symbol: str,
1574
+ start_time: Annotated[str, Field(description="基准线起点:已有K线日期,或带时区收盘时间/Unix秒字符串")],
1575
+ start_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True)],
1576
+ end_time: Annotated[str, Field(description="基准线终点:已有K线时间,必须晚于起点")],
1577
+ end_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True)],
1578
+ parallel_time: Annotated[str, Field(description="第三点:另一平行边界的已有K线时间,位于起止时间内;必须由用户明确提供")],
1579
+ parallel_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True, description="第三点精确价格,不得落在基准线上;不自动猜通道宽度")],
1580
+ name: Annotated[str, Field(max_length=48, description="用户指定的完整通道名称,不缩写")] = "",
1581
+ color: Annotated[ColorInput, Field(description="蓝色/info、绿色/success、橙色/warning、红色/danger")] = "info",
1582
+ show_midline: Annotated[bool, Field(strict=True, description="是否显示通道中线,默认显示")] = True,
1583
+ request_id: Annotated[str | None, Field(min_length=1, max_length=128)] = None,
1584
+ ) -> types.CallToolResult:
1585
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1586
+
1587
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1588
+ Only explicit snapshot-editing requests use this tool.
1589
+ Create one finite parallel channel (ascending/descending/horizontal) from three explicit anchors.
1590
+
1591
+ Exact bar-time rules as trend lines. Uses candle-index spacing and linear prices, not calendar
1592
+ elapsed time; no rays, log-price geometry, automatic identification or invented anchors.
1593
+ Read returned upper/lower edges; verify user-requested fields via verify_chart_drawings.
1594
+ """
1595
+ return _line_operation("create", chart_session, symbol, "channel", start_time=start_time,
1596
+ start_price=start_price, end_time=end_time, end_price=end_price,
1597
+ parallel_time=parallel_time, parallel_price=parallel_price,
1598
+ name=name, color=color, show_midline=show_midline, request_id=request_id)
1599
+
1600
+
1601
+ @mcp.tool(name="get_channels", annotations=types.ToolAnnotations(readOnlyHint=True))
1602
+ async def get_channels(chart_session: str, symbol: str) -> types.CallToolResult:
1603
+ """Read AI channels, three source anchors, derived upper/lower edges and stable IDs. No market fetch."""
1604
+ return _line_operation("list", chart_session, symbol, "channel")
1605
+
1606
+
1607
+ @mcp.tool(name="update_channel")
1608
+ async def update_channel(
1609
+ chart_session: str, symbol: str,
1610
+ channel_id: Annotated[str, Field(description="创建/读取返回的channel.id,不是边界线ID")],
1611
+ start_time: str | None = None,
1612
+ start_price: Annotated[float | None, Field(gt=0, allow_inf_nan=False, strict=True)] = None,
1613
+ end_time: str | None = None,
1614
+ end_price: Annotated[float | None, Field(gt=0, allow_inf_nan=False, strict=True)] = None,
1615
+ parallel_time: str | None = None,
1616
+ parallel_price: Annotated[float | None, Field(gt=0, allow_inf_nan=False, strict=True)] = None,
1617
+ name: Annotated[str | None, Field(max_length=48, description="完整名称,不缩写")] = None,
1618
+ color: Annotated[ColorInput | None, Field(description="可直接传绿色/红色等;省略表示不改色")] = None,
1619
+ show_midline: Annotated[bool | None, Field(strict=True)] = None,
1620
+ ) -> types.CallToolResult:
1621
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1622
+
1623
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1624
+ Only explicit snapshot-editing requests use this tool.
1625
+ Edit one channel atomically; recalculate parallel boundaries from its three explicit anchors.
1626
+
1627
+ Unspecified anchors remain fixed. Changing baseline may change width relative to the unchanged
1628
+ third anchor. To change width adjust parallel_price; no partial updates on invalid geometry.
1629
+ Use latest chart_session and verify original user-requested fields after publication.
1630
+ """
1631
+ return _line_operation("update", chart_session, symbol, "channel", channel_id=channel_id,
1632
+ start_time=start_time, start_price=start_price, end_time=end_time,
1633
+ end_price=end_price, parallel_time=parallel_time, parallel_price=parallel_price,
1634
+ name=name, color=color, show_midline=show_midline)
1635
+
1636
+
1637
+ @mcp.tool(name="delete_channel")
1638
+ async def delete_channel(chart_session: str, symbol: str, channel_id: str) -> types.CallToolResult:
1639
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1640
+
1641
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1642
+ Only explicit snapshot-editing requests use this tool. Delete one whole AI channel from the snapshot.
1643
+ """
1644
+ return _line_operation("delete", chart_session, symbol, "channel", channel_id=channel_id)
1645
+
1646
+
1647
+ @mcp.tool(name="create_rectangle")
1648
+ async def create_rectangle(
1649
+ chart_session: Annotated[str, Field(description="当前对话最新 chart_session,操作后依次使用新快照")],
1650
+ symbol: str,
1651
+ start_time: Annotated[str, Field(description="平台框起点:已有 K 线日期,或精确带时区收盘时间/Unix秒字符串")],
1652
+ end_time: Annotated[str, Field(description="平台框终点:已有 K 线时间,必须晚于起点;不自动就近匹配")],
1653
+ lower_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True, description="明确下沿:用户指定,或用户确认的宿主分析方案;执行器不选点")],
1654
+ upper_price: Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True, description="平台上沿价格,必须高于下沿,不自动交换")],
1655
+ name: Annotated[str, Field(max_length=48, description="用户指定或确认方案的完整平台框名称,不缩写")] = "",
1656
+ color: Annotated[ColorInput, Field(description="蓝色/info、绿色/success、橙色/warning、红色/danger")] = "info",
1657
+ show_fill: Annotated[bool, Field(strict=True, description="是否显示淡色填充,默认显示;关闭后保留完整边框")] = True,
1658
+ request_id: Annotated[str | None, Field(min_length=1, max_length=128)] = None,
1659
+ ) -> types.CallToolResult:
1660
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1661
+
1662
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1663
+ Only explicit snapshot-editing requests use this tool.
1664
+ Create one finite time/price rectangle using explicit user or approved-proposal bounds.
1665
+
1666
+ The executor does no pattern recognition: the host may analyze real candles when authorized,
1667
+ propose exact bounds, and honor a user's request to confirm before drawing. No invented bars or rays.
1668
+ Owns all four edges and optional fill under one stable ID. Verify the original requested/approved
1669
+ name/color/time/bounds/show_fill via verify_chart_drawings(kind='rectangle').
1670
+ """
1671
+ return _line_operation("create", chart_session, symbol, "rectangle", start_time=start_time,
1672
+ end_time=end_time, lower_price=lower_price, upper_price=upper_price,
1673
+ name=name, color=color, show_fill=show_fill, request_id=request_id)
1674
+
1675
+
1676
+ @mcp.tool(name="get_rectangles", annotations=types.ToolAnnotations(readOnlyHint=True))
1677
+ async def get_rectangles(chart_session: str, symbol: str) -> types.CallToolResult:
1678
+ """Read AI platform rectangles, exact time/price bounds, fill state and stable IDs. No market fetch."""
1679
+ return _line_operation("list", chart_session, symbol, "rectangle")
1680
+
1681
+
1682
+ @mcp.tool(name="update_rectangle")
1683
+ async def update_rectangle(
1684
+ chart_session: str, symbol: str,
1685
+ rectangle_id: Annotated[str, Field(description="创建/读回返回的 rectangle.id,不是名称或手动图形 ID")],
1686
+ start_time: str | None = None, end_time: str | None = None,
1687
+ lower_price: Annotated[float | None, Field(gt=0, allow_inf_nan=False, strict=True)] = None,
1688
+ upper_price: Annotated[float | None, Field(gt=0, allow_inf_nan=False, strict=True)] = None,
1689
+ name: Annotated[str | None, Field(max_length=48, description="用户指定的完整名称,不缩写")] = None,
1690
+ color: Annotated[ColorInput | None, Field(description="仅修改所请求颜色;绿色/green/success同义")] = None,
1691
+ show_fill: Annotated[bool | None, Field(strict=True)] = None,
1692
+ ) -> types.CallToolResult:
1693
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1694
+
1695
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1696
+ Only explicit snapshot-editing requests use this tool.
1697
+ Atomically edit one platform rectangle by ID; unspecified bounds/style remain fixed.
1698
+
1699
+ Change one bound or both together; invalid time/price order rejects the whole update.
1700
+ Use the latest chart_session and verify original requested fields, not copied actual values.
1701
+ """
1702
+ return _line_operation("update", chart_session, symbol, "rectangle", rectangle_id=rectangle_id,
1703
+ start_time=start_time, end_time=end_time, lower_price=lower_price,
1704
+ upper_price=upper_price, name=name, color=color, show_fill=show_fill)
1705
+
1706
+
1707
+ @mcp.tool(name="delete_rectangle")
1708
+ async def delete_rectangle(chart_session: str, symbol: str, rectangle_id: str) -> types.CallToolResult:
1709
+ """LEGACY SNAPSHOT ONLY. Not for the current browser chart, even literal requests.
1710
+
1711
+ For current charts use get_chart_context -> prepare_chart_edit -> apply_chart_edit -> get_chart_edit_status.
1712
+ Only explicit snapshot-editing requests use this tool. Delete one whole AI rectangle from the snapshot.
1713
+ """
1714
+ return _line_operation("delete", chart_session, symbol, "rectangle", rectangle_id=rectangle_id)
1715
+
1716
+
1717
+ @mcp.tool(name="verify_chart_drawings", annotations=types.ToolAnnotations(readOnlyHint=True))
1718
+ async def verify_chart_drawings(
1719
+ chart_session: str, symbol: str,
1720
+ expectations: Annotated[list[DrawingExpectation], Field(min_length=1, max_length=180,
1721
+ description="按原始要求或用户确认的方案及覆盖项独立填写期望,不抄修改结果;核对名称/颜色/锚点,删除填exists=false")],
1722
+ ) -> types.CallToolResult:
1723
+ """Read-only exact snapshot verification. Catch shortened labels, omitted colors and wrong anchors.
1724
+
1725
+ Return each expected/actual field and mismatch; matches=false must not be described as success.
1726
+ Never publishes a snapshot or proves visible rendering. Verify only supplied expectations,
1727
+ not inferred human intent. Repair mismatches only within the user's existing instructions
1728
+ or confirmed proposal; never alter an approved plan to make a mismatching result pass.
1729
+ """
1730
+ try:
1731
+ payload = _drawing_snapshot(chart_session, symbol)
1732
+ checked = verify_drawings(payload, expectations)
1733
+ except LineError as exc:
1734
+ return _drawing_error(exc)
1735
+ data = {"ok": True, "chart_session": chart_session, "symbol": payload.get("symbol"),
1736
+ "interval": payload.get("interval"), **checked}
1737
+ return _result(data, "绘图参数核对(不代表屏幕核验) · " + json.dumps(data, ensure_ascii=False, separators=(",", ":")))
1738
+
1739
+
1740
+ def main(argv: list[str] | None = None) -> None:
1741
+ parser = argparse.ArgumentParser(description="Standalone dsh_kline MCP server")
1742
+ parser.add_argument("--http", action="store_true", help="Run streamable HTTP instead of stdio")
1743
+ parser.add_argument("--port", type=int, default=8010)
1744
+ args = parser.parse_args(argv)
1745
+ start_chart_service()
1746
+ if args.http:
1747
+ mcp.settings.host = "127.0.0.1"
1748
+ mcp.settings.port = args.port
1749
+ mcp.run(transport="streamable-http")
1750
+ else:
1751
+ mcp.run(transport="stdio")
1752
+
1753
+
1754
+ if __name__ == "__main__":
1755
+ main()