dsh-desktop-kit 2.8.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 CHANGED
@@ -1,5 +1,19 @@
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
+
10
+ ## 2.9.0 (2026-11-12)
11
+
12
+ - **Project instructions.** `AGENTS.md` и `CLAUDE.md` читаются иерархически: root → вложенные папки до cwd → `.dsh/AGENTS.md`; поддержан `@import`, лимиты глубины/размера/файлов, защита от выхода за проект и symlink-escape.
13
+ - **MCP roots.** HTTP/stdio MCP-сервер получает capability `roots` и ответ `roots/list` с корнем проекта; `ping` поддержан. Sampling/elicitation возвращают явный `-32601`, а не тихо игнорируются.
14
+ - **Тесты.** `instructions-tests`, обновлённый `mcp-manager-tests` (roots request/response).
15
+ - **Ограничение.** Sampling, elicitation, agent teams, marketplace, IDE bridge и OS sandbox в этот релиз не входят.
16
+
3
17
  ## 2.8.0 (2026-11-12)
4
18
 
5
19
  - **MCP OAuth 2.1.** HTTP-серверы: protected-resource discovery (RFC 9728), AS metadata (RFC 8414/OIDC), dynamic client registration (RFC 7591), authorization code + PKCE S256, `state`, loopback callback, `resource`/audience binding, refresh, logout.
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.8.0/docs/images/hero.png)
7
+ ![DSH Desktop Kit 2.7](https://unpkg.com/dsh-desktop-kit@2.10.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.
12
12
 
13
- ![MCP Settings](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-mcp-manager/screenshots/settings-1440.png)
13
+ ![MCP Settings](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-mcp-manager/screenshots/settings-1440.png)
14
14
 
15
- ![MCP на 390px](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-mcp-manager/screenshots/settings-390.png)
15
+ ![MCP на 390px](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-mcp-manager/screenshots/settings-390.png)
16
16
 
17
- ![Добавление MCP-сервера](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-mcp-manager/screenshots/modal-390.png)
17
+ ![Добавление MCP-сервера](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-mcp-manager/screenshots/modal-390.png)
18
18
 
19
19
  ## Права и субагенты
20
20
 
@@ -23,12 +23,13 @@
23
23
  - **Approval** — штатная карточка DSH: Allow once / Always allow / Reject.
24
24
  - **`.dsh/`** создаётся автоматически: agents, commands, rules, hooks, verify, mcp, PROJECT.md.
25
25
  - **Worktrees и фоновые агенты.** `project_worktree` создаёт ветку `dsh/<slug>` и отдельную папку `.dsh/worktrees/<slug>`; `project_agent ... worktree=auto background=true` запускает агента в изоляции, а страница **Агенты** показывает worktrees и очередь запусков с кнопкой «Остановить».
26
+ - **Инструкции проекта.** `AGENTS.md` и `CLAUDE.md` читаются иерархически (root → вложенные папки → `.dsh`) с `@import`; MCP roots сообщает серверу корень проекта.
26
27
 
27
- ![Агенты проекта](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-agent-extensions/screenshots/agents-1440.png)
28
+ ![Агенты проекта](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-agent-extensions/screenshots/agents-1440.png)
28
29
 
29
- ![Права и ограничения](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-guardrails/screenshots/permissions-1440.png)
30
+ ![Права и ограничения](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-guardrails/screenshots/permissions-1440.png)
30
31
 
31
- **v2.8.0** · MIT · проверено на DSH `0.2.1-rc.5` и `0.2.2-rc.1` (Windows 11) · без внешних зависимостей и телеметрии
32
+ **v2.10.0** · MIT · проверено на DSH `0.2.1-rc.5` и `0.2.2-rc.1` (Windows 11) · без внешних зависимостей и телеметрии
32
33
 
33
34
  **План развития:** [docs/ROADMAP-3.0.md](docs/ROADMAP-3.0.md) — Memory Fabric, семантическое
34
35
  слияние, локальный индекс памяти, шифрованные переносы, Memory Hub и npm trusted publishing.
@@ -116,27 +117,27 @@
116
117
  - перед каждой синхронизацией проверяется, что репозиторий всё ещё приватный;
117
118
  - секреты и PII вычищаются, домашние пути заменяются токеном `%DSH_HOME%`; LLM не вызывается — **0 токенов**.
118
119
 
119
- ![Настройки памяти проектов](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-memory-bridge/docs/images/settings-light.png)
120
+ ![Настройки памяти проектов](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-memory-bridge/docs/images/settings-light.png)
120
121
 
121
- ![Конфликты досье](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-memory-bridge/docs/images/conflicts.png)
122
+ ![Конфликты досье](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-memory-bridge/docs/images/conflicts.png)
122
123
 
123
124
  ## Скриншоты
124
125
 
125
126
  ### Skills Studio: каталог, стоимость и редактор
126
127
 
127
- ![Каталог навыков](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-gkb-ru-ui/screenshots/02-skills-1440-light.png)
128
+ ![Каталог навыков](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-gkb-ru-ui/screenshots/02-skills-1440-light.png)
128
129
 
129
- ![Редактор навыка](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-gkb-ru-ui/screenshots/03-skills-editor-1440-light.png)
130
+ ![Редактор навыка](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-gkb-ru-ui/screenshots/03-skills-editor-1440-light.png)
130
131
 
131
132
  ### Token Lab: куда уходит контекст
132
133
 
133
- ![Токен-лаборатория](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-token-lab/screenshots/01-token-lab-1440-light.png)
134
+ ![Токен-лаборатория](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-token-lab/screenshots/01-token-lab-1440-light.png)
134
135
 
135
136
  ### Тёмная тема и мобильный
136
137
 
137
- ![Тёмная тема](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-gkb-ru-ui/screenshots/04-skills-1440-dark.png)
138
+ ![Тёмная тема](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-gkb-ru-ui/screenshots/04-skills-1440-dark.png)
138
139
 
139
- ![Каталог навыков на 390 px](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-gkb-ru-ui/screenshots/05-skills-390-light.png)
140
+ ![Каталог навыков на 390 px](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-gkb-ru-ui/screenshots/05-skills-390-light.png)
140
141
 
141
142
  ## Окно-напоминание: пиковый тариф
142
143
 
@@ -146,11 +147,11 @@ DeepSeek включает двойной тариф в пиковые часы (
146
147
  - **в окне** — красная карточка: причина, границы окна в местном времени и UTC, живой отсчёт до конца и рекомендация, когда вернуться;
147
148
  - **после окна** — карточка исчезает; состояние всегда доступно через `window.__DSH_PEAK_GUARD__.state()`.
148
149
 
149
- ![Окно-напоминание: светлая тема](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-peak-guard/screenshots/03-peak-card-1440-light.png)
150
+ ![Окно-напоминание: светлая тема](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-peak-guard/screenshots/03-peak-card-1440-light.png)
150
151
 
151
- ![Окно-напоминание: тёмная тема](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-peak-guard/screenshots/04-peak-card-1440-dark.png)
152
+ ![Окно-напоминание: тёмная тема](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-peak-guard/screenshots/04-peak-card-1440-dark.png)
152
153
 
153
- ![Окно-напоминание на 390 px](https://unpkg.com/dsh-desktop-kit@2.8.0/plugins/dsh-peak-guard/screenshots/05-peak-card-390-light.png)
154
+ ![Окно-напоминание на 390 px](https://unpkg.com/dsh-desktop-kit@2.10.0/plugins/dsh-peak-guard/screenshots/05-peak-card-390-light.png)
154
155
 
155
156
  Подробности и настройки — [plugins/dsh-peak-guard/README.md](plugins/dsh-peak-guard/README.md).
156
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.8.0", parts: __partNames, errors: __kitErrors, ready: false };
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 не реализован.
@@ -0,0 +1,28 @@
1
+ # DSH Desktop Kit 2.9.0 — тест
2
+
3
+ Дата: 2026-11-12.
4
+
5
+ ## Project instructions
6
+
7
+ - `AGENTS.md` / `CLAUDE.md` в root, вложенных папках до cwd и `.dsh/`.
8
+ - `@path` imports: внутри проекта, глубина ≤ 5, ≤ 20 файлов, ≤ 32 КБ.
9
+ - Symlink за пределы проекта игнорируется с пометкой.
10
+ - Рендер в `<project-instructions>` с source-атрибутом.
11
+
12
+ ## MCP roots
13
+
14
+ - Клиент объявляет `roots` capability для stdio.
15
+ - `roots/list` → корень проекта (file URL + basename).
16
+ - `ping` → `{}`.
17
+ - `sampling/createMessage` и `elicitation/create` → `-32601` с понятным текстом.
18
+
19
+ ## Проверки
20
+
21
+ - `tools/instructions-tests.mjs` — OK.
22
+ - `tools/mcp-manager-tests.mjs` — OK, включая roots request.
23
+ - `npm test` — exit 0.
24
+ - `build:client` / `check:client` — OK.
25
+
26
+ ## Не входит
27
+
28
+ Sampling, elicitation UI, agent teams, marketplace, IDE bridge, OS sandbox.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-desktop-kit",
3
- "version": "2.8.0",
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/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"
@@ -17,6 +17,7 @@ import { createWorktree, removeWorktree, worktreeSummary } from "./lib/worktrees
17
17
  import { registerChildPolicyHook } from "./lib/policy.js";
18
18
  import { registerCommands } from "./lib/commands.js";
19
19
  import { registerAgentApi } from "./lib/api.js";
20
+ import { renderProjectInstructions } from "./lib/instructions.js";
20
21
  import { ensureGlobalScaffold, ensureProjectScaffold } from "./lib/scaffold.js";
21
22
  import { findDshDir, loadAgents, projectFor } from "./lib/project.js";
22
23
 
@@ -219,6 +220,24 @@ export function apply(ctx) {
219
220
  ctx.logger?.warn?.(`[agent-extensions] system prompt registration failed: ${error instanceof Error ? error.message : String(error)}`);
220
221
  }
221
222
 
223
+ try {
224
+ ctx.systemPrompt.context({
225
+ name: "dsh-agent-extensions: project instructions",
226
+ order: 135,
227
+ interpolate: false,
228
+ required: false,
229
+ text: (assemblyContext) => {
230
+ try {
231
+ return renderProjectInstructions(assemblyContext?.agent?.session?.header?.cwd);
232
+ } catch {
233
+ return "";
234
+ }
235
+ },
236
+ });
237
+ } catch (error) {
238
+ ctx.logger?.warn?.(`[agent-extensions] instruction prompt skipped: ${error instanceof Error ? error.message : String(error)}`);
239
+ }
240
+
222
241
  try {
223
242
  ctx.inject(["commands"], (child) => registerCommands(child));
224
243
  } catch (error) {
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Claude Code-style project instructions.
3
+ *
4
+ * Order (lowest → highest priority):
5
+ * <root>/AGENTS.md, <root>/CLAUDE.md,
6
+ * <root>/.dsh/AGENTS.md,
7
+ * nested AGENTS.md/CLAUDE.md from root to session cwd.
8
+ *
9
+ * `@path` lines import another file. Imports stay inside the project root,
10
+ * are depth-limited and total-size limited.
11
+ */
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import { projectFor } from "./project.js";
15
+
16
+ const MAX_DEPTH = 5;
17
+ const MAX_BYTES = 32_000;
18
+ const MAX_FILES = 20;
19
+ const IMPORT = /^\s*@([^\s#]+)\s*$/u;
20
+
21
+ function inside(root, file) {
22
+ const relative = path.relative(root, path.resolve(file));
23
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
24
+ }
25
+
26
+ function readBounded(file, remaining) {
27
+ const stat = fs.statSync(file);
28
+ if (!stat.isFile()) return "";
29
+ if (stat.size > remaining) throw new Error(`instructions: file too large: ${file}`);
30
+ return fs.readFileSync(file, "utf8");
31
+ }
32
+
33
+ function expand(file, root, state, depth = 0, realRoot = root) {
34
+ if (depth > MAX_DEPTH) return `[import depth limit: ${file}]`;
35
+ if (state.files.size >= MAX_FILES) return `[import file limit reached: ${file}]`;
36
+ const resolved = path.resolve(file);
37
+ if (!inside(root, resolved)) return `[import outside project ignored: ${file}]`;
38
+ let real;
39
+ try {
40
+ real = fs.realpathSync(resolved);
41
+ } catch {
42
+ return `[unreadable import: ${path.relative(root, resolved)}]`;
43
+ }
44
+ if (!inside(realRoot, real)) return `[import symlink outside project ignored: ${file}]`;
45
+ if (state.files.has(real)) return `[already imported: ${path.relative(root, real)}]`;
46
+ state.files.add(real);
47
+ let text;
48
+ try {
49
+ text = readBounded(real, MAX_BYTES - state.bytes);
50
+ } catch (error) {
51
+ return `[unreadable import: ${path.relative(root, real)} — ${error instanceof Error ? error.message : String(error)}]`;
52
+ }
53
+ state.bytes += Buffer.byteLength(text, "utf8");
54
+ return text.split(/\r?\n/u).map((line) => {
55
+ const match = IMPORT.exec(line);
56
+ if (!match) return line;
57
+ const next = path.resolve(path.dirname(real), match[1]);
58
+ if (!inside(root, next)) return `[import outside project ignored: ${match[1]}]`;
59
+ return expand(next, root, state, depth + 1, realRoot);
60
+ }).join("\n");
61
+ }
62
+
63
+ export function loadProjectInstructions(cwd) {
64
+ const project = projectFor(cwd);
65
+ const root = project.root;
66
+ const candidates = [];
67
+ const seen = new Set();
68
+ const add = (file, scope) => {
69
+ const resolved = path.resolve(file);
70
+ if (seen.has(resolved) || !fs.existsSync(resolved)) return;
71
+ seen.add(resolved);
72
+ candidates.push({ file: resolved, scope });
73
+ };
74
+ const dirs = [];
75
+ let current = path.resolve(cwd || root);
76
+ while (inside(root, current)) {
77
+ dirs.unshift(current);
78
+ if (current === path.resolve(root)) break;
79
+ const parent = path.dirname(current);
80
+ if (parent === current) break;
81
+ current = parent;
82
+ }
83
+ for (const dir of dirs) {
84
+ for (const name of ["AGENTS.md", "CLAUDE.md"]) add(path.join(dir, name), dir === path.resolve(root) ? "project" : "nested");
85
+ }
86
+ for (const name of ["AGENTS.md", "CLAUDE.md"]) {
87
+ add(path.join(project.dsh ?? path.join(root, ".dsh"), name), "dsh");
88
+ }
89
+ const state = { files: new Set(), bytes: 0 };
90
+ const sections = [];
91
+ const realRoot = (() => { try { return fs.realpathSync(root); } catch { return root; } })();
92
+ for (const item of candidates) {
93
+ const text = expand(item.file, root, state, 0, realRoot);
94
+ if (text.trim().length > 0) sections.push({ ...item, text: text.trim() });
95
+ }
96
+ return { root, sections };
97
+ }
98
+
99
+ export function renderProjectInstructions(cwd) {
100
+ const result = loadProjectInstructions(cwd);
101
+ if (result.sections.length === 0) return "";
102
+ const body = result.sections.map((section) => `<instructions source="${section.scope}:${path.relative(result.root, section.file).split(path.sep).join("/")}">\n${section.text}\n</instructions>`).join("\n");
103
+ return `<project-instructions>\n${body}\n</project-instructions>`;
104
+ }
@@ -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
  ![MCP Settings](screenshots/settings-1440.png)
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
- - Нет sampling: сервер не может запросить генерацию у модели.
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 = {};
@@ -29,6 +29,11 @@ class StdioTransport {
29
29
  this.child = null;
30
30
  this.closed = false;
31
31
  this.stderr = "";
32
+ this.requestHandler = null;
33
+ }
34
+
35
+ setRequestHandler(handler) {
36
+ this.requestHandler = handler;
32
37
  }
33
38
 
34
39
  async start() {
@@ -42,6 +47,18 @@ class StdioTransport {
42
47
  reader.on("line", (line) => {
43
48
  const message = parseJsonRpc(line);
44
49
  if (!message) return;
50
+ if (message.method !== undefined && message.id !== undefined) {
51
+ const handler = this.requestHandler;
52
+ Promise.resolve()
53
+ .then(() => handler ? handler(message) : Promise.reject(Object.assign(new Error("method not supported"), { code: -32601 })))
54
+ .then((result) => {
55
+ this.child?.stdin?.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, result: result ?? {} })}\n`);
56
+ })
57
+ .catch((error) => {
58
+ this.child?.stdin?.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: error?.code ?? -32603, message: error instanceof Error ? error.message : String(error) } })}\n`);
59
+ });
60
+ return;
61
+ }
45
62
  if (message.id !== undefined && this.pending.has(String(message.id))) {
46
63
  const waiter = this.pending.get(String(message.id));
47
64
  this.pending.delete(String(message.id));
@@ -172,11 +189,15 @@ export class McpClient {
172
189
 
173
190
  async connect() {
174
191
  await this.transport.start?.();
192
+ const canHandle = typeof this.transport.setRequestHandler === "function" && typeof this.config.onServerRequest === "function";
193
+ if (canHandle) this.transport.setRequestHandler(this.config.onServerRequest);
175
194
  const result = await this.transport.request(
176
195
  "initialize",
177
196
  {
178
197
  protocolVersion: PROTOCOL_VERSION,
179
- capabilities: {},
198
+ capabilities: canHandle
199
+ ? { roots: { listChanged: false }, ...(this.config.sampling === true ? { sampling: {} } : {}) }
200
+ : {},
180
201
  clientInfo: { name: "dsh-mcp-manager", version: "1.0.0" },
181
202
  },
182
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,9 @@
3
3
  */
4
4
  import { McpClient } from "./client.js";
5
5
  import { getAccessToken } from "./oauth.js";
6
+ import { runSampling } from "./sampling.js";
7
+ import path from "node:path";
8
+ import { pathToFileURL } from "node:url";
6
9
 
7
10
  function sanitize(value) {
8
11
  return String(value ?? "").replace(/[^A-Za-z0-9_-]+/gu, "_").replace(/^_+|_+$/gu, "").slice(0, 48);
@@ -42,6 +45,25 @@ export class McpManager {
42
45
  return `${base.slice(0, 60)}_${suffix}`;
43
46
  }
44
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
+
45
67
  async connect(server) {
46
68
  if (this.closed) throw new Error("MCP manager is closed");
47
69
  const existing = this.clients.get(server.id);
@@ -49,6 +71,7 @@ export class McpManager {
49
71
  const client = new McpClient({
50
72
  ...server,
51
73
  tokenProvider: server.url ? () => getAccessToken(server.id, { resource: server.url }).catch(() => null) : undefined,
74
+ onServerRequest: (message) => this.handleServerRequest(server, message),
52
75
  }, this.ctx.logger);
53
76
  try {
54
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
+ }