dsh-desktop-kit 2.9.0 → 2.10.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.
- package/CHANGELOG.md +7 -0
- package/README.md +18 -18
- package/client.js +8 -3
- package/docs/TEST-2.10.0.md +28 -0
- package/package.json +2 -2
- package/plugins/dsh-mcp-manager/README.md +29 -2
- package/plugins/dsh-mcp-manager/client.js +7 -2
- package/plugins/dsh-mcp-manager/lib/api.js +2 -1
- package/plugins/dsh-mcp-manager/lib/client.js +3 -1
- package/plugins/dsh-mcp-manager/lib/config.js +1 -0
- package/plugins/dsh-mcp-manager/lib/manager.js +21 -15
- package/plugins/dsh-mcp-manager/lib/sampling.js +103 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.10.0 (2026-11-12)
|
|
4
|
+
|
|
5
|
+
- **MCP sampling.** Opt-in `sampling: true`; серверный `sampling/createMessage` идёт через DSH approval-карточку с preview, затем в модель текущей сессии.
|
|
6
|
+
- **Безопасность.** Tools в sampling запрещены, лимит 1024 токена, approval fail-closed, сервер без opt-in получает `-32601`.
|
|
7
|
+
- **UI.** Галочка sampling в форме сервера и понятное предупреждение о рисках.
|
|
8
|
+
- **Тесты.** `mcp-sampling-tests`: allow/reject/disabled/tools, лимит токенов, preview.
|
|
9
|
+
|
|
3
10
|
## 2.9.0 (2026-11-12)
|
|
4
11
|
|
|
5
12
|
- **Project instructions.** `AGENTS.md` и `CLAUDE.md` читаются иерархически: root → вложенные папки до cwd → `.dsh/AGENTS.md`; поддержан `@import`, лимиты глубины/размера/файлов, защита от выхода за проект и symlink-escape.
|
package/README.md
CHANGED
|
@@ -4,17 +4,17 @@
|
|
|
4
4
|
|
|
5
5
|
Набор из **16 плагинов и 30 навыков** для DeepSeek Harness 0.2.x: русский интерфейс, автопилот навыков, токен-лаборатория, студия навыков, память проектов, обмен памятью между машинами (GitHub и USB), guardrails, карта репозитория, чекпоинты, plan mode, browser QA, GitHub review, Claude Code-подобные hooks/agents/commands, перенос чатов и резервные копии профиля.
|
|
6
6
|
|
|
7
|
-

|
|
8
8
|
|
|
9
9
|
## MCP: подключения без JSON
|
|
10
10
|
|
|
11
|
-
Настройки → **MCP**: пресеты GitHub, PostgreSQL и Filesystem, живые статусы, health, список tools и безопасное хранение токенов в `~/.dsh/mcp.secrets.json`. Промпты сервера открываются кнопкой **Prompts**: аргументы, запуск и копирование результата. HTTP-серверы подключаются через **OAuth 2.1 + PKCE
|
|
11
|
+
Настройки → **MCP**: пресеты GitHub, PostgreSQL и Filesystem, живые статусы, health, список tools и безопасное хранение токенов в `~/.dsh/mcp.secrets.json`. Промпты сервера открываются кнопкой **Prompts**: аргументы, запуск и копирование результата. HTTP-серверы подключаются через **OAuth 2.1 + PKCE**, а **sampling** включается отдельно и проходит через approval-карточку DSH.
|
|
12
12
|
|
|
13
|
-

|
|
14
14
|
|
|
15
|
-

|
|
16
16
|
|
|
17
|
-

|
|
18
18
|
|
|
19
19
|
## Права и субагенты
|
|
20
20
|
|
|
@@ -25,11 +25,11 @@
|
|
|
25
25
|
- **Worktrees и фоновые агенты.** `project_worktree` создаёт ветку `dsh/<slug>` и отдельную папку `.dsh/worktrees/<slug>`; `project_agent ... worktree=auto background=true` запускает агента в изоляции, а страница **Агенты** показывает worktrees и очередь запусков с кнопкой «Остановить».
|
|
26
26
|
- **Инструкции проекта.** `AGENTS.md` и `CLAUDE.md` читаются иерархически (root → вложенные папки → `.dsh`) с `@import`; MCP roots сообщает серверу корень проекта.
|
|
27
27
|
|
|
28
|
-

|
|
29
29
|
|
|
30
|
-

