dsh-desktop-kit 2.9.0 → 2.11.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 CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.11.0 (2026-11-12)
4
+
5
+ - **MCP elicitation.** Opt-in `elicitation: true`; `elicitation/create` открывает глобальную форму DSH с Accept/Decline/Cancel, валидацией плоской JSON-схемы и таймаутом.
6
+ - **UI.** Глобальный overlay `shell.overlay` (не только Settings), поля string/number/integer/boolean/enum, очередь и счётчик запросов.
7
+ - **Безопасность.** Неизвестные поля отклоняются, required/min/max проверяются на хосте, лимиты 4 КБ и 5 запросов, decline/cancel не отправляют content.
8
+ - **Тесты.** `mcp-elicitation-tests`: accept/decline/cancel, required, unknown field, max, timeout queue limits.
9
+ - **Elicitation UI.** 390/768/1440: overflow 0, console 0, markup 0; исправлены CSS-переменные overlay.
10
+
11
+ ## 2.10.0 (2026-11-12)
12
+
13
+ - **MCP sampling.** Opt-in `sampling: true`; серверный `sampling/createMessage` идёт через DSH approval-карточку с preview, затем в модель текущей сессии.
14
+ - **Безопасность.** Tools в sampling запрещены, лимит 1024 токена, approval fail-closed, сервер без opt-in получает `-32601`.
15
+ - **UI.** Галочка sampling в форме сервера и понятное предупреждение о рисках.
16
+ - **Тесты.** `mcp-sampling-tests`: allow/reject/disabled/tools, лимит токенов, preview.
17
+
3
18
  ## 2.9.0 (2026-11-12)
4
19
 
5
20
  - **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
