bcs-mcp 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +141 -0
- package/dist/catalog.js +63 -0
- package/dist/catalog.js.map +1 -0
- package/dist/client.js +179 -0
- package/dist/client.js.map +1 -0
- package/dist/endpoints.js +18 -0
- package/dist/endpoints.js.map +1 -0
- package/dist/helpers.js +144 -0
- package/dist/helpers.js.map +1 -0
- package/dist/index.js +33 -0
- package/dist/index.js.map +1 -0
- package/dist/instruments-cache.js +119 -0
- package/dist/instruments-cache.js.map +1 -0
- package/dist/output.js +139 -0
- package/dist/output.js.map +1 -0
- package/dist/prompts.js +209 -0
- package/dist/prompts.js.map +1 -0
- package/dist/resources.js +31 -0
- package/dist/resources.js.map +1 -0
- package/dist/tools/info.js +29 -0
- package/dist/tools/info.js.map +1 -0
- package/dist/tools/read.js +884 -0
- package/dist/tools/read.js.map +1 -0
- package/dist/tools/trading.js +196 -0
- package/dist/tools/trading.js.map +1 -0
- package/dist/version.js +4 -0
- package/dist/version.js.map +1 -0
- package/package.json +49 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# bcs-mcp
|
|
2
|
+
|
|
3
|
+
**Твой портфель БКС Мир инвестиций — в диалоге с AI.**
|
|
4
|
+
|
|
5
|
+
MCP-сервер, который подключает Claude (Claude Code, Claude Desktop — и любой другой
|
|
6
|
+
MCP-клиент) к [BCS Trade API](https://trade-api.bcs.ru/). Смотри портфель, котировки,
|
|
7
|
+
стакан, свечи, анализируй позиции и планируй ребалансировку — обычными фразами, на русском.
|
|
8
|
+
|
|
9
|
+
Это не торговый робот и не «сигналы». Решения всегда принимаешь ты — сервер лишь
|
|
10
|
+
даёт модели безопасный доступ к данным твоего брокерского счёта.
|
|
11
|
+
|
|
12
|
+
Собран по образу и подобию [t-invest-mcp](https://github.com/human-turn/t-invest-mcp)
|
|
13
|
+
(аналогичный сервер для Т-Инвестиций) — та же модель безопасности и файловых выгрузок.
|
|
14
|
+
|
|
15
|
+
## Почему это безопасно
|
|
16
|
+
|
|
17
|
+
- **Read-only по умолчанию.** Торговые операции даже не регистрируются, пока ты их
|
|
18
|
+
явно не включишь. Достаточно токена **«только для чтения»**.
|
|
19
|
+
- **Сделки — только с твоего подтверждения.** Если включишь торговлю, перед каждой
|
|
20
|
+
заявкой сервер показывает диалог «Купить N шт. X?» — без явного «да» заявка не уйдёт.
|
|
21
|
+
- **У БКС нет песочницы** — поэтому торговый режим включай осознанно: каждая заявка реальная.
|
|
22
|
+
- Токен живёт в переменной окружения и никогда не попадает в код, логи и ответы сервера.
|
|
23
|
+
Быстрый старт ниже кладёт его в конфиг клиента — для постоянного использования держи
|
|
24
|
+
токен в системном keychain, рецепт: [docs/secure-token.md](docs/secure-token.md).
|
|
25
|
+
|
|
26
|
+
## Быстрый старт (5 минут)
|
|
27
|
+
|
|
28
|
+
Нужен Node.js ≥ 22 и брокерский счёт в БКС.
|
|
29
|
+
|
|
30
|
+
1. **Токен.** Войди в веб-версию [БКС Мир инвестиций](https://lk.bcs.ru/) →
|
|
31
|
+
«Профиль» → «Управление счетами» → нажми на брокерский счёт → «Токены API» →
|
|
32
|
+
«Выпустить токен», тип **«Только для чтения»**. Токен показывается один раз;
|
|
33
|
+
живёт 90 дней. Токен привязан ровно к одному счёту.
|
|
34
|
+
2. **Подключение к Claude Code:**
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
claude mcp add bcs \
|
|
38
|
+
-e BCS_REFRESH_TOKEN=<ваш-токен> \
|
|
39
|
+
-- node /path/to/bcs-mcp/dist/index.js
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Для Claude Desktop тот же блок добавляется в Settings → Developer → Edit Config:
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
{
|
|
46
|
+
"mcpServers": {
|
|
47
|
+
"bcs": {
|
|
48
|
+
"command": "node",
|
|
49
|
+
"args": ["/path/to/bcs-mcp/dist/index.js"],
|
|
50
|
+
"env": { "BCS_REFRESH_TOKEN": "<ваш-токен>" }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Перед этим: `npm install && npm run build` в папке проекта.
|
|
57
|
+
|
|
58
|
+
3. **Проверка:** спроси «покажи мой портфель БКС».
|
|
59
|
+
|
|
60
|
+
## Готовое из коробки: slash-команды
|
|
61
|
+
|
|
62
|
+
В Claude Code появляются как `/bcs:<имя>`:
|
|
63
|
+
|
|
64
|
+
| Команда | Что делает |
|
|
65
|
+
|---|---|
|
|
66
|
+
| `portfolio_review` | Полный обзор: структура, концентрация, риски |
|
|
67
|
+
| `rebalance_check` | Дрейф от целевых долей + план сделок в лотах (без исполнения) |
|
|
68
|
+
| `invest_cash <сумма>` | Пришла зарплата: куда докупить, чтобы приблизиться к целям |
|
|
69
|
+
| `bond_picker <сумма> <горизонт>` | Скрининг каталога облигаций: рейтинг, купон, доходность, лесенка |
|
|
70
|
+
| `fire_progress` | Прогресс к целям (FIRE) из `portfolio-target.json`: прогноз, требуемый взнос |
|
|
71
|
+
| `position_deep_dive <тикер>` | Разбор бумаги: карточка, динамика, моя позиция |
|
|
72
|
+
| `trades_review [дней]` | Мои сделки за период: обороты, средние цены, комиссии |
|
|
73
|
+
| `weekly [сумма]` | Недельный ритуал: дайджест + план докупок |
|
|
74
|
+
| `quarterly` | Обзор портфеля + проверка ребалансировки |
|
|
75
|
+
| `feedback [тема]` | Репорт о проблеме для разработчиков (без токена и личных данных) |
|
|
76
|
+
|
|
77
|
+
Все команды **анализируют и предлагают** — ни одна не совершает сделок сама.
|
|
78
|
+
Целевые доли для ребалансировки задаются файлом `portfolio-target.json` в корне проекта
|
|
79
|
+
(эталон — MCP-ресурс `bcs://portfolio-target/example`, формат совместим с t-invest-mcp).
|
|
80
|
+
|
|
81
|
+
Дивиденды и купоны BCS Trade API не отдаёт — рядом можно подключить публичный
|
|
82
|
+
[moex-mcp](https://github.com/cyberash-dev/moex-mcp) (MOEX ISS): команды это учитывают.
|
|
83
|
+
|
|
84
|
+
## Переменные окружения
|
|
85
|
+
|
|
86
|
+
| Переменная | Значение | Описание |
|
|
87
|
+
|---|---|---|
|
|
88
|
+
| `BCS_REFRESH_TOKEN` | обязательна | Refresh-токен из ЛК БКС (90 дней, привязан к счёту) |
|
|
89
|
+
| `BCS_ALLOW_TRADING` | `true`/`false` | Регистрирует place/edit/cancel_order. Нужен токен «для торговли и чтения». РЕАЛЬНЫЕ деньги! |
|
|
90
|
+
| `BCS_CONFIRM` | `off` | Отключает elicitation-подтверждение сделок (по умолчанию включено; выключать не рекомендуется — песочницы нет) |
|
|
91
|
+
| `BCS_OUTPUT_DIR` | путь | Корень для файловых выгрузок `outputPath` (по умолчанию — cwd сервера) |
|
|
92
|
+
|
|
93
|
+
## Tools
|
|
94
|
+
|
|
95
|
+
Read-only (всегда):
|
|
96
|
+
|
|
97
|
+
| Tool | Описание |
|
|
98
|
+
|---|---|
|
|
99
|
+
| `get_portfolio` | Портфель: позиции с P&L, долями, стоимостью в RUB/USD/EUR; итоги по классам (срез `term`, по умолчанию T0) |
|
|
100
|
+
| `get_limits` | Денежные и депо-лимиты: свободные средства по валютам (`free` = quantity − locked; снимок на начало дня) |
|
|
101
|
+
| `get_quotes` | Котировки (батч): bid/offer, last, open/high/low, изменение за день |
|
|
102
|
+
| `get_order_book` | Стакан L2 (глубина 20) |
|
|
103
|
+
| `get_recent_trades` | Лента обезличенных сделок: новейшие `limit` (расширяемое окно), период `from`/`to`; полный период в файл — через `outputPath` |
|
|
104
|
+
| `get_candles` | Свечи OHLCV (M1…MN); с `outputPath` — весь период чанками |
|
|
105
|
+
| `find_instrument` | Карточки по тикерам/ISIN: лот, classCode, купоны, дивдоходность, рейтинги (одна карточка на бумагу; `allBoards` — все площадки) |
|
|
106
|
+
| `get_instruments_by_type` | Каталог инструментов типа (акции/облигации/ETF/фьючерсы…), пагинация |
|
|
107
|
+
| `get_trading_schedule` | Сессии инструмента на сегодня (МСК, отсортированы) |
|
|
108
|
+
| `get_trading_status` | Открыт/закрыт инструмент сейчас + кросс-чек с расписанием (`warning` при расхождении) |
|
|
109
|
+
| `get_discounts` | Маржинальные дисконты (long/short) |
|
|
110
|
+
| `get_orders` | Список заявок (данные с 26.01.2026) |
|
|
111
|
+
| `get_order_status` | Статус заявки по UUID или биржевому номеру |
|
|
112
|
+
| `get_trades` | Мои исполненные сделки (данные с 26.01.2026) |
|
|
113
|
+
| `get_server_info` | Диагностика сервера (для фидбэка) |
|
|
114
|
+
|
|
115
|
+
Торговые (`BCS_ALLOW_TRADING=true`): `place_order`, `edit_order`, `cancel_order`.
|
|
116
|
+
**Важно:** количество в заявках — в штуках, не в лотах (лот — `lotSize` из `find_instrument`).
|
|
117
|
+
|
|
118
|
+
### Выгрузка в файл
|
|
119
|
+
|
|
120
|
+
Каждый read-tool принимает `outputPath` (путь относительно `BCS_OUTPUT_DIR`) и
|
|
121
|
+
`outputFormat` (`json`/`csv`). Сервер пишет результат на диск, в диалог возвращает
|
|
122
|
+
summary. Для `get_candles` и `get_instruments_by_type` это включает выкачивание
|
|
123
|
+
полного периода/каталога чанками. Запись возможна строго внутри корня выгрузок.
|
|
124
|
+
|
|
125
|
+
## Ограничения BCS Trade API
|
|
126
|
+
|
|
127
|
+
- Нет истории денежных операций (полученные дивиденды, комиссии, пополнения) —
|
|
128
|
+
только биржевые сделки. XIRR и налоговые отчёты поэтому невозможны.
|
|
129
|
+
- Нет песочницы.
|
|
130
|
+
- Один токен = один счёт (несколько счетов — несколько инстансов сервера).
|
|
131
|
+
- Списки заявок/сделок — только с 26.01.2026.
|
|
132
|
+
|
|
133
|
+
## Disclaimer
|
|
134
|
+
|
|
135
|
+
Не является индивидуальной инвестиционной рекомендацией. Все торговые решения вы
|
|
136
|
+
принимаете самостоятельно. `place_order` оперирует реальными деньгами — используйте
|
|
137
|
+
`BCS_ALLOW_TRADING=true` осознанно и держите подтверждение сделок включённым.
|
|
138
|
+
|
|
139
|
+
## License
|
|
140
|
+
|
|
141
|
+
Apache 2.0
|
package/dist/catalog.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { API } from "./endpoints.js";
|
|
2
|
+
import { bcsFetch } from "./client.js";
|
|
3
|
+
import { pickList } from "./helpers.js";
|
|
4
|
+
/** Lazy ticker catalog for prompt-argument completions (stocks + bonds + ETFs, 24h TTL) */
|
|
5
|
+
const TTL_MS = 24 * 60 * 60 * 1000;
|
|
6
|
+
/** After a failed load, don't hammer the rate-limited API on every completion keystroke */
|
|
7
|
+
const FAIL_COOLDOWN_MS = 60_000;
|
|
8
|
+
const PAGE_SIZE = 100;
|
|
9
|
+
const MAX_PAGES = 100; // backstop: 10k tickers per type is plenty for completion
|
|
10
|
+
// Same idiom as instruments-cache: one state object + shared in-flight promise
|
|
11
|
+
let loaded = null;
|
|
12
|
+
let loading = null;
|
|
13
|
+
let lastFailAt = 0;
|
|
14
|
+
async function byType(type) {
|
|
15
|
+
const all = [];
|
|
16
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
17
|
+
const items = pickList(await bcsFetch(API.information, "/instruments/by-type", {
|
|
18
|
+
query: { type, page: String(page), size: String(PAGE_SIZE) },
|
|
19
|
+
}), "instruments");
|
|
20
|
+
all.push(...items);
|
|
21
|
+
if (items.length < PAGE_SIZE)
|
|
22
|
+
break;
|
|
23
|
+
}
|
|
24
|
+
return all;
|
|
25
|
+
}
|
|
26
|
+
async function load() {
|
|
27
|
+
const [stocks, bonds, etfs] = await Promise.all([byType("STOCK"), byType("BONDS"), byType("ETF")]);
|
|
28
|
+
const set = new Set();
|
|
29
|
+
for (const list of [stocks, bonds, etfs]) {
|
|
30
|
+
for (const i of list)
|
|
31
|
+
if (i.ticker)
|
|
32
|
+
set.add(i.ticker.toUpperCase());
|
|
33
|
+
}
|
|
34
|
+
return [...set].sort();
|
|
35
|
+
}
|
|
36
|
+
export async function completeTicker(prefix) {
|
|
37
|
+
try {
|
|
38
|
+
const fresh = loaded !== null && Date.now() - loaded.at < TTL_MS;
|
|
39
|
+
const coolingDown = Date.now() - lastFailAt < FAIL_COOLDOWN_MS;
|
|
40
|
+
if (!fresh && !coolingDown) {
|
|
41
|
+
loading ??= load()
|
|
42
|
+
.then((t) => {
|
|
43
|
+
loaded = { tickers: t, at: Date.now() };
|
|
44
|
+
return t;
|
|
45
|
+
})
|
|
46
|
+
.catch((e) => {
|
|
47
|
+
lastFailAt = Date.now();
|
|
48
|
+
throw e;
|
|
49
|
+
})
|
|
50
|
+
.finally(() => {
|
|
51
|
+
loading = null;
|
|
52
|
+
});
|
|
53
|
+
await loading;
|
|
54
|
+
}
|
|
55
|
+
const p = prefix.toUpperCase();
|
|
56
|
+
// stale data beats no data: on refresh failure the previous catalog keeps serving
|
|
57
|
+
return (loaded?.tickers ?? []).filter((t) => t.startsWith(p)).slice(0, 100);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return (loaded?.tickers ?? []).filter((t) => t.startsWith(prefix.toUpperCase())).slice(0, 100);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=catalog.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,M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AI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IAC9E,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,CAAC,MAAM,EAAE,OAAO,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACjG,CAAC;AACH,CAAC"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
2
|
+
import { AUTH_URL } from "./endpoints.js";
|
|
3
|
+
export const config = {
|
|
4
|
+
refreshToken: process.env.BCS_REFRESH_TOKEN ?? "",
|
|
5
|
+
allowTrading: process.env.BCS_ALLOW_TRADING === "true",
|
|
6
|
+
/** Human confirmation (MCP elicitation) before each trade; opt out with BCS_CONFIRM=off */
|
|
7
|
+
confirm: process.env.BCS_CONFIRM !== "off",
|
|
8
|
+
};
|
|
9
|
+
/** Refresh access tokens a minute before their 24h expiry */
|
|
10
|
+
const EXPIRY_MARGIN_MS = 60_000;
|
|
11
|
+
const RATE_LIMIT_RETRIES = 2;
|
|
12
|
+
const RATE_LIMIT_BACKOFF_MS = 5_000;
|
|
13
|
+
/** Hard cap per HTTP attempt — a hung connection must not hang the MCP tool call */
|
|
14
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
15
|
+
export class BcsApiError extends Error {
|
|
16
|
+
status;
|
|
17
|
+
body;
|
|
18
|
+
kind;
|
|
19
|
+
constructor(message, status, body, kind = "api") {
|
|
20
|
+
super(message);
|
|
21
|
+
this.status = status;
|
|
22
|
+
this.body = body;
|
|
23
|
+
this.kind = kind;
|
|
24
|
+
this.name = "BcsApiError";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Keycloak token manager: exchanges the refresh token for a 24h access token,
|
|
29
|
+
* caches it, and keeps the rotated refresh token in memory (the env value stays
|
|
30
|
+
* valid until its own 90-day expiry, but the freshest one is preferred).
|
|
31
|
+
* The in-flight promise is cached so concurrent calls share one auth request.
|
|
32
|
+
*/
|
|
33
|
+
class TokenManager {
|
|
34
|
+
refreshToken = config.refreshToken;
|
|
35
|
+
accessToken = null;
|
|
36
|
+
expiresAt = 0;
|
|
37
|
+
inFlight = null;
|
|
38
|
+
/**
|
|
39
|
+
* `staleToken` marks the token that just got a 401: refresh happens only if the
|
|
40
|
+
* cache still holds that exact token — if a concurrent call already refreshed,
|
|
41
|
+
* the fresh cached token is returned without another Keycloak round-trip.
|
|
42
|
+
*/
|
|
43
|
+
async getAccessToken(staleToken) {
|
|
44
|
+
const cachedValid = this.accessToken !== null && Date.now() < this.expiresAt;
|
|
45
|
+
if (cachedValid && this.accessToken !== staleToken)
|
|
46
|
+
return this.accessToken;
|
|
47
|
+
this.inFlight ??= this.fetchAccessToken().finally(() => {
|
|
48
|
+
this.inFlight = null;
|
|
49
|
+
});
|
|
50
|
+
return this.inFlight;
|
|
51
|
+
}
|
|
52
|
+
/** Diagnostics for get_server_info — never exposes token values */
|
|
53
|
+
status() {
|
|
54
|
+
const valid = this.accessToken !== null && Date.now() < this.expiresAt;
|
|
55
|
+
return {
|
|
56
|
+
accessTokenCached: valid,
|
|
57
|
+
accessExpiresInMinutes: valid ? Math.round((this.expiresAt - Date.now()) / 60_000) : null,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
async fetchAccessToken() {
|
|
61
|
+
if (!this.refreshToken)
|
|
62
|
+
throw new Error("BCS_REFRESH_TOKEN is not set");
|
|
63
|
+
const clientId = config.allowTrading ? "trade-api-write" : "trade-api-read";
|
|
64
|
+
const body = new URLSearchParams({
|
|
65
|
+
client_id: clientId,
|
|
66
|
+
grant_type: "refresh_token",
|
|
67
|
+
refresh_token: this.refreshToken,
|
|
68
|
+
});
|
|
69
|
+
const res = await fetch(AUTH_URL, {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
72
|
+
body,
|
|
73
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
74
|
+
});
|
|
75
|
+
if (!res.ok) {
|
|
76
|
+
// Plain Error (not BcsApiError): HTTP hints for API endpoints don't apply to auth failures.
|
|
77
|
+
// Never include tokens in the error text.
|
|
78
|
+
throw new Error(`Auth failed: HTTP ${res.status} — check that BCS_REFRESH_TOKEN is valid, not expired (90 days) ` +
|
|
79
|
+
`and matches the mode (a read-only token cannot authenticate as trade-api-write)`);
|
|
80
|
+
}
|
|
81
|
+
const data = (await res.json());
|
|
82
|
+
this.accessToken = data.access_token;
|
|
83
|
+
this.expiresAt = Date.now() + data.expires_in * 1000 - EXPIRY_MARGIN_MS;
|
|
84
|
+
if (data.refresh_token)
|
|
85
|
+
this.refreshToken = data.refresh_token; // Keycloak rotates it
|
|
86
|
+
return this.accessToken;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const tokens = new TokenManager();
|
|
90
|
+
/** Token diagnostics (no secret values) for get_server_info */
|
|
91
|
+
export const tokenStatus = () => tokens.status();
|
|
92
|
+
function classifyError(status, body) {
|
|
93
|
+
const trimmed = body.trim();
|
|
94
|
+
if (trimmed.startsWith("<"))
|
|
95
|
+
return { kind: "no-route", detail: "" }; // gateway HTML — route does not exist
|
|
96
|
+
try {
|
|
97
|
+
const parsed = JSON.parse(trimmed);
|
|
98
|
+
if (parsed.displayOptions?.text)
|
|
99
|
+
return { kind: "no-data", detail: parsed.displayOptions.text };
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// not JSON — fall through
|
|
103
|
+
}
|
|
104
|
+
return { kind: "api", detail: trimmed.slice(0, 500) };
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Authenticated request to the BCS Trade API.
|
|
108
|
+
* `base` is a service root from endpoints.ts, `path` starts with "/".
|
|
109
|
+
* Retries once with a token refresh on 401 (only if no one refreshed meanwhile)
|
|
110
|
+
* and up to RATE_LIMIT_RETRIES times with a growing backoff on 429
|
|
111
|
+
* (unless retry429 is false). Every attempt is capped by REQUEST_TIMEOUT_MS.
|
|
112
|
+
*/
|
|
113
|
+
export async function bcsFetch(base, path, opts = {}) {
|
|
114
|
+
const url = new URL(base + path);
|
|
115
|
+
for (const [k, v] of Object.entries(opts.query ?? {})) {
|
|
116
|
+
if (v === undefined)
|
|
117
|
+
continue;
|
|
118
|
+
for (const item of Array.isArray(v) ? v : [v])
|
|
119
|
+
url.searchParams.append(k, item);
|
|
120
|
+
}
|
|
121
|
+
const method = opts.method ?? "GET";
|
|
122
|
+
let retried401 = false;
|
|
123
|
+
let rateRetries = 0;
|
|
124
|
+
let staleToken;
|
|
125
|
+
for (;;) {
|
|
126
|
+
const token = await tokens.getAccessToken(staleToken);
|
|
127
|
+
staleToken = undefined;
|
|
128
|
+
let res;
|
|
129
|
+
try {
|
|
130
|
+
res = await fetch(url, {
|
|
131
|
+
method,
|
|
132
|
+
headers: {
|
|
133
|
+
Authorization: `Bearer ${token}`,
|
|
134
|
+
...(opts.body != null ? { "Content-Type": "application/json" } : {}),
|
|
135
|
+
},
|
|
136
|
+
body: opts.body != null ? JSON.stringify(opts.body) : undefined,
|
|
137
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
catch (e) {
|
|
141
|
+
if (e.name === "TimeoutError" || e.name === "AbortError") {
|
|
142
|
+
throw new Error(`Request timeout after ${REQUEST_TIMEOUT_MS / 1000}s: ${method} ${url.pathname}`);
|
|
143
|
+
}
|
|
144
|
+
throw e;
|
|
145
|
+
}
|
|
146
|
+
if (res.status === 401 && !retried401) {
|
|
147
|
+
retried401 = true;
|
|
148
|
+
staleToken = token; // refresh only if nobody refreshed the cache meanwhile
|
|
149
|
+
res.body?.cancel().catch(() => { });
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (!res.ok) {
|
|
153
|
+
const body = await res.text().catch(() => "");
|
|
154
|
+
// 429 with "message exceeds maximum size" is the backend's ~4 MB cap leaking through —
|
|
155
|
+
// the feed only grows during the day, so backoff-and-retry cannot succeed
|
|
156
|
+
const tooLarge = res.status === 429 && /exceeds maximum size/i.test(body);
|
|
157
|
+
if (res.status === 429 && !tooLarge && rateRetries < RATE_LIMIT_RETRIES && opts.retry429 !== false) {
|
|
158
|
+
rateRetries++;
|
|
159
|
+
await sleep(RATE_LIMIT_BACKOFF_MS * rateRetries);
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const { kind, detail } = classifyError(res.status, body);
|
|
163
|
+
throw new BcsApiError(`HTTP ${res.status} ${method} ${url.pathname}${detail ? ` — ${detail}` : ""}`, res.status, detail, tooLarge ? "too-large" : kind);
|
|
164
|
+
}
|
|
165
|
+
if (res.status === 204)
|
|
166
|
+
return undefined;
|
|
167
|
+
// Some mutation endpoints answer 200 with an empty body — that is still success
|
|
168
|
+
const text = await res.text();
|
|
169
|
+
if (!text.trim())
|
|
170
|
+
return undefined;
|
|
171
|
+
try {
|
|
172
|
+
return JSON.parse(text);
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
throw new Error(`Unexpected non-JSON response (HTTP ${res.status}, ${method} ${url.pathname}): ${text.slice(0, 200)}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAA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AG,aAAa,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YACzD,MAAM,IAAI,WAAW,CACnB,QAAQ,GAAG,CAAC,MAAM,IAAI,MAAM,IAAI,GAAG,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAC7E,GAAG,CAAC,MAAM,EACV,MAAM,EACN,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAC9B,CAAC;QACJ,CAAC;QACD,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG;YAAE,OAAO,SAAc,CAAC;QAC9C,gFAAgF;QAChF,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;YAAE,OAAO,SAAc,CAAC;QACxC,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAM,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,KAAK,CACb,sCAAsC,GAAG,CAAC,MAAM,KAAK,MAAM,IAAI,GAAG,CAAC,QAAQ,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CACtG,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BCS Trade API service base URLs.
|
|
3
|
+
* The PDF manual is partially outdated — paths here are verified against the
|
|
4
|
+
* live API and https://trade-api.bcs.ru (see also bcs-trade-go as a reference).
|
|
5
|
+
*/
|
|
6
|
+
export const AUTH_URL = "https://be.broker.ru/trade-api-keycloak/realms/tradeapi/protocol/openid-connect/token";
|
|
7
|
+
const BASE = "https://be.broker.ru";
|
|
8
|
+
export const API = {
|
|
9
|
+
portfolio: `${BASE}/trade-api-bff-portfolio/api/v1`,
|
|
10
|
+
limits: `${BASE}/trade-api-bff-limit/api/v1`,
|
|
11
|
+
operations: `${BASE}/trade-api-bff-operations/api/v1`,
|
|
12
|
+
orderDetails: `${BASE}/trade-api-bff-order-details/api/v1`,
|
|
13
|
+
tradeDetails: `${BASE}/trade-api-bff-trade-details/api/v1`,
|
|
14
|
+
information: `${BASE}/trade-api-information-service/api/v1`,
|
|
15
|
+
marketData: `${BASE}/trade-api-market-data-connector/api/v1`,
|
|
16
|
+
marginal: `${BASE}/trade-api-bff-marginal-indicators/api/v1`,
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=endpoints.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endpoints.js","sourceRoot":"","sources":["../src/endpoints.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,QAAQ,GACnB,uFAAuF,CAAC;AAE1F,MAAM,IAAI,GAAG,sBAAsB,CAAC;AAEpC,MAAM,CAAC,MAAM,GAAG,GAAG;IACjB,SAAS,EAAE,GAAG,IAAI,iCAAiC;IACnD,MAAM,EAAE,GAAG,IAAI,6BAA6B;IAC5C,UAAU,EAAE,GAAG,IAAI,kCAAkC;IACrD,YAAY,EAAE,GAAG,IAAI,qCAAqC;IAC1D,YAAY,EAAE,GAAG,IAAI,qCAAqC;IAC1D,WAAW,EAAE,GAAG,IAAI,uCAAuC;IAC3D,UAAU,EAAE,GAAG,IAAI,yCAAyC;IAC5D,QAAQ,EAAE,GAAG,IAAI,2CAA2C;CACpD,CAAC"}
|