|
|
31
31
|
|
|
32
|
-
**v2.
|
|
32
|
+
**v2.10.0** · MIT · проверено на DSH `0.2.1-rc.5` и `0.2.2-rc.1` (Windows 11) · без внешних зависимостей и телеметрии
|
|
33
33
|
|
|
34
34
|
**План развития:** [docs/ROADMAP-3.0.md](docs/ROADMAP-3.0.md) — Memory Fabric, семантическое
|
|
35
35
|
слияние, локальный индекс памяти, шифрованные переносы, Memory Hub и npm trusted publishing.
|
|
@@ -117,27 +117,27 @@
|
|
|
117
117
|
- перед каждой синхронизацией проверяется, что репозиторий всё ещё приватный;
|
|
118
118
|
- секреты и PII вычищаются, домашние пути заменяются токеном `%DSH_HOME%`; LLM не вызывается — **0 токенов**.
|
|
119
119
|
|
|
120
|
-

|
|
121
121
|
|
|
122
|
-

|
|
123
123
|
|
|
124
124
|
## Скриншоты
|
|
125
125
|
|
|
126
126
|
### Skills Studio: каталог, стоимость и редактор
|
|
127
127
|
|
|
128
|
-

|
|
129
129
|
|
|
130
|
-

|
|
131
131
|
|
|
132
132
|
### Token Lab: куда уходит контекст
|
|
133
133
|
|
|
134
|
-

|
|
135
135
|
|
|
136
136
|
### Тёмная тема и мобильный
|
|
137
137
|
|
|
138
|
-

|
|
139
139
|
|
|
140
|
-