- ![DSH Desktop Kit 2.7](https://unpkg.com/dsh-desktop-kit@2.9.0/docs/images/hero.png)
7
+ ![DSH Desktop Kit 2.7](https://unpkg.com/dsh-desktop-kit@2.11.0/docs/images/hero.png)
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** — токен хранится отдельно в `~/.dsh/mcp.oauth.json`.
11
+ Настройки → **MCP**: пресеты GitHub, PostgreSQL и Filesystem, живые статусы, health, список tools и безопасное хранение токенов в `~/.dsh/mcp.secrets.json`. Промпты сервера открываются кнопкой **Prompts**: аргументы, запуск и копирование результата. HTTP-серверы подключаются через **OAuth 2.1 + PKCE**, **sampling** идёт через approval-карточку DSH, а **elicitation** — через глобальную форму с Accept/Decline.
12
12
 
13
- ![MCP Settings](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-mcp-manager/screenshots/settings-1440.png)
13
+ ![MCP Settings](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-mcp-manager/screenshots/settings-1440.png)
14
14
 
15
- ![MCP на 390px](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-mcp-manager/screenshots/settings-390.png)
15
+ ![MCP на 390px](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-mcp-manager/screenshots/settings-390.png)
16
16
 
17
- ![Добавление MCP-сервера](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-mcp-manager/screenshots/modal-390.png)
17
+ ![Добавление MCP-сервера](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-mcp-manager/screenshots/modal-390.png)
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
- ![Агенты проекта](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-agent-extensions/screenshots/agents-1440.png)
28
+ ![Агенты проекта](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-agent-extensions/screenshots/agents-1440.png)
29
29
 
30
- ![Права и ограничения](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-guardrails/screenshots/permissions-1440.png)
30
+ ![Права и ограничения](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-guardrails/screenshots/permissions-1440.png)
31
31
 
32
- **v2.9.0** · MIT · проверено на DSH `0.2.1-rc.5` и `0.2.2-rc.1` (Windows 11) · без внешних зависимостей и телеметрии
32
+ **v2.11.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
- ![Настройки памяти проектов](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-memory-bridge/docs/images/settings-light.png)
120
+ ![Настройки памяти проектов](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-memory-bridge/docs/images/settings-light.png)
121
121
 
122
- ![Конфликты досье](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-memory-bridge/docs/images/conflicts.png)
122
+ ![Конфликты досье](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-memory-bridge/docs/images/conflicts.png)
123
123
 
124
124
  ## Скриншоты
125
125
 
126
126
  ### Skills Studio: каталог, стоимость и редактор
127
127
 
128
- ![Каталог навыков](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-gkb-ru-ui/screenshots/02-skills-1440-light.png)
128
+ ![Каталог навыков](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-gkb-ru-ui/screenshots/02-skills-1440-light.png)
129
129
 
130
- ![Редактор навыка](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-gkb-ru-ui/screenshots/03-skills-editor-1440-light.png)
130
+ ![Редактор навыка](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-gkb-ru-ui/screenshots/03-skills-editor-1440-light.png)
131
131
 
132
132
  ### Token Lab: куда уходит контекст
133
133
 
134
- ![Токен-лаборатория](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-token-lab/screenshots/01-token-lab-1440-light.png)
134
+ ![Токен-лаборатория](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-token-lab/screenshots/01-token-lab-1440-light.png)
135
135
 
136
136
  ### Тёмная тема и мобильный
137
137
 
138
- ![Тёмная тема](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-gkb-ru-ui/screenshots/04-skills-1440-dark.png)
138
+ ![Тёмная тема](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-gkb-ru-ui/screenshots/04-skills-1440-dark.png)
139
139
 
140
- ![Каталог навыков на 390 px](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-gkb-ru-ui/screenshots/05-skills-390-light.png)
140
+ ![Каталог навыков на 390 px](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-gkb-ru-ui/screenshots/05-skills-390-light.png)
141
141
 
142
142
  ## Окно-напоминание: пиковый тариф
143
143
 
@@ -147,11 +147,11 @@ DeepSeek включает двойной тариф в пиковые часы (
147
147
  - **в окне** — красная карточка: причина, границы окна в местном времени и UTC, живой отсчёт до конца и рекомендация, когда вернуться;
148
148
  - **после окна** — карточка исчезает; состояние всегда доступно через `window.__DSH_PEAK_GUARD__.state()`.
149
149
 
150
- ![Окно-напоминание: светлая тема](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-peak-guard/screenshots/03-peak-card-1440-light.png)
150
+ ![Окно-напоминание: светлая тема](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-peak-guard/screenshots/03-peak-card-1440-light.png)
151
151
 
152
- ![Окно-напоминание: тёмная тема](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-peak-guard/screenshots/04-peak-card-1440-dark.png)
152
+ ![Окно-напоминание: тёмная тема](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-peak-guard/screenshots/04-peak-card-1440-dark.png)
153
153
 
154
- ![Окно-напоминание на 390 px](https://unpkg.com/dsh-desktop-kit@2.9.0/plugins/dsh-peak-guard/screenshots/05-peak-card-390-light.png)
154
+ ![Окно-напоминание на 390 px](https://unpkg.com/dsh-desktop-kit@2.11.0/plugins/dsh-peak-guard/screenshots/05-peak-card-390-light.png)
155
155
 
156
156
  Подробности и настройки — [plugins/dsh-peak-guard/README.md](plugins/dsh-peak-guard/README.md).
157
157
 
package/client.js CHANGED
@@ -6936,6 +6936,8 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
6936
6936
  .mcp-prompt-card b{display:block;font-size:13px}
6937
6937
  .mcp-prompt-card span{display:block;color:var(--mcp-muted);font-size:12px;line-height:1.4;margin-top:3px}
6938
6938
  .mcp-prompt-output{margin:0;padding:12px;border:1px solid var(--mcp-line);border-radius:10px;background:var(--mcp-soft);color:var(--mcp-text);font:12px/1.55 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;max-height:38vh;overflow:auto}
6939
+ .mcp-elicit{--mcp-line:var(--dsw-alias-border-l1,rgba(20,40,36,.13));--mcp-soft:var(--dsw-alias-bg-layer-1,#f4f7f5);--mcp-panel:var(--dsw-alias-bg-layer-2,#fff);--mcp-text:var(--dsw-alias-label-primary,#17231f);--mcp-muted:var(--dsw-alias-label-secondary,#61706b);--mcp-accent:var(--dsw-alias-brand-primary,#0f766e);--mcp-accent-soft:rgba(15,118,110,.07);pointer-events:auto;z-index:90}
6940
+ .mcp-elicit-message{margin:0;color:var(--mcp-text);font-size:13px;line-height:1.5;max-height:22vh;overflow:auto;overflow-wrap:anywhere}
6939
6941
  .mcp-empty{border:1px dashed var(--mcp-line);border-radius:18px;padding:26px;background:linear-gradient(160deg,var(--mcp-soft),transparent 75%);display:flex;flex-direction:column;gap:12px;align-items:flex-start}
6940
6942
  .mcp-empty h3{margin:0;font-size:18px;letter-spacing:-.015em}
6941
6943
  .mcp-empty p{margin:0;color:var(--mcp-muted);font-size:13px;line-height:1.5;max-width:60ch}
@@ -6947,7 +6949,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
6947
6949
  .mcp-note{color:var(--mcp-muted);font-size:11px;line-height:1.45;margin:0}
6948
6950
  .mcp-loading{color:var(--mcp-muted);font-size:13px;padding:18px 0}
6949
6951
  .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}
6952
+ .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
6953
  .mcp-modal-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
6952
6954
  .mcp-modal h2{margin:0;font-size:20px;letter-spacing:-.02em}
6953
6955
  .mcp-modal p{margin:4px 0 0;color:var(--mcp-muted);font-size:13px;line-height:1.45}
@@ -7145,6 +7147,16 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
7145
7147
  h("input", { type: "checkbox", checked: form.trusted, onChange: (event) => set({ trusted: event.target.checked }) }),
7146
7148
  h("span", null, "Я доверяю этому серверу. Он сможет выполнять команды и читать данные, к которым у него есть доступ."),
7147
7149
  ),
7150
+ form.transport === "stdio" ? h(React.Fragment, null,
7151
+ h("label", { className: "mcp-check wide" },
7152
+ h("input", { type: "checkbox", checked: form.sampling === true, onChange: (event) => set({ sampling: event.target.checked }) }),
7153
+ h("span", null, "Разрешить sampling: сервер сможет попросить модель сгенерировать текст. Каждый запрос показывает approval-карточку, tools запрещены, лимит 1024 токена."),
7154
+ ),
7155
+ h("label", { className: "mcp-check wide" },
7156
+ h("input", { type: "checkbox", checked: form.elicitation === true, onChange: (event) => set({ elicitation: event.target.checked }) }),
7157
+ h("span", null, "Разрешить elicitation: сервер сможет запросить структурированные данные через форму DSH. Каждый запрос можно принять или отклонить."),
7158
+ ),
7159
+ ) : null,
7148
7160
  ),
7149
7161
  h("p", { className: "mcp-note" }, "Секрет сохраняется в ~/.dsh/mcp.secrets.json с правами 0600 и не попадает в mcp.json или лог."),
7150
7162
  h("div", { className: "mcp-form-actions" },
@@ -7308,8 +7320,10 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
7308
7320
  tokenPlaceholder: preset.tokenPlaceholder || "",
7309
7321
  token: "",
7310
7322
  trusted: preset.trusted === true,
7323
+ sampling: false,
7324
+ elicitation: false,
7311
7325
  });
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 });
7326
+ 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, elicitation: false });
7313
7327
 
7314
7328
  const servers = data?.servers ?? [];
7315
7329
  const connected = servers.filter((server) => server.connected).length;
@@ -7393,6 +7407,134 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
7393
7407
  );
7394
7408
  }
7395
7409
 
