@apocdata-info/mcp-server 0.1.0

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 (74) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/LICENSE +191 -0
  3. package/README.md +230 -0
  4. package/dist/cache.d.ts +26 -0
  5. package/dist/cache.js +51 -0
  6. package/dist/cache.js.map +1 -0
  7. package/dist/client.js +113 -0
  8. package/dist/errors.d.ts +37 -0
  9. package/dist/errors.js +56 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/index.d.ts +17 -0
  12. package/dist/index.js +259 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/resources.js +229 -0
  15. package/dist/server.d.ts +20 -0
  16. package/dist/server.js +69 -0
  17. package/dist/server.js.map +1 -0
  18. package/dist/tools/factor-registry.d.ts +17 -0
  19. package/dist/tools/factor-registry.js +36 -0
  20. package/dist/tools/factor-registry.js.map +1 -0
  21. package/dist/tools/index.d.ts +21 -0
  22. package/dist/tools/index.js +45 -0
  23. package/dist/tools/index.js.map +1 -0
  24. package/dist/tools/macro-dashboard.d.ts +17 -0
  25. package/dist/tools/macro-dashboard.js +30 -0
  26. package/dist/tools/macro-dashboard.js.map +1 -0
  27. package/dist/tools/macro-indicator.d.ts +17 -0
  28. package/dist/tools/macro-indicator.js +45 -0
  29. package/dist/tools/macro-indicator.js.map +1 -0
  30. package/dist/tools/quotes-snapshot.d.ts +17 -0
  31. package/dist/tools/quotes-snapshot.js +39 -0
  32. package/dist/tools/quotes-snapshot.js.map +1 -0
  33. package/dist/tools/stock-bars-daily.d.ts +17 -0
  34. package/dist/tools/stock-bars-daily.js +45 -0
  35. package/dist/tools/stock-bars-daily.js.map +1 -0
  36. package/dist/tools/stock-detail.d.ts +17 -0
  37. package/dist/tools/stock-detail.js +38 -0
  38. package/dist/tools/stock-detail.js.map +1 -0
  39. package/dist/tools/stock-financials.d.ts +17 -0
  40. package/dist/tools/stock-financials.js +36 -0
  41. package/dist/tools/stock-financials.js.map +1 -0
  42. package/dist/tools/stock-list.d.ts +17 -0
  43. package/dist/tools/stock-list.js +39 -0
  44. package/dist/tools/stock-list.js.map +1 -0
  45. package/dist/tools/stock-news.d.ts +17 -0
  46. package/dist/tools/stock-news.js +36 -0
  47. package/dist/tools/stock-news.js.map +1 -0
  48. package/dist/tools/stock-quote.d.ts +17 -0
  49. package/dist/tools/stock-quote.js +32 -0
  50. package/dist/tools/stock-quote.js.map +1 -0
  51. package/dist/tools/top10-holders.d.ts +17 -0
  52. package/dist/tools/top10-holders.js +35 -0
  53. package/dist/tools/top10-holders.js.map +1 -0
  54. package/dist/tools/trade-days.d.ts +17 -0
  55. package/dist/tools/trade-days.js +36 -0
  56. package/dist/tools/trade-days.js.map +1 -0
  57. package/dist/tools/types.d.ts +29 -0
  58. package/dist/tools/types.js +16 -0
  59. package/dist/tools/types.js.map +1 -0
  60. package/dist/tools.js +540 -0
  61. package/dist/transport.d.ts +44 -0
  62. package/dist/transport.js +87 -0
  63. package/dist/transport.js.map +1 -0
  64. package/dist/types.d.ts +54 -0
  65. package/dist/types.js +16 -0
  66. package/dist/types.js.map +1 -0
  67. package/package.json +67 -0
  68. package/scripts/client-unit-test.mjs +147 -0
  69. package/scripts/contract-test.mjs +167 -0
  70. package/scripts/coverage-test.mjs +126 -0
  71. package/scripts/error-path-test.mjs +110 -0
  72. package/scripts/freshness-probe.mjs +144 -0
  73. package/scripts/integration-test.mjs +284 -0
  74. package/scripts/mcp-e2e-test.mjs +196 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,50 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@apocdata/mcp-server` are documented here.
4
+
5
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ### Added
10
+
11
+ - **后端 §5.5 数据 SLA 标注**:响应头 `X-Tdc-Freshness-Tier` + `X-Tdc-Freshness-Detail` 透传数据时效分类(intraday / post-close / t0-morning / quarterly / metadata / aggregated 共 6 档)。MCP server 已通过 `x-tdc-` 前缀自动透传,guide resource 加了 6 档说明 + 典型用法
12
+ - **后端 §6.3 OpenAPI @Operation 文案调优**:12 个易混淆工具(quote / stock / daily / ranking / announcements / news / concepts / ths-boards / hot-money / hot-money-detail / macro / factors / profile-full / factor-categories)的 description 加"何时用 / 不该用"对照,Java 侧文档对齐 MCP server tools.ts
13
+ - **后端 §2.6 fields 全局扩展**:所有 47 个 `/open/data/*` 接口都支持 `?fields=col1,col2`(之前只有 financial / announcements)。MCP resources 的 `apocdata://limits` 段相应更新说明全局可用
14
+ - **后端 announcements 加过滤参数**:解决用户实测痛点"只能拿最近 5 条无任何过滤"。新增 `startDate` / `endDate` / `category` / `q` / `includeContent` 参数;limit 上限从 5 提到 30。MCP tool schema 同步更新,对应字段同步进 SKILL.md
15
+ - **后端 news 加过滤参数**:与 announcements 同款思路。新增 `startDate` / `endDate` / `category` / `q` / `sentiment`(bullish/neutral/bearish)/ `importance`(high/medium/low);limit 上限从 10 提到 30;时间过滤优先级 startDate+endDate > hours
16
+ - **后端 calendar 加 `?detail=true`**:路线图差异登记"pretrade_date 可由相邻交易日计算"项落地。默认返回 List<String> 向后兼容;detail=true 返回 List<{trade_date, pretrade_date}>
17
+ - **MCP resources**:暴露 3 个 markdown 文档(`apocdata://guide` 接入指南 / `apocdata://scenarios` 场景速查 / `apocdata://limits` limit-fields-compact 速查表),Agent 一连上即可读到全局上下文
18
+ - **工具 description 调优**:易混淆的工具组(quote vs profile-full、daily vs ranking、news vs announcements、concepts vs ths-boards、hot-money vs hot-money-detail、macro 三件套)加入"何时用 / 不该用"提示,提升 Agent 选择准确率
19
+ - **GitHub Actions**:
20
+ - `test.yml`:push / PR 触发,矩阵 Node 18/20/22 × Ubuntu/macOS,跑 unit + integration(不打外网)
21
+ - `publish.yml`:GitHub Release 触发自动 `npm publish --access public --provenance`;支持 workflow_dispatch dry-run
22
+ - **CHANGELOG.md**:Keep-a-Changelog 格式
23
+ - **发包脚本**:`npm run publish:dry`、`npm run version:patch|minor|major`、`prepublishOnly` 自动跑 test:ci
24
+
25
+ ### Changed
26
+
27
+ - e2e 测试用例从 11 涨到 16(加 resources/list、resources/read、未知 URI 错误响应)
28
+
29
+ ## [0.1.0] - 2026-05-27
30
+
31
+ ### Added
32
+
33
+ - 初始版本,覆盖 ApocData `/open/data/*` 全部 47 个免鉴权接口
34
+ - MCP server(stdio transport),自动透传 `X-Tdc-*` 元信息头与 `Cache-Control`
35
+ - HTTP client:30s 超时(AbortController)、5xx/网络异常指数 backoff 重试 ×2、4xx 不重试、错误归一化为 `NetworkError`
36
+ - 优雅退出:SIGTERM/SIGINT 等 in-flight 请求结束(最多 5s)后再退
37
+ - CLI:`--version` / `--help`,环境变量 `APOCDATA_BASE_URL` / `APOCDATA_DEBUG` / `APOCDATA_TIMEOUT_MS` / `APOCDATA_MAX_RETRIES`
38
+ - 测试套件 6 套:unit / contract / errors / coverage / e2e / integration,总计 125 PROD case
39
+
40
+ ### Known limitations
41
+
42
+ 后端服务 `data.tianqis.com` 当前部署版本滞后于源码,以下能力 MCP 客户端代码已就绪,需后端 redeploy 才会生效:
43
+
44
+ - `profile/full` 与 `factor-categories` 端点(404)
45
+ - 多接口非法 enum 校验(`ranking` direction / `macro` type / `sector-flow` type / `hot-rank` type / `margin` exchange / `macro-latest|definition` type)
46
+ - `X-Tdc-Error-Code` / `X-Tdc-RateLimit-Remaining` / `X-Tdc-Truncated` 响应头
47
+ - `format=compact` 列式输出
48
+
49
+ [Unreleased]: https://github.com/ApocData/ApocData-skill/compare/v0.1.0...HEAD
50
+ [0.1.0]: https://github.com/ApocData/ApocData-skill/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form, made
34
+ available under the License, as indicated by a copyright notice that is included
35
+ in or attached to the work (an example is provided in the Appendix below).
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work
47
+ by the copyright owner or by an individual or Legal Entity authorized to submit
48
+ on behalf of the copyright owner. For the purposes of this definition,
49
+ "submitted" means any form of electronic, verbal, or written communication sent
50
+ to the Licensor or its representatives, including but not limited to
51
+ communication on electronic mailing lists, source code control systems, and
52
+ issue tracking systems that are managed by, or on behalf of, the Licensor for
53
+ the purpose of discussing and improving the Work, but excluding communication
54
+ that is conspicuously marked or otherwise designated in writing by the copyright
55
+ owner as "Not a Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License.
62
+
63
+ Subject to the terms and conditions of this License, each Contributor hereby
64
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65
+ irrevocable copyright license to reproduce, prepare Derivative Works of,
66
+ publicly display, publicly perform, sublicense, and distribute the Work and such
67
+ Derivative Works in Source or Object form.
68
+
69
+ 3. Grant of Patent License.
70
+
71
+ Subject to the terms and conditions of this License, each Contributor hereby
72
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73
+ irrevocable (except as stated in this section) patent license to make, have
74
+ made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75
+ such license applies only to those patent claims licensable by such Contributor
76
+ that are necessarily infringed by their Contribution(s) alone or by combination
77
+ of their Contribution(s) with the Work to which such Contribution(s) was
78
+ submitted. If You institute patent litigation against any entity (including a
79
+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80
+ Contribution incorporated within the Work constitutes direct or contributory
81
+ patent infringement, then any patent licenses granted to You under this License
82
+ for that Work shall terminate as of the date such litigation is filed.
83
+
84
+ 4. Redistribution.
85
+
86
+ You may reproduce and distribute copies of the Work or Derivative Works thereof
87
+ in any medium, with or without modifications, and in Source or Object form,
88
+ provided that You meet the following conditions:
89
+
90
+ You must give any other recipients of the Work or Derivative Works a copy of
91
+ this License; and
92
+ You must cause any modified files to carry prominent notices stating that You
93
+ changed the files; and
94
+ You must retain, in the Source form of any Derivative Works that You distribute,
95
+ all copyright, patent, trademark, and attribution notices from the Source form
96
+ of the Work, excluding those notices that do not pertain to any part of the
97
+ Derivative Works; and
98
+ If the Work includes a "NOTICE" text file as part of its distribution, then any
99
+ Derivative Works that You distribute must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, excluding those notices
101
+ that do not pertain to any part of the Derivative Works, in at least one of the
102
+ following places: within a NOTICE text file distributed as part of the
103
+ Derivative Works; within the Source form or documentation, if provided along
104
+ with the Derivative Works; or, within a display generated by the Derivative
105
+ Works, if and wherever such third-party notices normally appear. The contents of
106
+ the NOTICE file are for informational purposes only and do not modify the
107
+ License. You may add Your own attribution notices within Derivative Works that
108
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+ provided that such additional attribution notices cannot be construed as
110
+ modifying the License.
111
+ You may add Your own copyright statement to Your modifications and may provide
112
+ additional or different license terms and conditions for use, reproduction, or
113
+ distribution of Your modifications, or for any such Derivative Works as a whole,
114
+ provided Your use, reproduction, and distribution of the Work otherwise complies
115
+ with the conditions stated in this License.
116
+
117
+ 5. Submission of Contributions.
118
+
119
+ Unless You explicitly state otherwise, any Contribution intentionally submitted
120
+ for inclusion in the Work by You to the Licensor shall be under the terms and
121
+ conditions of this License, without any additional terms or conditions.
122
+ Notwithstanding the above, nothing herein shall supersede or modify the terms of
123
+ any separate license agreement you may have executed with Licensor regarding
124
+ such Contributions.
125
+
126
+ 6. Trademarks.
127
+
128
+ This License does not grant permission to use the trade names, trademarks,
129
+ service marks, or product names of the Licensor, except as required for
130
+ reasonable and customary use in describing the origin of the Work and
131
+ reproducing the content of the NOTICE file.
132
+
133
+ 7. Disclaimer of Warranty.
134
+
135
+ Unless required by applicable law or agreed to in writing, Licensor provides the
136
+ Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138
+ including, without limitation, any warranties or conditions of TITLE,
139
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140
+ solely responsible for determining the appropriateness of using or
141
+ redistributing the Work and assume any risks associated with Your exercise of
142
+ permissions under this License.
143
+
144
+ 8. Limitation of Liability.
145
+
146
+ In no event and under no legal theory, whether in tort (including negligence),
147
+ contract, or otherwise, unless required by applicable law (such as deliberate
148
+ and grossly negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special, incidental,
150
+ or consequential damages of any character arising as a result of this License or
151
+ out of the use or inability to use the Work (including but not limited to
152
+ damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153
+ any and all other commercial damages or losses), even if such Contributor has
154
+ been advised of the possibility of such damages.
155
+
156
+ 9. Accepting Warranty or Additional Liability.
157
+
158
+ While redistributing the Work or Derivative Works thereof, You may choose to
159
+ offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160
+ other liability obligations and/or rights consistent with this License. However,
161
+ in accepting such obligations, You may act only on Your own behalf and on Your
162
+ sole responsibility, not on behalf of any other Contributor, and only if You
163
+ agree to indemnify, defend, and hold each Contributor harmless for any liability
164
+ incurred by, or claims asserted against, such Contributor by reason of your
165
+ accepting any such warranty or additional liability.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ APPENDIX: How to apply the Apache License to your work
170
+
171
+ To apply the Apache License to your work, attach the following boilerplate
172
+ notice, with the fields enclosed by brackets "{}" replaced with your own
173
+ identifying information. (Don't include the brackets!) The text should be
174
+ enclosed in the appropriate comment syntax for the file format. We also
175
+ recommend that a file or class name and description of purpose be included on
176
+ the same "printed page" as the copyright notice for easier identification within
177
+ third-party archives.
178
+
179
+ Copyright 2023 BladeX (https://bladex.cn)
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,230 @@
1
+ # @apocdata/mcp-server
2
+
3
+ 天启至数 **ApocData** 的 MCP(Model Context Protocol)Server。把 46 个免鉴权 A 股数据接口包装成 MCP tools,可在 Claude Desktop / Cursor / Cline / Continue 等任意 MCP client 中直接调用。
4
+
5
+ - 数据源:`https://data.tianqis.com/api/blade-dataplatform/open/data/*`
6
+ - 无需 API Key,无需注册(网关已配置 `/open/**` 免鉴权)
7
+ - 自动透传 `X-Tdc-*` 元信息头(限流剩余/截断标志/错误码/缓存策略)
8
+ - 46 工具覆盖:行情、估值、财务、股东、资金流、涨跌停、板块、公告、宏观、因子、综合画像
9
+
10
+ ---
11
+
12
+ ## 安装
13
+
14
+ ### 方式 A:npx(推荐,零安装)
15
+
16
+ 直接在 client 配置里写 `npx -y @apocdata/mcp-server`,无需手动 install。
17
+
18
+ ### 方式 B:全局安装
19
+
20
+ ```bash
21
+ npm install -g @apocdata/mcp-server
22
+ apocdata-mcp # 可执行命令
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Client 配置示例
28
+
29
+ ### Claude Desktop
30
+
31
+ 编辑 `~/Library/Application Support/Claude/claude_desktop_config.json`(macOS)或 `%APPDATA%\Claude\claude_desktop_config.json`(Windows):
32
+
33
+ ```json
34
+ {
35
+ "mcpServers": {
36
+ "apocdata": {
37
+ "command": "npx",
38
+ "args": ["-y", "@apocdata/mcp-server"]
39
+ }
40
+ }
41
+ }
42
+ ```
43
+
44
+ ### Cursor
45
+
46
+ `~/.cursor/mcp.json`:
47
+
48
+ ```json
49
+ {
50
+ "mcpServers": {
51
+ "apocdata": {
52
+ "command": "npx",
53
+ "args": ["-y", "@apocdata/mcp-server"]
54
+ }
55
+ }
56
+ }
57
+ ```
58
+
59
+ ### Cline / Continue / 其它 stdio MCP client
60
+
61
+ 同上,传 `command=npx, args=["-y","@apocdata/mcp-server"]` 即可。
62
+
63
+ ### CLI flags
64
+
65
+ ```bash
66
+ apocdata-mcp --version # 打印版本号
67
+ apocdata-mcp --help # 显示完整用法
68
+ ```
69
+
70
+ ### 信号
71
+
72
+ - `SIGTERM` / `SIGINT`:优雅退出。等正在进行的请求完成(最多 5 秒),再关闭 transport 退出。
73
+
74
+ ### 调试模式
75
+
76
+ 环境变量 `APOCDATA_DEBUG=1` 会把每次 HTTP 调用的 path/status/meta 打到 stderr:
77
+
78
+ ```json
79
+ {
80
+ "mcpServers": {
81
+ "apocdata": {
82
+ "command": "npx",
83
+ "args": ["-y", "@apocdata/mcp-server"],
84
+ "env": { "APOCDATA_DEBUG": "1" }
85
+ }
86
+ }
87
+ }
88
+ ```
89
+
90
+ ### 自定义 BASE URL
91
+
92
+ 环境变量 `APOCDATA_BASE_URL` 可指向内网/私有部署:
93
+
94
+ ```json
95
+ "env": { "APOCDATA_BASE_URL": "https://intranet.example.com/api/blade-dataplatform/open/data" }
96
+ ```
97
+
98
+ ### 超时与重试
99
+
100
+ | 环境变量 | 默认 | 说明 |
101
+ | --- | --- | --- |
102
+ | `APOCDATA_TIMEOUT_MS` | `30000` | 单次请求超时(毫秒),到时间 AbortController 中断 |
103
+ | `APOCDATA_MAX_RETRIES` | `2` | 5xx 或网络错误重试次数(不含首次),指数 backoff 500→1000→2000ms |
104
+
105
+ 4xx 不重试(业务错误重试无意义)。重试用尽后返回最后一次的 5xx 响应,或抛 `NetworkError`(网络异常)。
106
+
107
+ ---
108
+
109
+ ## 工具清单(46 个)
110
+
111
+ | 类别 | 工具 |
112
+ | --- | --- |
113
+ | **A. 行情与估值(10)** | `quote` `quotes` `daily` `stock` `stocks` `st` `ranking` `indexes` `index-daily` `hot-rank` |
114
+ | **B. 财务与股东(8)** | `financial` `express` `dividend` `holders` `holder-number` `share-float` `repurchase` `block-trade` |
115
+ | **C. 资金流向(8)** | `moneyflow` `hsgt` `hk-hold` `hk-daily` `margin` `dragon-tiger` `hot-money` `hot-money-detail` |
116
+ | **D. 涨跌停与板块(4)** | `limit-list` `limit-step` `sector-flow` `cyq-perf` |
117
+ | **E. 公告/调研(2)** | `announcements` `survey` |
118
+ | **F. 板块成分(4)** | `concepts` `concept-stocks` `ths-boards` `ths-board-stocks` |
119
+ | **G. 可转债(2)** | `convertible-bonds` `cb-price-chg` |
120
+ | **H. 因子(2)** | `factors` `tech-factor` |
121
+ | **I. 宏观(3)** | `macro` `macro-latest` `macro-definition` |
122
+ | **J. 日历(1)** | `calendar` |
123
+ | **K. 综合(2)** | `profile-full` `factor-categories` |
124
+
125
+ 每个 tool 的入参/出参/默认值在 MCP 协议层用 JSON Schema 暴露,client 会自动展示。
126
+
127
+ ## MCP Resources
128
+
129
+ 除工具外还暴露 3 个 markdown 文档,Agent 通过 `resources/list` 和 `resources/read` 拉取:
130
+
131
+ | URI | 内容 |
132
+ | --- | --- |
133
+ | `apocdata://guide` | 全局接入指南:46 工具分组、symbol 格式、延迟/限流/错误协议、元信息头说明 |
134
+ | `apocdata://scenarios` | 场景速查:常见用户意图到工具组合的映射 + 反模式(避免串调 8 个接口) |
135
+ | `apocdata://limits` | limit/fields/compact 速查表:每个工具的默认值/上限/字段裁剪支持情况 |
136
+
137
+ ---
138
+
139
+ ## 用法示例(在 Claude 里直接问)
140
+
141
+ ```
142
+ > 帮我看下贵州茅台最近 5 天行情
143
+ (Claude 调用 daily(symbol="600519", limit=5))
144
+
145
+ > 现在涨幅榜前 10 是哪些股票?
146
+ (Claude 调用 ranking(type="gainers", limit=10))
147
+
148
+ > 整理一下平安银行的综合画像
149
+ (Claude 调用 profile-full(symbol="000001"))
150
+
151
+ > CPI 最近一次数据是多少?
152
+ (Claude 调用 macro-latest(type="cpi"))
153
+ ```
154
+
155
+ ---
156
+
157
+ ## 性能与限流
158
+
159
+ - 单 IP 限流:60 req/min(响应头 `X-Tdc-RateLimit-Remaining` 透传剩余配额)
160
+ - 缓存策略:盘中实时数据 5s、盘后日更 5min、元数据 1h(`Cache-Control` 头自动给)
161
+ - `limit` 参数上限 50,超出会**静默截断**(看响应头 `X-Tdc-Truncated`)
162
+ - 大批量数据建议用 `format=compact` 列式输出,节省 60-70% token
163
+ - 字段较多的接口(如 financial、announcements)支持 `fields=...` 裁剪
164
+
165
+ 详细行为参考主 SKILL 文档:<https://github.com/ApocData/ApocData-skill>
166
+
167
+ ---
168
+
169
+ ## 开发
170
+
171
+ ```bash
172
+ git clone https://github.com/ApocData/ApocData-skill.git
173
+ cd ApocData-skill/mcp-server
174
+ npm install
175
+ npm run build
176
+ npm start
177
+ ```
178
+
179
+ 源码结构:
180
+
181
+ ```
182
+ src/
183
+ index.ts # MCP server 入口,stdio transport
184
+ client.ts # HTTP client,BASE_URL 调用 + meta 头提取
185
+ tools.ts # 46 个工具的配置表(声明式)
186
+ ```
187
+
188
+ 要加一个新接口:在 `tools.ts` 对应分组里加一条 `ToolDef`,重新 build 即可,无需改其它代码。
189
+
190
+ ## 测试
191
+
192
+ ```bash
193
+ npm test # build + 6 类测试全跑(需在 tianqi-mcp 目录执行)
194
+ npm run test:unit # client 单测:超时/重试/URL 构造,不打外网
195
+ npm run test:contract # 46 工具逐个真实 HTTP 调用(happy path)
196
+ npm run test:errors # 错误路径:非法参数 / 不存在 symbol / 日期格式
197
+ npm run test:coverage # 限流头/截断头/所有枚举值遍历
198
+ npm run test:e2e # MCP 协议层:stdio JSON-RPC + isError + compact
199
+ npm run test:integration # 集成:mock HTTP + 子进程 server,验证 retries / timeout / --version / SIGTERM
200
+ ```
201
+
202
+ 六个脚本对应六种验证:
203
+
204
+ | 脚本 | 验证 |
205
+ | --- | --- |
206
+ | `client-unit-test.mjs` | client 4xx 不重试、5xx 重试到成功/用尽、超时归一化、meta 头提取、URL 构造(mock fetch) |
207
+ | `contract-test.mjs` | 所有 46 端点参数名/必填和后端 `@RequestParam` 一致;happy path 全部 200 |
208
+ | `error-path-test.mjs` | 业务错误用 HTTP 200 + `success=false` 表达;标记 PROD(已部署)/ LAG(源码已写、线上待发版)|
209
+ | `coverage-test.mjs` | 限流头 / 截断头透传;所有 enum 工具(ranking / limit-list / sector-flow / hot-rank / margin / macro)的合法值全部遍历 |
210
+ | `mcp-e2e-test.mjs` | MCP 协议正确:tools/list 46 个、isError 在 HTTP 4xx 和 `success=false` 都正确标记、compact 模式列式输出 |
211
+ | `integration-test.mjs` | 真实 backoff 耗时验证;真实 timeout 触发;`--version` / `--help` CLI;SIGTERM 空闲即时退出;SIGTERM in-flight 等待完成后退出 |
212
+
213
+ 私有部署:`APOCDATA_BASE_URL=http://your.host/path npm test`
214
+
215
+ ### 已知 LAG(线上待发版)
216
+
217
+ 以下能力源码已实现(路线图 §2.1 / §5.1 / §5.3),但 `data.tianqis.com` 当前部署的版本尚未生效。后端 redeploy 后无需改 MCP server,行为自动恢复:
218
+
219
+ - `ranking` / `macro` / `macro/latest` / `macro/definition` / `sector-flow` / `hot-rank` / `margin` 的非法 enum 校验
220
+ - `X-Tdc-Error-Code` 响应头
221
+ - `X-Tdc-RateLimit-Remaining` 响应头(限流剩余配额)
222
+ - `X-Tdc-Truncated` 响应头(limit 超上限通知;注意 controller 内的 `safeLimit` 截断本身已生效,只是没有头通知)
223
+ - `format=compact` 列式输出
224
+ - `/profile/full` 和 `/factor-categories` 两个端点本身
225
+
226
+ ---
227
+
228
+ ## License
229
+
230
+ Apache-2.0
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ *
14
+ * @author Chill
15
+ */
16
+ /**
17
+ * 缓存包装:命中直接返,未命中调 factory 并缓存。
18
+ * @param key 缓存键
19
+ * @param ttlMs 本次缓存 TTL(毫秒);若 undefined 用默认 5min
20
+ * @param factory 数据源工厂
21
+ */
22
+ export declare function withCache<T>(key: string, ttlMs: number | undefined, factory: () => Promise<T>): Promise<T>;
23
+ /**
24
+ * 测试用:清空缓存。
25
+ */
26
+ export declare function clearCache(): void;
package/dist/cache.js ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ *
14
+ * @author Chill
15
+ */
16
+ import { LRUCache } from "lru-cache";
17
+ /**
18
+ * MCP 端进程内 LRU 缓存。
19
+ * - 容量 1000 条
20
+ * - 默认 TTL 5min(若 factory 未指定)
21
+ * - key 形如 "tool:get_stock_quote:000001"
22
+ */
23
+ const cache = new LRUCache({
24
+ max: 1000,
25
+ ttl: 5 * 60 * 1000,
26
+ });
27
+ /**
28
+ * 缓存包装:命中直接返,未命中调 factory 并缓存。
29
+ * @param key 缓存键
30
+ * @param ttlMs 本次缓存 TTL(毫秒);若 undefined 用默认 5min
31
+ * @param factory 数据源工厂
32
+ */
33
+ export async function withCache(key, ttlMs, factory) {
34
+ const hit = cache.get(key);
35
+ if (hit !== undefined)
36
+ return hit;
37
+ const value = await factory();
38
+ if (ttlMs !== undefined) {
39
+ cache.set(key, value, { ttl: ttlMs });
40
+ }
41
+ else {
42
+ cache.set(key, value);
43
+ }
44
+ return value;
45
+ }
46
+ /**
47
+ * 测试用:清空缓存。
48
+ */
49
+ export function clearCache() {
50
+ cache.clear();
51
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC;;;;;GAKG;AACH,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAc;IACtC,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI;CACnB,CAAC,CAAC;AAEH;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,GAAW,EACX,KAAyB,EACzB,OAAyB;IAEzB,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAkB,CAAC;IAC5C,IAAI,GAAG,KAAK,SAAS;QAAE,OAAO,GAAG,CAAC;IAClC,MAAM,KAAK,GAAG,MAAM,OAAO,EAAE,CAAC;IAC9B,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC;IACxC,CAAC;SAAM,CAAC;QACN,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU;IACxB,KAAK,CAAC,KAAK,EAAE,CAAC;AAChB,CAAC"}
package/dist/client.js ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * 通用 HTTP client,封装 ApocData /open/data/* 调用。
3
+ *
4
+ * - GET only,参数序列化为 query string
5
+ * - 自动透传 X-Tdc-* 元信息头(限流/截断/错误码/缓存)
6
+ * - 超时控制(AbortController)和 5xx 自动重试(指数 backoff)
7
+ * - 错误归一化为 NetworkError,保留 HTTP 状态和原始消息
8
+ */
9
+ const META_HEADER_PREFIX = 'x-tdc-';
10
+ const CACHE_CONTROL_HEADER = 'cache-control';
11
+ export class ApocDataClient {
12
+ baseUrl;
13
+ timeoutMs;
14
+ maxRetries;
15
+ retryBackoffMs;
16
+ constructor(baseUrl, options = {}) {
17
+ this.baseUrl = baseUrl;
18
+ this.timeoutMs = options.timeoutMs ?? 30_000;
19
+ this.maxRetries = options.maxRetries ?? 2;
20
+ this.retryBackoffMs = options.retryBackoffMs ?? 500;
21
+ }
22
+ async call(path, params) {
23
+ const url = this.buildUrl(path, params);
24
+ let lastError = null;
25
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
26
+ try {
27
+ const result = await this.fetchOnce(url);
28
+ // 5xx 触发重试;4xx 直接返回(业务问题,不该重试)
29
+ if (result.status >= 500 && attempt < this.maxRetries) {
30
+ await this.sleep(this.backoff(attempt));
31
+ continue;
32
+ }
33
+ return result;
34
+ }
35
+ catch (err) {
36
+ lastError = err;
37
+ // AbortError 或网络错误:重试
38
+ if (attempt < this.maxRetries) {
39
+ await this.sleep(this.backoff(attempt));
40
+ continue;
41
+ }
42
+ }
43
+ }
44
+ // 重试用尽,抛规范化错误
45
+ throw new NetworkError(this.formatError(lastError), lastError);
46
+ }
47
+ async fetchOnce(url) {
48
+ const ctrl = new AbortController();
49
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
50
+ try {
51
+ const res = await fetch(url, {
52
+ method: 'GET',
53
+ signal: ctrl.signal,
54
+ headers: {
55
+ 'User-Agent': 'apocdata-mcp-server/0.1.0',
56
+ Accept: 'application/json',
57
+ },
58
+ });
59
+ const meta = {};
60
+ for (const [key, value] of res.headers) {
61
+ const lower = key.toLowerCase();
62
+ if (lower.startsWith(META_HEADER_PREFIX) || lower === CACHE_CONTROL_HEADER) {
63
+ meta[key] = value;
64
+ }
65
+ }
66
+ const text = await res.text();
67
+ let body;
68
+ try {
69
+ body = text ? JSON.parse(text) : null;
70
+ }
71
+ catch {
72
+ body = { raw: text };
73
+ }
74
+ return { body, meta, status: res.status };
75
+ }
76
+ finally {
77
+ clearTimeout(timer);
78
+ }
79
+ }
80
+ buildUrl(path, params) {
81
+ const trimmed = path.replace(/^\/+/, '');
82
+ const url = new URL(`${this.baseUrl.replace(/\/+$/, '')}/${trimmed}`);
83
+ for (const [k, v] of Object.entries(params)) {
84
+ if (v === undefined || v === null || v === '')
85
+ continue;
86
+ url.searchParams.append(k, String(v));
87
+ }
88
+ return url.toString();
89
+ }
90
+ backoff(attempt) {
91
+ // attempt 从 0 开始:500ms, 1000ms, 2000ms ...
92
+ return this.retryBackoffMs * Math.pow(2, attempt);
93
+ }
94
+ sleep(ms) {
95
+ return new Promise((r) => setTimeout(r, ms));
96
+ }
97
+ formatError(err) {
98
+ if (err instanceof Error) {
99
+ if (err.name === 'AbortError')
100
+ return `Request timed out after ${this.timeoutMs}ms`;
101
+ return err.message;
102
+ }
103
+ return String(err);
104
+ }
105
+ }
106
+ export class NetworkError extends Error {
107
+ cause;
108
+ constructor(message, cause) {
109
+ super(message);
110
+ this.cause = cause;
111
+ this.name = 'NetworkError';
112
+ }
113
+ }