|
|
141
141
|
|
|
142
142
|
## Окно-напоминание: пиковый тариф
|
|
143
143
|
|
|
@@ -147,11 +147,11 @@ DeepSeek включает двойной тариф в пиковые часы (
|
|
|
147
147
|
- **в окне** — красная карточка: причина, границы окна в местном времени и UTC, живой отсчёт до конца и рекомендация, когда вернуться;
|
|
148
148
|
- **после окна** — карточка исчезает; состояние всегда доступно через `window.__DSH_PEAK_GUARD__.state()`.
|
|
149
149
|
|
|
150
|
-

|
|
151
151
|
|
|
152
|
-

|
|
153
153
|
|
|
154
|
-

|
|
155
155
|
|
|
156
156
|
Подробности и настройки — [plugins/dsh-peak-guard/README.md](plugins/dsh-peak-guard/README.md).
|
|
157
157
|
|
package/client.js
CHANGED
|
@@ -6947,7 +6947,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
6947
6947
|
.mcp-note{color:var(--mcp-muted);font-size:11px;line-height:1.45;margin:0}
|
|
6948
6948
|
.mcp-loading{color:var(--mcp-muted);font-size:13px;padding:18px 0}
|
|
6949
6949
|
.mcp-overlay{position:fixed;inset:0;background:rgba(10,20,18,.42);backdrop-filter:blur(4px);z-index:80;display:flex;align-items:center;justify-content:center;padding:20px}
|
|
6950
|
-
.mcp-modal{width:min(640px,100%);max-height:min(86vh,820px);overflow:auto;background:var(--mcp-panel);border:1px solid var(--mcp-line);border-radius:20px;box-shadow:0 24px 80px rgba(10,20,18,.24);padding:22px;display:flex;flex-direction:column;gap:16px}
|
|
6950
|
+
.mcp-modal{box-sizing:border-box;width:min(640px,100%);max-height:min(86vh,820px);overflow:auto;background:var(--mcp-panel);border:1px solid var(--mcp-line);border-radius:20px;box-shadow:0 24px 80px rgba(10,20,18,.24);padding:22px;display:flex;flex-direction:column;gap:16px}
|
|
6951
6951
|
.mcp-modal-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
|
|
6952
6952
|
.mcp-modal h2{margin:0;font-size:20px;letter-spacing:-.02em}
|
|
6953
6953
|
.mcp-modal p{margin:4px 0 0;color:var(--mcp-muted);font-size:13px;line-height:1.45}
|
|
@@ -7145,6 +7145,10 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
7145
7145
|
h("input", { type: "checkbox", checked: form.trusted, onChange: (event) => set({ trusted: event.target.checked }) }),
|
|
7146
7146
|
h("span", null, "Я доверяю этому серверу. Он сможет выполнять команды и читать данные, к которым у него есть доступ."),
|
|
7147
7147
|
),
|
|
7148
|
+
h("label", { className: "mcp-check wide" },
|
|
7149
|
+
h("input", { type: "checkbox", checked: form.sampling === true, onChange: (event) => set({ sampling: event.target.checked }) }),
|
|
7150
|
+
h("span", null, "Разрешить sampling: сервер сможет попросить модель сгенерировать текст. Каждый запрос показывает approval-карточку, tools запрещены, лимит 1024 токена."),
|
|
7151
|
+
),
|
|
7148
7152
|
),
|
|
7149
7153
|
h("p", { className: "mcp-note" }, "Секрет сохраняется в ~/.dsh/mcp.secrets.json с правами 0600 и не попадает в mcp.json или лог."),
|
|
7150
7154
|
h("div", { className: "mcp-form-actions" },
|
|
@@ -7308,8 +7312,9 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
7308
7312
|
tokenPlaceholder: preset.tokenPlaceholder || "",
|
|
7309
7313
|
token: "",
|
|
7310
7314
|
trusted: preset.trusted === true,
|
|
7315
|
+
sampling: false,
|
|
7311
7316
|
});
|
|
7312
|
-
const openManual = () => setForm({ edit: false, id: "", transport: "stdio", command: "npx", args: "-y\n", url: "", tokenEnv: "MCP_TOKEN", tokenHeader: "Authorization", tokenLabel: "Токен", tokenPlaceholder: "", token: "", trusted: false });
|
|
7317
|
+
const openManual = () => setForm({ edit: false, id: "", transport: "stdio", command: "npx", args: "-y\n", url: "", tokenEnv: "MCP_TOKEN", tokenHeader: "Authorization", tokenLabel: "Токен", tokenPlaceholder: "", token: "", trusted: false, sampling: false });
|
|
7313
7318
|
|
|
7314
7319
|
const servers = data?.servers ?? [];
|
|
7315
7320
|
const connected = servers.filter((server) => server.connected).length;
|
|
@@ -7870,7 +7875,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
|
|
|
7870
7875
|
if (__kitErrors.length <= 5) console.error("[dsh-desktop-kit] registration failed:", label, message);
|
|
7871
7876
|
};
|
|
7872
7877
|
try {
|
|
7873
|
-
window.__DSH_DESKTOP_KIT__ = { version: "2.
|
|
7878
|
+
window.__DSH_DESKTOP_KIT__ = { version: "2.10.0", parts: __partNames, errors: __kitErrors, ready: false };
|
|
7874
7879
|
} catch {}
|
|
7875
7880
|
const __inject = [];
|
|
7876
7881
|
for (const __part of __parts) {
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# DSH Desktop Kit 2.10.0 — тест
|
|
2
|
+
|
|
3
|
+
Дата: 2026-11-12.
|
|
4
|
+
|
|
5
|
+
## MCP sampling
|
|
6
|
+
|
|
7
|
+
- Per-server `sampling: true` (по умолчанию false).
|
|
8
|
+
- `sampling/createMessage` → `ctx.approval.request` → `ctx.llm.stream`.
|
|
9
|
+
- Approval fail-closed; rejected/unavailable возвращают JSON-RPC error.
|
|
10
|
+
- Tools в sampling запрещены.
|
|
11
|
+
- maxTokens clamp 1..1024.
|
|
12
|
+
- Модель — текущая сессия, fallback на agentDefaultModel.
|
|
13
|
+
- Prompt preview в displayReason (EN/RU).
|
|
14
|
+
|
|
15
|
+
## UI
|
|
16
|
+
|
|
17
|
+
- Галочка sampling в форме сервера.
|
|
18
|
+
- Предупреждение: каждый запрос — approval, tools запрещены, 1024 токена.
|
|
19
|
+
|
|
20
|
+
## Тесты
|
|
21
|
+
|
|
22
|
+
- `tools/mcp-sampling-tests.mjs` — allow, reject, disabled, tools, cap, preview.
|
|
23
|
+
- `npm test` — exit 0.
|
|
24
|
+
- `build:client` / `check:client` — OK.
|
|
25
|
+
|
|
26
|
+
## Ограничение
|
|
27
|
+
|
|
28
|
+
Prompt preview не редактируется в approval-карточке; elicitation не реализован.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-desktop-kit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.10.0",
|
|
4
4
|
"description": "DeepSeek Harness desktop kit 2.7: 16 plugins and 30 skills — self-applying skills, token lab, Skills Studio, project memory, GitHub and USB memory transfer, guardrails, repo map, checkpoints, plan mode, browser QA, GitHub review, Claude Code-like hooks/agents/commands, Russian UI, peak guard, chat move and profile transfer.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"deepseek-harness",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"build:client": "node tools/build-client.mjs",
|
|
75
75
|
"build:skills": "node tools/build-skill-manifest.mjs",
|
|
76
76
|
"check:client": "node tools/check-client.mjs client.js",
|
|
77
|
-
"test": "node tools/smoke-tests.mjs && node tools/memory-tests.mjs && node tools/skills-sync-tests.mjs && node tools/kit-upgrade-tests.mjs && node plugins/dsh-profile-transfer/test/transfer.test.mjs && node --test plugins/dsh-memory-bridge/test/bridge.test.mjs plugins/dsh-memory-bridge/test/github.test.mjs plugins/dsh-memory-bridge/test/merge.test.mjs plugins/dsh-memory-bridge/test/user-specific.test.mjs && node tools/repo-map-tests.mjs && node tools/checkpoints-tests.mjs && node tools/plan-mode-tests.mjs && node tools/browser-qa-tests.mjs && node tools/ui-gate-tests.mjs && node tools/agent-extensions-tests.mjs && node tools/mcp-manager-tests.mjs && node tools/github-review-tests.mjs && node tools/instructions-tests.mjs && node tools/mcp-oauth-tests.mjs && node tools/worktrees-tests.mjs && node tools/background-agents-tests.mjs && node tools/permissions-ui-tests.mjs && node plugins/dsh-guardrails/tools/guardrails-tests.mjs",
|
|
77
|
+
"test": "node tools/smoke-tests.mjs && node tools/memory-tests.mjs && node tools/skills-sync-tests.mjs && node tools/kit-upgrade-tests.mjs && node plugins/dsh-profile-transfer/test/transfer.test.mjs && node --test plugins/dsh-memory-bridge/test/bridge.test.mjs plugins/dsh-memory-bridge/test/github.test.mjs plugins/dsh-memory-bridge/test/merge.test.mjs plugins/dsh-memory-bridge/test/user-specific.test.mjs && node tools/repo-map-tests.mjs && node tools/checkpoints-tests.mjs && node tools/plan-mode-tests.mjs && node tools/browser-qa-tests.mjs && node tools/ui-gate-tests.mjs && node tools/agent-extensions-tests.mjs && node tools/mcp-manager-tests.mjs && node tools/github-review-tests.mjs && node tools/instructions-tests.mjs && node tools/mcp-sampling-tests.mjs && node tools/mcp-oauth-tests.mjs && node tools/worktrees-tests.mjs && node tools/background-agents-tests.mjs && node tools/permissions-ui-tests.mjs && node plugins/dsh-guardrails/tools/guardrails-tests.mjs",
|
|
78
78
|
"skills:cost": "node tools/skill-cost.mjs",
|
|
79
79
|
"skills:check": "node tools/skill-cost.mjs --check",
|
|
80
80
|
"release": "node tools/release.mjs"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# dsh-mcp-manager
|
|
2
2
|
|
|
3
|
-
MCP-серверы для DSH без SDK-зависимости: stdio и streamable HTTP, tools, resources, prompts, **OAuth 2.1**, trust-гейт и премиальный экран в Settings.
|
|
3
|
+
MCP-серверы для DSH без SDK-зависимости: stdio и streamable HTTP, tools, resources, prompts, **OAuth 2.1**, **sampling**, trust-гейт и премиальный экран в Settings.
|
|
4
4
|
|
|
5
5
|

|
|
6
6
|
|
|
@@ -14,6 +14,7 @@ MCP-серверы для DSH без SDK-зависимости: stdio и stream
|
|
|
14
14
|
- «Tools» — список инструментов с описаниями;
|
|
15
15
|
- «Prompts» — промпты сервера: аргументы, запуск и копирование результата;
|
|
16
16
|
- **«Войти» / «OAuth»** у HTTP-сервера — authorization code + PKCE в браузере; токен хранится в `~/.dsh/mcp.oauth.json` (0600) и не попадает в `mcp.json`;
|
|
17
|
+
- **Sampling** — отдельный opt-in: сервер может попросить модель, но каждый запрос идёт через approval-карточку DSH;
|
|
17
18
|
- «Добавить сервер» — пресеты GitHub / PostgreSQL / Filesystem или ручная форма;
|
|
18
19
|
- токен сохраняется в `~/.dsh/mcp.secrets.json` (0600), а в `mcp.json` остаётся только `${secret:…}`;
|
|
19
20
|
- новые tools появляются в **новом чате** после подключения.
|
|
@@ -35,6 +36,32 @@ MCP-серверы для DSH без SDK-зависимости: stdio и stream
|
|
|
35
36
|
|
|
36
37
|
Токены лежат отдельно от конфига и не логируются. HTTP без TLS разрешён только для localhost. Если сервер не отдаёт metadata или не поддерживает dynamic registration, OAuth завершится понятной ошибкой — токен вручную не подставляется.
|
|
37
38
|
|
|
39
|
+
## Sampling
|
|
40
|
+
|
|
41
|
+
Sampling выключен по умолчанию. Включите его галочкой в форме сервера или в `mcp.json`:
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"mcpServers": {
|
|
46
|
+
"remote": {
|
|
47
|
+
"url": "https://example.com/mcp",
|
|
48
|
+
"trusted": true,
|
|
49
|
+
"sampling": true
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Что гарантирует kit:
|
|
56
|
+
|
|
57
|
+
- запрос обрабатывает **DSH approval** — «Allow once» или отказ; в карточке виден preview промпта;
|
|
58
|
+
- **tools в sampling запрещены** (сервер не получает исполнение инструментов через этот путь);
|
|
59
|
+
- лимит **1024 токена** и модель текущей сессии;
|
|
60
|
+
- approval/ошибка возвращаются серверу как JSON-RPC error, без утечки ключей;
|
|
61
|
+
- сервер без `sampling: true` получает `-32601`.
|
|
62
|
+
|
|
63
|
+
Это безопасный first version: prompt preview показывается, но не редактируется в approval-карточке.
|
|
64
|
+
|
|
38
65
|
## Prompts
|
|
39
66
|
|
|
40
67
|
Промпт — это готовый запрос с аргументами, который отдаёт сам MCP-сервер. Нажмите **Prompts**, заполните поля и получите текст. Результат можно скопировать одной кнопкой.
|
|
@@ -96,7 +123,7 @@ MCP-серверы для DSH без SDK-зависимости: stdio и stream
|
|
|
96
123
|
|
|
97
124
|
## Ограничения
|
|
98
125
|
|
|
99
|
-
-
|
|
126
|
+
- Sampling: только opt-in, без tools; approval-карточка показывает preview, но не редактирует prompt.
|
|
100
127
|
- OAuth поддерживает dynamic registration; серверы только со статическим client_id пока не подключаются автоматически.
|
|
101
128
|
- HTTP-транспорт поддерживает JSON и простой SSE-ответ; интерактивный SSE-стрим с серверными запросами не реализован.
|
|
102
129
|
- MCP-сервер — произвольный процесс. Доверяйте только своим конфигам.
|
|
@@ -82,7 +82,7 @@ window.__ModuleLoader__.load({
|
|
|
82
82
|
.mcp-note{color:var(--mcp-muted);font-size:11px;line-height:1.45;margin:0}
|
|
83
83
|
.mcp-loading{color:var(--mcp-muted);font-size:13px;padding:18px 0}
|
|
84
84
|
.mcp-overlay{position:fixed;inset:0;background:rgba(10,20,18,.42);backdrop-filter:blur(4px);z-index:80;display:flex;align-items:center;justify-content:center;padding:20px}
|
|
85
|
-
.mcp-modal{width:min(640px,100%);max-height:min(86vh,820px);overflow:auto;background:var(--mcp-panel);border:1px solid var(--mcp-line);border-radius:20px;box-shadow:0 24px 80px rgba(10,20,18,.24);padding:22px;display:flex;flex-direction:column;gap:16px}
|
|
85
|
+
.mcp-modal{box-sizing:border-box;width:min(640px,100%);max-height:min(86vh,820px);overflow:auto;background:var(--mcp-panel);border:1px solid var(--mcp-line);border-radius:20px;box-shadow:0 24px 80px rgba(10,20,18,.24);padding:22px;display:flex;flex-direction:column;gap:16px}
|
|
86
86
|
.mcp-modal-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
|
|
87
87
|
.mcp-modal h2{margin:0;font-size:20px;letter-spacing:-.02em}
|
|
88
88
|
.mcp-modal p{margin:4px 0 0;color:var(--mcp-muted);font-size:13px;line-height:1.45}
|
|
@@ -280,6 +280,10 @@ window.__ModuleLoader__.load({
|
|
|
280
280
|
h("input", { type: "checkbox", checked: form.trusted, onChange: (event) => set({ trusted: event.target.checked }) }),
|
|
281
281
|
h("span", null, "Я доверяю этому серверу. Он сможет выполнять команды и читать данные, к которым у него есть доступ."),
|
|
282
282
|
),
|
|
283
|
+
h("label", { className: "mcp-check wide" },
|
|
284
|
+
h("input", { type: "checkbox", checked: form.sampling === true, onChange: (event) => set({ sampling: event.target.checked }) }),
|
|
285
|
+
h("span", null, "Разрешить sampling: сервер сможет попросить модель сгенерировать текст. Каждый запрос показывает approval-карточку, tools запрещены, лимит 1024 токена."),
|
|
286
|
+
),
|
|
283
287
|
),
|
|
284
288
|
h("p", { className: "mcp-note" }, "Секрет сохраняется в ~/.dsh/mcp.secrets.json с правами 0600 и не попадает в mcp.json или лог."),
|
|
285
289
|
h("div", { className: "mcp-form-actions" },
|
|
@@ -443,8 +447,9 @@ window.__ModuleLoader__.load({
|
|
|
443
447
|
tokenPlaceholder: preset.tokenPlaceholder || "",
|
|
444
448
|
token: "",
|
|
445
449
|
trusted: preset.trusted === true,
|
|
450
|
+
sampling: false,
|
|
446
451
|
});
|
|
447
|
-
const openManual = () => setForm({ edit: false, id: "", transport: "stdio", command: "npx", args: "-y\n", url: "", tokenEnv: "MCP_TOKEN", tokenHeader: "Authorization", tokenLabel: "Токен", tokenPlaceholder: "", token: "", trusted: false });
|
|
452
|
+
const openManual = () => setForm({ edit: false, id: "", transport: "stdio", command: "npx", args: "-y\n", url: "", tokenEnv: "MCP_TOKEN", tokenHeader: "Authorization", tokenLabel: "Токен", tokenPlaceholder: "", token: "", trusted: false, sampling: false });
|
|
448
453
|
|
|
449
454
|
const servers = data?.servers ?? [];
|
|
450
455
|
const connected = servers.filter((server) => server.connected).length;
|
|
@@ -52,6 +52,7 @@ function publicServer(server) { return {
|
|
|
52
52
|
url: server.url ? (() => { try { return new URL(server.url).origin; } catch { return "invalid"; } })() : "",
|
|
53
53
|
enabled: server.enabled,
|
|
54
54
|
trusted: server.trusted,
|
|
55
|
+
sampling: server.sampling === true,
|
|
55
56
|
};
|
|
56
57
|
}
|
|
57
58
|
function presets() {
|
|
@@ -209,7 +210,7 @@ export function registerApi(ctx, manager) {
|
|
|
209
210
|
throw new Error(`для ${payload.tokenEnv} нужен токен`);
|
|
210
211
|
}
|
|
211
212
|
if (payload.tokenHeader && payload.token && !payload.tokenHeader) throw new Error("tokenHeader обязателен для HTTP-токена");
|
|
212
|
-
const raw = { trusted, enabled: payload.enabled !== false };
|
|
213
|
+
const raw = { trusted, enabled: payload.enabled !== false, sampling: payload.sampling === true };
|
|
213
214
|
if (transport === "http") {
|
|
214
215
|
raw.url = String(payload.url).trim();
|
|
215
216
|
const headers = {};
|
|
@@ -195,7 +195,9 @@ export class McpClient {
|
|
|
195
195
|
"initialize",
|
|
196
196
|
{
|
|
197
197
|
protocolVersion: PROTOCOL_VERSION,
|
|
198
|
-
capabilities: canHandle
|
|
198
|
+
capabilities: canHandle
|
|
199
|
+
? { roots: { listChanged: false }, ...(this.config.sampling === true ? { sampling: {} } : {}) }
|
|
200
|
+
: {},
|
|
199
201
|
clientInfo: { name: "dsh-mcp-manager", version: "1.0.0" },
|
|
200
202
|
},
|
|
201
203
|
this.config.timeoutMs,
|
|
@@ -155,6 +155,7 @@ function normalizeServer(id, raw, env, secrets) {
|
|
|
155
155
|
cwd: typeof raw.cwd === "string" ? raw.cwd : undefined,
|
|
156
156
|
timeoutMs: Math.max(1_000, Math.min(120_000, Number(raw.timeoutMs) || 30_000)),
|
|
157
157
|
trusted: raw.trusted === true,
|
|
158
|
+
sampling: raw.sampling === true,
|
|
158
159
|
enabled: raw.enabled !== false,
|
|
159
160
|
};
|
|
160
161
|
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { McpClient } from "./client.js";
|
|
5
5
|
import { getAccessToken } from "./oauth.js";
|
|
6
|
+
import { runSampling } from "./sampling.js";
|
|
6
7
|
import path from "node:path";
|
|
7
8
|
import { pathToFileURL } from "node:url";
|
|
8
9
|
|
|
@@ -44,28 +45,33 @@ export class McpManager {
|
|
|
44
45
|
return `${base.slice(0, 60)}_${suffix}`;
|
|
45
46
|
}
|
|
46
47
|
|
|
48
|
+
async handleServerRequest(server, message) {
|
|
49
|
+
const root = path.resolve(server.cwd || process.cwd());
|
|
50
|
+
if (message.method === "roots/list") {
|
|
51
|
+
return {
|
|
52
|
+
roots: [{
|
|
53
|
+
uri: pathToFileURL(root).href,
|
|
54
|
+
name: path.basename(root) || "workspace",
|
|
55
|
+
}],
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
if (message.method === "ping") return {};
|
|
59
|
+
if (message.method === "sampling/createMessage") {
|
|
60
|
+
return runSampling(this.ctx, server, message.params ?? {});
|
|
61
|
+
}
|
|
62
|
+
const error = new Error(`${message.method}: not supported by DSH; elicitation requires explicit approval`);
|
|
63
|
+
error.code = -32601;
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
|
|
47
67
|
async connect(server) {
|
|
48
68
|
if (this.closed) throw new Error("MCP manager is closed");
|
|
49
69
|
const existing = this.clients.get(server.id);
|
|
50
70
|
if (existing?.client?.connected) return existing;
|
|
51
|
-
const root = path.resolve(server.cwd || process.cwd());
|
|
52
71
|
const client = new McpClient({
|
|
53
72
|
...server,
|
|
54
73
|
tokenProvider: server.url ? () => getAccessToken(server.id, { resource: server.url }).catch(() => null) : undefined,
|
|
55
|
-
onServerRequest: (message) =>
|
|
56
|
-
if (message.method === "roots/list") {
|
|
57
|
-
return {
|
|
58
|
-
roots: [{
|
|
59
|
-
uri: pathToFileURL(root).href,
|
|
60
|
-
name: path.basename(root) || "workspace",
|
|
61
|
-
}],
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
if (message.method === "ping") return {};
|
|
65
|
-
const error = new Error(`${message.method}: not supported by DSH; sampling and elicitation require explicit approval`);
|
|
66
|
-
error.code = -32601;
|
|
67
|
-
throw error;
|
|
68
|
-
},
|
|
74
|
+
onServerRequest: (message) => this.handleServerRequest(server, message),
|
|
69
75
|
}, this.ctx.logger);
|
|
70
76
|
try {
|
|
71
77
|
await client.connect();
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safe MCP sampling.
|
|
3
|
+
*
|
|
4
|
+
* The server never gets a direct model key. Every request goes through:
|
|
5
|
+
* 1. per-server `sampling: true` opt-in;
|
|
6
|
+
* 2. the deployment approval service (human, fail-closed);
|
|
7
|
+
* 3. the current/default model through `ctx.llm` with bounded tokens.
|
|
8
|
+
*
|
|
9
|
+
* Tools are intentionally rejected in this first version: a server-supplied
|
|
10
|
+
* prompt must not gain tool execution through the sampling loop.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
function textFromContent(content) {
|
|
14
|
+
if (typeof content === "string") return content;
|
|
15
|
+
if (Array.isArray(content)) return content.map((block) => block?.text ?? "").join("\n");
|
|
16
|
+
return content?.text ?? "";
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function promptText(params) {
|
|
20
|
+
const messages = Array.isArray(params?.messages) ? params.messages : [];
|
|
21
|
+
return messages.map((message) => `${message.role === "assistant" ? "assistant" : "user"}: ${textFromContent(message.content)}`).join("\n");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function preview(value, max = 900) {
|
|
25
|
+
const text = String(value ?? "");
|
|
26
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function modelOf(agent, ctx) {
|
|
30
|
+
const header = agent?.session?.requestHeader?.();
|
|
31
|
+
if (header?.config?.provider && header?.config?.model) return header.config;
|
|
32
|
+
const selection = ctx.get?.("agentDefaultModel")?.currentSelection?.();
|
|
33
|
+
if (selection?.provider && selection?.model) return selection;
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function runSampling(ctx, server, params) {
|
|
38
|
+
if (server?.sampling !== true) {
|
|
39
|
+
const error = new Error(`MCP ${server?.id ?? "?"}: sampling is disabled for this server`);
|
|
40
|
+
error.code = -32601;
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
if (Array.isArray(params?.tools) && params.tools.length > 0) {
|
|
44
|
+
throw new Error("MCP sampling with tools is not supported; tools must be executed through explicit MCP tool calls");
|
|
45
|
+
}
|
|
46
|
+
const agents = ctx.get?.("agents");
|
|
47
|
+
const agent = agents?.currentInitiator?.();
|
|
48
|
+
if (!agent) throw new Error("MCP sampling requires an active agent turn");
|
|
49
|
+
const approval = ctx.get?.("approval");
|
|
50
|
+
if (!approval || typeof approval.request !== "function") throw new Error("MCP sampling is unavailable: approval service is missing");
|
|
51
|
+
const prompt = promptText(params);
|
|
52
|
+
const displayReason = {
|
|
53
|
+
en: `MCP server "${server.id}" asks the model:\n${preview(prompt)}`,
|
|
54
|
+
ru: `MCP-сервер «${server.id}» просит модель:\n${preview(prompt)}`,
|
|
55
|
+
};
|
|
56
|
+
const outcome = await approval.request({
|
|
57
|
+
agent,
|
|
58
|
+
toolName: "mcp_sampling",
|
|
59
|
+
reason: `MCP ${server.id} sampling request`,
|
|
60
|
+
displayReason,
|
|
61
|
+
});
|
|
62
|
+
if (outcome !== "allowed-once") {
|
|
63
|
+
const error = new Error(`MCP sampling ${outcome === "rejected" ? "rejected by user" : `not allowed (${outcome})`}`);
|
|
64
|
+
error.code = -32600;
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
const model = modelOf(agent, ctx);
|
|
68
|
+
if (!model) throw new Error("MCP sampling: no model route is available");
|
|
69
|
+
const llm = ctx.get?.("llm");
|
|
70
|
+
if (!llm || typeof llm.stream !== "function") throw new Error("MCP sampling: llm service is unavailable");
|
|
71
|
+
const messages = (Array.isArray(params?.messages) ? params.messages : []).map((message) => ({
|
|
72
|
+
role: message.role === "assistant" ? "assistant" : "user",
|
|
73
|
+
content: [{ type: "text", text: textFromContent(message.content) }],
|
|
74
|
+
}));
|
|
75
|
+
const maxTokens = Math.max(1, Math.min(1024, Number(params?.maxTokens) || 512));
|
|
76
|
+
const chunks = llm.stream({
|
|
77
|
+
provider: model.provider,
|
|
78
|
+
model: model.model,
|
|
79
|
+
messages,
|
|
80
|
+
system: typeof params?.systemPrompt === "string" ? params.systemPrompt : undefined,
|
|
81
|
+
maxTokens,
|
|
82
|
+
temperature: 0.7,
|
|
83
|
+
sessionId: agent.session?.id,
|
|
84
|
+
purpose: "mcp-sampling",
|
|
85
|
+
});
|
|
86
|
+
let text = "";
|
|
87
|
+
let stopReason = "endTurn";
|
|
88
|
+
for await (const chunk of chunks) {
|
|
89
|
+
if (chunk?.type === "text-delta") text += chunk.text;
|
|
90
|
+
else if (chunk?.type === "block-end" && chunk.block?.type === "text") text += chunk.block.text ?? "";
|
|
91
|
+
else if (chunk?.type === "finish") {
|
|
92
|
+
if (chunk.reason?.kind === "error") throw new Error(chunk.reason.failure?.message ?? "model error");
|
|
93
|
+
if (chunk.reason?.kind === "max-tokens") stopReason = "maxTokens";
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (!text.trim()) throw new Error("MCP sampling: model returned no text");
|
|
97
|
+
return {
|
|
98
|
+
role: "assistant",
|
|
99
|
+
content: { type: "text", text },
|
|
100
|
+
model: `${model.provider}/${model.model}`,
|
|
101
|
+
stopReason,
|
|
102
|
+
};
|
|
103
|
+
}
|