7410
+ function ElicitationHost() {
7411
+ const [items, setItems] = useState([]);
7412
+ const [values, setValues] = useState({});
7413
+ const [busy, setBusy] = useState(false);
7414
+ const [error, setError] = useState("");
7415
+ const current = items[0];
7416
+
7417
+ useEffect(() => {
7418
+ let stopped = false;
7419
+ const refresh = async () => {
7420
+ if (document.hidden) return;
7421
+ try {
7422
+ const result = await call(window.__DSH_MCP_CTX__, "elicitations");
7423
+ if (!stopped) setItems(Array.isArray(result.items) ? result.items : []);
7424
+ } catch { /* host may be restarting */ }
7425
+ };
7426
+ void refresh();
7427
+ const timer = setInterval(refresh, 2500);
7428
+ const onVisible = () => { if (!document.hidden) void refresh(); };
7429
+ document.addEventListener("visibilitychange", onVisible);
7430
+ return () => {
7431
+ stopped = true;
7432
+ clearInterval(timer);
7433
+ document.removeEventListener("visibilitychange", onVisible);
7434
+ };
7435
+ }, []);
7436
+
7437
+ useEffect(() => {
7438
+ if (!current) { setValues({}); return; }
7439
+ const next = {};
7440
+ for (const [key, property] of Object.entries(current.schema?.properties ?? {})) {
7441
+ if (property?.type === "boolean") next[key] = false;
7442
+ else if (property?.enum?.length) next[key] = property.enum[0];
7443
+ else next[key] = "";
7444
+ }
7445
+ setValues(next);
7446
+ setError("");
7447
+ }, [current?.id]);
7448
+
7449
+ if (!current) return null;
7450
+ const properties = Object.entries(current.schema?.properties ?? {});
7451
+ const required = Array.isArray(current.schema?.required) ? current.schema.required : [];
7452
+
7453
+ const respond = async (action) => {
7454
+ setBusy(true);
7455
+ setError("");
7456
+ try {
7457
+ await call(window.__DSH_MCP_CTX__, "elicitation", {
7458
+ id: current.id,
7459
+ action,
7460
+ ...(action === "accept" ? { content: values } : {}),
7461
+ });
7462
+ setItems((list) => list.slice(1));
7463
+ } catch (cause) {
7464
+ setError(cause instanceof Error ? cause.message : String(cause));
7465
+ } finally {
7466
+ setBusy(false);
7467
+ }
7468
+ };
7469
+
7470
+ return h("div", { className: "mcp-overlay mcp-elicit" },
7471
+ h("div", { className: "mcp-modal", role: "dialog", "aria-modal": "true", "aria-labelledby": "mcp-elicit-title" },
7472
+ h("div", { className: "mcp-modal-head" },
7473
+ h("div", null,
7474
+ h("h2", { id: "mcp-elicit-title" }, "Запрос данных"),
7475
+ h("p", null, `Сервер «${current.serverId}» просит заполнить форму.`),
7476
+ ),
7477
+ items.length > 1 ? h("span", { className: "mcp-badge" }, `${items.length} в очереди`) : null,
7478
+ ),
7479
+ h("p", { className: "mcp-elicit-message" }, current.message),
7480
+ error ? h("div", { className: "mcp-error", role: "alert" }, error) : null,
7481
+ h("div", { className: "mcp-form" },
7482
+ properties.length === 0 ? h("p", { className: "mcp-note", style: { gridColumn: "1/-1" } }, "Сервер не запросил полей — можно просто подтвердить.") : null,
7483
+ properties.map(([key, property], index) => {
7484
+ const id = `mcp-elicit-field-${index}`;
7485
+ if (property?.type === "boolean") {
7486
+ return h("label", { className: "mcp-check wide", key }, h("input", {
7487
+ type: "checkbox",
7488
+ checked: values[key] === true,
7489
+ onChange: (event) => setValues((currentValues) => ({ ...currentValues, [key]: event.target.checked })),
7490
+ }), h("span", null, property.title || key, required.includes(key) ? " *" : ""));
7491
+ }
7492
+ if (Array.isArray(property?.enum)) {
7493
+ return h("div", { className: "mcp-field", key },
7494
+ h("label", { htmlFor: id }, property.title || key, required.includes(key) ? " *" : ""),
7495
+ h("select", {
7496
+ id,
7497
+ value: values[key] ?? "",
7498
+ onChange: (event) => setValues((currentValues) => ({ ...currentValues, [key]: event.target.value })),
7499
+ }, property.enum.map((option) => h("option", { key: String(option), value: String(option) }, String(option)))),
7500
+ );
7501
+ }
7502
+ if (property?.type === "number" || property?.type === "integer") {
7503
+ return h("div", { className: "mcp-field", key },
7504
+ h("label", { htmlFor: id }, property.title || key, required.includes(key) ? " *" : ""),
7505
+ h("input", {
7506
+ id,
7507
+ type: "number",
7508
+ value: values[key] ?? "",
7509
+ min: property.minimum,
7510
+ max: property.maximum,
7511
+ onChange: (event) => setValues((currentValues) => ({ ...currentValues, [key]: event.target.value === "" ? "" : Number(event.target.value) })),
7512
+ }),
7513
+ );
7514
+ }
7515
+ if (property?.type === "string") {
7516
+ return h("div", { className: `mcp-field${String(property.description || "").length > 40 ? " wide" : ""}`, key },
7517
+ h("label", { htmlFor: id }, property.title || key, required.includes(key) ? " *" : ""),
7518
+ h("input", {
7519
+ id,
7520
+ value: values[key] ?? "",
7521
+ placeholder: property.description || "",
7522
+ onChange: (event) => setValues((currentValues) => ({ ...currentValues, [key]: event.target.value })),
7523
+ }),
7524
+ );
7525
+ }
7526
+ return h("div", { className: "mcp-error wide", key }, `Поле «${key}» имеет неподдерживаемый тип.`);
7527
+ }),
7528
+ h("div", { className: "mcp-form-actions", style: { gridColumn: "1/-1" } },
7529
+ h("button", { className: "mcp-btn ghost", type: "button", disabled: busy, onClick: () => respond("decline") }, "Отклонить"),
7530
+ h("button", { className: "mcp-btn ghost", type: "button", disabled: busy, onClick: () => respond("cancel") }, "Отмена"),
7531
+ h("button", { className: "mcp-btn primary", type: "button", disabled: busy, onClick: () => respond("accept") }, busy ? "Отправляем…" : "Подтвердить"),
7532
+ ),
7533
+ ),
7534
+ ),
7535
+ );
7536
+ }
7537
+
7396
7538
  function apply(ctx) {
7397
7539
  window.__DSH_MCP_CTX__ = ctx;
7398
7540
  ctx.effect(() => {
@@ -7406,7 +7548,13 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
7406
7548
  name: "settings.section",
7407
7549
  id: "mcp-manager",
7408
7550
  order: 35,
7409
- label: () => "MCP", }, McpSection)), "mcp-manager: settings");
7551
+ label: () => "MCP",
7552
+ }, McpSection)), "mcp-manager: settings");
7553
+ ctx.effect(() => ctx.slots.inject("shell.overlay", () => ctx.slots.register({
7554
+ name: "shell.overlay",
7555
+ id: "mcp-elicitation",
7556
+ order: 700,
7557
+ }, ElicitationHost)), "mcp-manager: elicitation overlay");
7410
7558
  }
7411
7559
 
7412
7560
  exports.apply = apply;
@@ -7870,7 +8018,7 @@ var(--dsw-alias-bg-layer-1,#fff);box-shadow:inset 0 1px 0 color-mix(in srgb,#fff
7870
8018
  if (__kitErrors.length <= 5) console.error("[dsh-desktop-kit] registration failed:", label, message);
7871
8019
  };
7872
8020
  try {
7873
- window.__DSH_DESKTOP_KIT__ = { version: "2.9.0", parts: __partNames, errors: __kitErrors, ready: false };
8021
+ window.__DSH_DESKTOP_KIT__ = { version: "2.11.0", parts: __partNames, errors: __kitErrors, ready: false };
7874
8022
  } catch {}
7875
8023
  const __inject = [];
7876
8024
  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 не реализован.
@@ -0,0 +1,29 @@
1
+ # DSH Desktop Kit 2.11.0 — тест
2
+
3
+ Дата: 2026-11-12.
4
+
5
+ ## MCP elicitation
6
+
7
+ - Per-server `elicitation: true` (по умолчанию false).
8
+ - `elicitation/create` → global `shell.overlay` форма.
9
+ - Accept/Decline/Cancel; accept валидируется по схеме.
10
+ - Поддержаны string, number/integer, boolean, enum.
11
+ - Required, minimum, maximum, unknown field проверяются.
12
+ - Лимиты: message/value 4000, 5 pending, timeout 5 минут.
13
+ - Очередь пересоздаётся после restart manager.
14
+
15
+ ## UI
16
+
17
+ - Глобальный overlay поверх всех колонок, pointer-events auto.
18
+ - Счётчик очереди, ошибки, адаптив 390/768/1440.
19
+ - Скриншоты/аудит: overflow 0, console 0, markup 0.
20
+
21
+ ## Тесты
22
+
23
+ - `tools/mcp-elicitation-tests.mjs` — OK.
24
+ - `npm test` — exit 0.
25
+ - `build:client` / `check:client` — OK.
26
+
27
+ ## Ограничение
28
+
29
+ Плоская схема; вложенные object/array не поддержаны. Только stdio transport.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-desktop-kit",
3
- "version": "2.9.0",
3
+ "version": "2.11.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-elicitation-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**, **elicitation**, trust-гейт и премиальный экран в Settings.
4
4
 
5
5
  ![MCP Settings](screenshots/settings-1440.png)
6
6
 
@@ -14,6 +14,8 @@ 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;
18
+ - **Elicitation** — отдельный opt-in: сервер может запросить структурированные данные через глобальную форму DSH с Accept/Decline/Cancel;
17
19
  - «Добавить сервер» — пресеты GitHub / PostgreSQL / Filesystem или ручная форма;
18
20
  - токен сохраняется в `~/.dsh/mcp.secrets.json` (0600), а в `mcp.json` остаётся только `${secret:…}`;
19
21
  - новые tools появляются в **новом чате** после подключения.
@@ -35,6 +37,42 @@ MCP-серверы для DSH без SDK-зависимости: stdio и stream
35
37
 
36
38
  Токены лежат отдельно от конфига и не логируются. HTTP без TLS разрешён только для localhost. Если сервер не отдаёт metadata или не поддерживает dynamic registration, OAuth завершится понятной ошибкой — токен вручную не подставляется.
37
39
 
40
+ ## Sampling
41
+
42
+ Sampling выключен по умолчанию. Включите его галочкой в форме сервера или в `mcp.json`:
43
+
44
+ ```json
45
+ {
46
+ "mcpServers": {
47
+ "remote": {
48
+ "url": "https://example.com/mcp",
49
+ "trusted": true,
50
+ "sampling": true
51
+ }
52
+ }
53
+ }
54
+ ```
55
+
56
+ Что гарантирует kit:
57
+
58
+ - запрос обрабатывает **DSH approval** — «Allow once» или отказ; в карточке виден preview промпта;
59
+ - **tools в sampling запрещены** (сервер не получает исполнение инструментов через этот путь);
60
+ - лимит **1024 токена** и модель текущей сессии;
61
+ - approval/ошибка возвращаются серверу как JSON-RPC error, без утечки ключей;
62
+ - сервер без `sampling: true` получает `-32601`.
63
+
64
+ Это безопасный first version: prompt preview показывается, но не редактируется в approval-карточке.
65
+
66
+ ## Elicitation
67
+
68
+ Elicitation тоже выключен по умолчанию (`"elicitation": true`). Запрос сервера появляется **глобальной формой** поверх DSH, а не только внутри Settings:
69
+
70
+ - поддержаны поля `string`, `number`/`integer`, `boolean`, `enum`;
71
+ - обязательные поля и границы (`minimum`/`maximum`) проверяются на хосте;
72
+ - неизвестные поля отклоняются, сообщение и значения ограничены по длине;
73
+ - `accept` отправляет только валидированный `content`, `decline`/`cancel` закрывают запрос;
74
+ - пять одновременных запросов — предел, таймаут 5 минут, при перезапуске менеджера очередь очищается.
75
+
38
76
  ## Prompts
39
77
 
40
78
  Промпт — это готовый запрос с аргументами, который отдаёт сам MCP-сервер. Нажмите **Prompts**, заполните поля и получите текст. Результат можно скопировать одной кнопкой.
@@ -96,7 +134,8 @@ MCP-серверы для DSH без SDK-зависимости: stdio и stream
96
134
 
97
135
  ## Ограничения
98
136
 
99
- - Нет sampling: сервер не может запросить генерацию у модели.
137
+ - Sampling: только opt-in, без tools; approval-карточка показывает preview, но не редактирует prompt.
138
+ - Elicitation: только opt-in, плоская схема; вложенные object/array не поддержаны.
100
139
  - OAuth поддерживает dynamic registration; серверы только со статическим client_id пока не подключаются автоматически.
101
140
  - HTTP-транспорт поддерживает JSON и простой SSE-ответ; интерактивный SSE-стрим с серверными запросами не реализован.
102
141
  - MCP-сервер — произвольный процесс. Доверяйте только своим конфигам.
@@ -71,6 +71,8 @@ window.__ModuleLoader__.load({
71
71
  .mcp-prompt-card b{display:block;font-size:13px}
72
72
  .mcp-prompt-card span{display:block;color:var(--mcp-muted);font-size:12px;line-height:1.4;margin-top:3px}
73
73
  .mcp-prompt-output{margin:0;padding:12px;border:1px solid var(--mcp-line);border-radius:10px;background:var(--mcp-soft);color:var(--mcp-text);font:12px/1.55 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;max-height:38vh;overflow:auto}
74
+ .mcp-elicit{--mcp-line:var(--dsw-alias-border-l1,rgba(20,40,36,.13));--mcp-soft:var(--dsw-alias-bg-layer-1,#f4f7f5);--mcp-panel:var(--dsw-alias-bg-layer-2,#fff);--mcp-text:var(--dsw-alias-label-primary,#17231f);--mcp-muted:var(--dsw-alias-label-secondary,#61706b);--mcp-accent:var(--dsw-alias-brand-primary,#0f766e);--mcp-accent-soft:rgba(15,118,110,.07);pointer-events:auto;z-index:90}
75
+ .mcp-elicit-message{margin:0;color:var(--mcp-text);font-size:13px;line-height:1.5;max-height:22vh;overflow:auto;overflow-wrap:anywhere}
74
76
  .mcp-empty{border:1px dashed var(--mcp-line);border-radius:18px;padding:26px;background:linear-gradient(160deg,var(--mcp-soft),transparent 75%);display:flex;flex-direction:column;gap:12px;align-items:flex-start}
75
77
  .mcp-empty h3{margin:0;font-size:18px;letter-spacing:-.015em}
76
78
  .mcp-empty p{margin:0;color:var(--mcp-muted);font-size:13px;line-height:1.5;max-width:60ch}
@@ -82,7 +84,7 @@ window.__ModuleLoader__.load({
82
84
  .mcp-note{color:var(--mcp-muted);font-size:11px;line-height:1.45;margin:0}
83
85
  .mcp-loading{color:var(--mcp-muted);font-size:13px;padding:18px 0}
84
86
  .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}
87
+ .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
88
  .mcp-modal-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
87
89
  .mcp-modal h2{margin:0;font-size:20px;letter-spacing:-.02em}
88
90
  .mcp-modal p{margin:4px 0 0;color:var(--mcp-muted);font-size:13px;line-height:1.45}
@@ -280,6 +282,16 @@ window.__ModuleLoader__.load({
280
282
  h("input", { type: "checkbox", checked: form.trusted, onChange: (event) => set({ trusted: event.target.checked }) }),
281
283
  h("span", null, "Я доверяю этому серверу. Он сможет выполнять команды и читать данные, к которым у него есть доступ."),
282
284
  ),
285
+ form.transport === "stdio" ? h(React.Fragment, null,
286
+ h("label", { className: "mcp-check wide" },
287
+ h("input", { type: "checkbox", checked: form.sampling === true, onChange: (event) => set({ sampling: event.target.checked }) }),
288
+ h("span", null, "Разрешить sampling: сервер сможет попросить модель сгенерировать текст. Каждый запрос показывает approval-карточку, tools запрещены, лимит 1024 токена."),
289
+ ),
290
+ h("label", { className: "mcp-check wide" },
291
+ h("input", { type: "checkbox", checked: form.elicitation === true, onChange: (event) => set({ elicitation: event.target.checked }) }),
292
+ h("span", null, "Разрешить elicitation: сервер сможет запросить структурированные данные через форму DSH. Каждый запрос можно принять или отклонить."),
293
+ ),
294
+ ) : null,
283
295
  ),
284
296
  h("p", { className: "mcp-note" }, "Секрет сохраняется в ~/.dsh/mcp.secrets.json с правами 0600 и не попадает в mcp.json или лог."),
285
297
  h("div", { className: "mcp-form-actions" },
@@ -443,8 +455,10 @@ window.__ModuleLoader__.load({
443
455
  tokenPlaceholder: preset.tokenPlaceholder || "",
444
456
  token: "",
445
457
  trusted: preset.trusted === true,
458
+ sampling: false,
459
+ elicitation: false,
446
460
  });
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 });
461
+ 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, elicitation: false });
448
462
 
449
463
  const servers = data?.servers ?? [];
450
464
  const connected = servers.filter((server) => server.connected).length;
@@ -528,6 +542,134 @@ window.__ModuleLoader__.load({
528
542
  );
529
543
  }
530
544
 
545
+ function ElicitationHost() {
546
+ const [items, setItems] = useState([]);
547
+ const [values, setValues] = useState({});
548
+ const [busy, setBusy] = useState(false);
549
+ const [error, setError] = useState("");
550
+ const current = items[0];
551
+
552
+ useEffect(() => {
553
+ let stopped = false;
554
+ const refresh = async () => {
555
+ if (document.hidden) return;
556
+ try {
557
+ const result = await call(window.__DSH_MCP_CTX__, "elicitations");
558
+ if (!stopped) setItems(Array.isArray(result.items) ? result.items : []);
559
+ } catch { /* host may be restarting */ }
560
+ };
561
+ void refresh();
562
+ const timer = setInterval(refresh, 2500);
563
+ const onVisible = () => { if (!document.hidden) void refresh(); };
564
+ document.addEventListener("visibilitychange", onVisible);
565
+ return () => {
566
+ stopped = true;
567
+ clearInterval(timer);
568
+ document.removeEventListener("visibilitychange", onVisible);
569
+ };
570
+ }, []);
571
+
572
+ useEffect(() => {
573
+ if (!current) { setValues({}); return; }
574
+ const next = {};
575
+ for (const [key, property] of Object.entries(current.schema?.properties ?? {})) {
576
+ if (property?.type === "boolean") next[key] = false;
577
+ else if (property?.enum?.length) next[key] = property.enum[0];
578
+ else next[key] = "";
579
+ }
580
+ setValues(next);
581
+ setError("");
582
+ }, [current?.id]);
583
+
584
+ if (!current) return null;
585
+ const properties = Object.entries(current.schema?.properties ?? {});
586
+ const required = Array.isArray(current.schema?.required) ? current.schema.required : [];
587
+
588
+ const respond = async (action) => {
589
+ setBusy(true);
590
+ setError("");
591
+ try {
592
+ await call(window.__DSH_MCP_CTX__, "elicitation", {
593
+ id: current.id,
594
+ action,
595
+ ...(action === "accept" ? { content: values } : {}),
596
+ });
597
+ setItems((list) => list.slice(1));
598
+ } catch (cause) {
599
+ setError(cause instanceof Error ? cause.message : String(cause));
600
+ } finally {
601
+ setBusy(false);
602
+ }
603
+ };
604
+
605
+ return h("div", { className: "mcp-overlay mcp-elicit" },
606
+ h("div", { className: "mcp-modal", role: "dialog", "aria-modal": "true", "aria-labelledby": "mcp-elicit-title" },
607
+ h("div", { className: "mcp-modal-head" },
608
+ h("div", null,
609
+ h("h2", { id: "mcp-elicit-title" }, "Запрос данных"),
610
+ h("p", null, `Сервер «${current.serverId}» просит заполнить форму.`),
611
+ ),
612
+ items.length > 1 ? h("span", { className: "mcp-badge" }, `${items.length} в очереди`) : null,
613
+ ),
614
+ h("p", { className: "mcp-elicit-message" }, current.message),
615
+ error ? h("div", { className: "mcp-error", role: "alert" }, error) : null,
616
+ h("div", { className: "mcp-form" },
617
+ properties.length === 0 ? h("p", { className: "mcp-note", style: { gridColumn: "1/-1" } }, "Сервер не запросил полей — можно просто подтвердить.") : null,
618
+ properties.map(([key, property], index) => {
619
+ const id = `mcp-elicit-field-${index}`;
620
+ if (property?.type === "boolean") {
621
+ return h("label", { className: "mcp-check wide", key }, h("input", {
622
+ type: "checkbox",
623
+ checked: values[key] === true,
624
+ onChange: (event) => setValues((currentValues) => ({ ...currentValues, [key]: event.target.checked })),
625
+ }), h("span", null, property.title || key, required.includes(key) ? " *" : ""));
626
+ }
627
+ if (Array.isArray(property?.enum)) {
628
+ return h("div", { className: "mcp-field", key },
629
+ h("label", { htmlFor: id }, property.title || key, required.includes(key) ? " *" : ""),
630
+ h("select", {
631
+ id,
632
+ value: values[key] ?? "",
633
+ onChange: (event) => setValues((currentValues) => ({ ...currentValues, [key]: event.target.value })),
634
+ }, property.enum.map((option) => h("option", { key: String(option), value: String(option) }, String(option)))),
635
+ );
636
+ }
637
+ if (property?.type === "number" || property?.type === "integer") {
638
+ return h("div", { className: "mcp-field", key },
639
+ h("label", { htmlFor: id }, property.title || key, required.includes(key) ? " *" : ""),
640
+ h("input", {
641
+ id,
642
+ type: "number",
643
+ value: values[key] ?? "",
644
+ min: property.minimum,
645
+ max: property.maximum,
646
+ onChange: (event) => setValues((currentValues) => ({ ...currentValues, [key]: event.target.value === "" ? "" : Number(event.target.value) })),
647
+ }),
648
+ );
649
+ }
650
+ if (property?.type === "string") {
651
+ return h("div", { className: `mcp-field${String(property.description || "").length > 40 ? " wide" : ""}`, key },
652
+ h("label", { htmlFor: id }, property.title || key, required.includes(key) ? " *" : ""),
653
+ h("input", {
654
+ id,
655
+ value: values[key] ?? "",
656
+ placeholder: property.description || "",
657
+ onChange: (event) => setValues((currentValues) => ({ ...currentValues, [key]: event.target.value })),
658
+ }),
659
+ );
660
+ }
661
+ return h("div", { className: "mcp-error wide", key }, `Поле «${key}» имеет неподдерживаемый тип.`);
662
+ }),
663
+ h("div", { className: "mcp-form-actions", style: { gridColumn: "1/-1" } },
664
+ h("button", { className: "mcp-btn ghost", type: "button", disabled: busy, onClick: () => respond("decline") }, "Отклонить"),
665
+ h("button", { className: "mcp-btn ghost", type: "button", disabled: busy, onClick: () => respond("cancel") }, "Отмена"),
666
+ h("button", { className: "mcp-btn primary", type: "button", disabled: busy, onClick: () => respond("accept") }, busy ? "Отправляем…" : "Подтвердить"),
667
+ ),
668
+ ),
669
+ ),
670
+ );
671
+ }
672
+
531
673
  function apply(ctx) {
532
674
  window.__DSH_MCP_CTX__ = ctx;
533
675
  ctx.effect(() => {
@@ -541,7 +683,13 @@ window.__ModuleLoader__.load({
541
683
  name: "settings.section",
542
684
  id: "mcp-manager",
543
685
  order: 35,
544
- label: () => "MCP", }, McpSection)), "mcp-manager: settings");
686
+ label: () => "MCP",
687
+ }, McpSection)), "mcp-manager: settings");
688
+ ctx.effect(() => ctx.slots.inject("shell.overlay", () => ctx.slots.register({
689
+ name: "shell.overlay",
690
+ id: "mcp-elicitation",
691
+ order: 700,
692
+ }, ElicitationHost)), "mcp-manager: elicitation overlay");
545
693
  }
546
694
 
547
695
  exports.apply = apply;
@@ -52,6 +52,8 @@ 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,
56
+ elicitation: server.elicitation === true,
55
57
  };
56
58
  }
57
59
  function presets() {
@@ -193,6 +195,12 @@ export function registerApi(ctx, manager) {
193
195
  await restartGlobal(manager);
194
196
  return { ...oauthStatus(id), pending: false, error: "" };
195
197
  });
198
+ operation("elicitations", async () => ({ items: manager.elicitations.list() }));
199
+ operation("elicitation", async (payload) => {
200
+ const id = String(payload.id ?? "");
201
+ const action = String(payload.action ?? "");
202
+ return manager.elicitations.respond(id, action, payload.content);
203
+ });
196
204
  operation("presets", async () => ({ presets: presets() }));
197
205
  operation("trust-project", async () => {
198
206
  const config = loadConfig({ cwd: process.cwd() });
@@ -209,7 +217,7 @@ export function registerApi(ctx, manager) {
209
217
  throw new Error(`для ${payload.tokenEnv} нужен токен`);
210
218
  }
211
219
  if (payload.tokenHeader && payload.token && !payload.tokenHeader) throw new Error("tokenHeader обязателен для HTTP-токена");
212
- const raw = { trusted, enabled: payload.enabled !== false };
220
+ const raw = { trusted, enabled: payload.enabled !== false, sampling: payload.sampling === true, elicitation: payload.elicitation === true };
213
221
  if (transport === "http") {
214
222
  raw.url = String(payload.url).trim();
215
223
  const headers = {};
@@ -195,7 +195,13 @@ export class McpClient {
195
195
  "initialize",
196
196
  {
197
197
  protocolVersion: PROTOCOL_VERSION,
198
- capabilities: canHandle ? { roots: { listChanged: false } } : {},
198
+ capabilities: canHandle
199
+ ? {
200
+ roots: { listChanged: false },
201
+ ...(this.config.sampling === true ? { sampling: {} } : {}),
202
+ ...(this.config.elicitation === true ? { elicitation: {} } : {}),
203
+ }
204
+ : {},
199
205
  clientInfo: { name: "dsh-mcp-manager", version: "1.0.0" },
200
206
  },
201
207
  this.config.timeoutMs,
@@ -155,6 +155,8 @@ 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,
159
+ elicitation: raw.elicitation === true,
158
160
  enabled: raw.enabled !== false,
159
161
  };
160
162
  }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * MCP elicitation queue.
3
+ *
4
+ * A server request waits here until the user accepts, declines or cancels it
5
+ * in the global DSH overlay. Accept validates the flat schema: strings,
6
+ * numbers/integers, booleans and enums, bounded message/values.
7
+ */
8
+ import crypto from "node:crypto";
9
+
10
+ const MAX_PENDING = 5;
11
+ const MAX_MESSAGE = 4_000;
12
+ const MAX_VALUE = 4_000;
13
+
14
+ function typeOf(property) {
15
+ return property?.type === "integer" ? "number" : property?.type;
16
+ }
17
+
18
+ function validateContent(schema, content) {
19
+ if (!content || typeof content !== "object" || Array.isArray(content)) throw new Error("elicitation: content must be an object");
20
+ const properties = schema?.properties && typeof schema.properties === "object" ? schema.properties : {};
21
+ const required = Array.isArray(schema?.required) ? schema.required : [];
22
+ for (const key of Object.keys(content)) {
23
+ if (!Object.hasOwn(properties, key)) throw new Error(`elicitation: unknown field "${key}"`);
24
+ }
25
+ for (const key of required) {
26
+ if (!Object.hasOwn(content, key) || content[key] === "" || content[key] === null || content[key] === undefined) {
27
+ throw new Error(`elicitation: "${key}" is required`);
28
+ }
29
+ }
30
+ for (const [key, value] of Object.entries(content)) {
31
+ const property = properties[key];
32
+ const type = typeOf(property);
33
+ if (type === "string") {
34
+ if (typeof value !== "string") throw new Error(`elicitation: "${key}" must be a string`);
35
+ if (Array.isArray(property.enum) && !property.enum.includes(value)) throw new Error(`elicitation: "${key}" is not an allowed value`);
36
+ if (value.length > MAX_VALUE) throw new Error(`elicitation: "${key}" is too long`);
37
+ } else if (type === "number") {
38
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`elicitation: "${key}" must be a number`);
39
+ if (property.minimum !== undefined && value < property.minimum) throw new Error(`elicitation: "${key}" is below minimum`);
40
+ if (property.maximum !== undefined && value > property.maximum) throw new Error(`elicitation: "${key}" is above maximum`);
41
+ } else if (type === "boolean") {
42
+ if (typeof value !== "boolean") throw new Error(`elicitation: "${key}" must be a boolean`);
43
+ } else {
44
+ throw new Error(`elicitation: unsupported field type for "${key}"`);
45
+ }
46
+ }
47
+ return content;
48
+ }
49
+
50
+ export class ElicitationQueue {
51
+ constructor({ timeoutMs = 5 * 60_000 } = {}) {
52
+ this.timeoutMs = timeoutMs;
53
+ this.pending = new Map();
54
+ this.closed = false;
55
+ }
56
+
57
+ create(server, params) {
58
+ if (this.closed) throw new Error("elicitation queue is closed");
59
+ if (this.pending.size >= MAX_PENDING) throw new Error("elicitation: too many pending requests");
60
+ const message = String(params?.message ?? "").trim();
61
+ if (!message) throw new Error("elicitation: message is required");
62
+ if (message.length > MAX_MESSAGE) throw new Error("elicitation: message is too long");
63
+ const schema = params?.requestedSchema && typeof params.requestedSchema === "object" ? params.requestedSchema : { type: "object", properties: {} };
64
+ const id = `elicit-${crypto.randomUUID()}`;
65
+ let resolve;
66
+ let reject;
67
+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
68
+ const timer = setTimeout(() => {
69
+ this.pending.delete(id);
70
+ reject(new Error("elicitation: timed out"));
71
+ }, this.timeoutMs);
72
+ timer.unref?.();
73
+ this.pending.set(id, { id, serverId: server.id, message, schema, resolve, reject, timer, createdAt: new Date().toISOString() });
74
+ return promise;
75
+ }
76
+
77
+ list() {
78
+ return [...this.pending.values()].map((entry) => ({
79
+ id: entry.id,
80
+ serverId: entry.serverId,
81
+ message: entry.message,
82
+ schema: entry.schema,
83
+ createdAt: entry.createdAt,
84
+ }));
85
+ }
86
+
87
+ respond(id, action, content) {
88
+ const entry = this.pending.get(String(id ?? ""));
89
+ if (!entry) throw new Error("elicitation: request not found");
90
+ if (!["accept", "decline", "cancel"].includes(action)) throw new Error("elicitation: invalid action");
91
+ let payload;
92
+ if (action === "accept") {
93
+ payload = { action: "accept", content: validateContent(entry.schema, content) };
94
+ } else {
95
+ payload = { action };
96
+ }
97
+ clearTimeout(entry.timer);
98
+ this.pending.delete(entry.id);
99
+ entry.resolve(payload);
100
+ return payload;
101
+ }
102
+
103
+ cancelAll(reason = "manager closed") {
104
+ for (const entry of this.pending.values()) {
105
+ clearTimeout(entry.timer);
106
+ entry.reject(new Error(`elicitation: ${reason}`));
107
+ }
108
+ this.pending.clear();
109
+ this.closed = true;
110
+ }
111
+ }
@@ -3,6 +3,8 @@
3
3
  */
4
4
  import { McpClient } from "./client.js";
5
5
  import { getAccessToken } from "./oauth.js";
6
+ import { runSampling } from "./sampling.js";
7
+ import { ElicitationQueue } from "./elicitation.js";
6
8
  import path from "node:path";
7
9
  import { pathToFileURL } from "node:url";
8
10
 
@@ -30,10 +32,12 @@ export class McpManager {
30
32
  this.tools = new Map();
31
33
  this.disposers = [];
32
34
  this.closed = false;
35
+ this.elicitations = new ElicitationQueue();
33
36
  }
34
37
 
35
38
  reopen() {
36
39
  this.closed = false;
40
+ if (this.elicitations.closed) this.elicitations = new ElicitationQueue();
37
41
  }
38
42
 
39
43
  toolName(serverId, toolName) {
@@ -44,28 +48,41 @@ export class McpManager {
44
48
  return `${base.slice(0, 60)}_${suffix}`;
45
49
  }
46
50
 
51
+ async handleServerRequest(server, message) {
52
+ const root = path.resolve(server.cwd || process.cwd());
53
+ if (message.method === "roots/list") {
54
+ return {
55
+ roots: [{
56
+ uri: pathToFileURL(root).href,
57
+ name: path.basename(root) || "workspace",
58
+ }],
59
+ };
60
+ }
61
+ if (message.method === "ping") return {};
62
+ if (message.method === "sampling/createMessage") {
63
+ return runSampling(this.ctx, server, message.params ?? {});
64
+ }
65
+ if (message.method === "elicitation/create") {
66
+ if (server.elicitation !== true) {
67
+ const error = new Error(`MCP ${server.id}: elicitation is disabled for this server`);
68
+ error.code = -32601;
69
+ throw error;
70
+ }
71
+ return this.elicitations.create(server, message.params ?? {});
72
+ }
73
+ const error = new Error(`${message.method}: not supported by DSH; elicitation requires explicit approval`);
74
+ error.code = -32601;
75
+ throw error;
76
+ }
77
+
47
78
  async connect(server) {
48
79
  if (this.closed) throw new Error("MCP manager is closed");
49
80
  const existing = this.clients.get(server.id);
50
81
  if (existing?.client?.connected) return existing;
51
- const root = path.resolve(server.cwd || process.cwd());
52
82
  const client = new McpClient({
53
83
  ...server,
54
84
  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
- },
85
+ onServerRequest: (message) => this.handleServerRequest(server, message),
69
86
  }, this.ctx.logger);
70
87
  try {
71
88
  await client.connect();
@@ -169,6 +186,7 @@ export class McpManager {
169
186
 
170
187
  async close() {
171
188
  this.closed = true;
189
+ this.elicitations.cancelAll();
172
190
  for (const dispose of this.disposers.splice(0)) {
173
191
  try { dispose(); } catch { /* best effort */ }
174
192
  }
@@ -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
+ }