dsh-control-mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mrbeandev and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,203 @@
1
- # Temporary Holding Version
1
+ # dsh-control-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Control [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH) **itself** from MCP clients and an opt-in HTTP API.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/dsh-control-mcp.svg)](https://www.npmjs.com/package/dsh-control-mcp)
6
+ [![license](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
7
+ [![DSH](https://img.shields.io/badge/DSH-0.2.0--rc.1%20%E2%86%92%20%3C0.3.0-informational.svg)](#supported-dsh-versions)
8
+ [![Check](https://github.com/mrbeandev/dsh-control-mcp/actions/workflows/check.yml/badge.svg)](https://github.com/mrbeandev/dsh-control-mcp/actions/workflows/check.yml)
9
+
10
+ - **Source code:** [github.com/mrbeandev/dsh-control-mcp](https://github.com/mrbeandev/dsh-control-mcp)
11
+ - **npm package:** [npmjs.com/package/dsh-control-mcp](https://www.npmjs.com/package/dsh-control-mcp)
12
+ - **Issues:** [github.com/mrbeandev/dsh-control-mcp/issues](https://github.com/mrbeandev/dsh-control-mcp/issues)
13
+
14
+ Once you switch it on, an MCP client (Claude Code, Claude Desktop, Codex, Cursor, another DSH…) or your own script can list and create sessions, send prompts and read the replies, and manage workspaces, models, plugins, schedules, goals, terminals and settings. It speaks the same Remote API the DSH web GUI uses, so every call gets the same validation and has the same effect as the matching click in the GUI.
15
+
16
+ - **MCP server**: Streamable HTTP at `/dsh-control-mcp/mcp`, plus a bundled stdio bridge (`npx -y dsh-control-mcp`).
17
+ - **HTTP API**: JSON and Server-Sent Events at `/dsh-control-mcp/api/v1`.
18
+ - **Off by default.** Turn each surface on in **Plugins → dsh-control-mcp**; changes apply at once.
19
+ - **One bearer token** for both, kept in the DSH credential store. Show, copy and rotate it on the plugin page.
20
+ - **Read-only mode** and **blocked endpoint patterns** limit what clients may do.
21
+
22
+ ## Supported DSH versions
23
+
24
+ **Supported range: DSH `0.2.0-rc.1` up to (not including) `0.3.0`** (`engines.dsh: ">=0.2.0-0 <0.3.0-0"`, prereleases included). Check yours with `dsh --version`.
25
+
26
+ | DSH version | npm tag (at the time of this release) | Status |
27
+ |---|---|---|
28
+ | `0.2.3-alpha.2` | `alpha` | ✅ Tested |
29
+ | `0.2.2-rc.5` | `latest`, `next` | ✅ Tested |
30
+ | `0.2.2-rc.3` | — | ✅ Tested |
31
+ | `0.2.1-rc.5` | — | ✅ Tested |
32
+ | `0.2.0-rc.2` | — | ✅ Tested |
33
+ | other releases from `0.2.0-rc.1` up to `0.3.0` | — | ⚠️ Untested, expected to work |
34
+ | older than `0.2.0-rc.1` (0.1.x) | — | ❌ Not supported |
35
+ | `0.3.0` and newer (prereleases included) | — | ❌ Refused by DSH until tested |
36
+
37
+ "Tested" means the packed tarball was installed into a disposable DSH home for that exact version, and both the headless-Chrome page test and the live MCP/API test passed (see [LOCAL-SETUP.md](./LOCAL-SETUP.md)).
38
+
39
+ What differs between versions:
40
+
41
+ | Feature | 0.2.0 | 0.2.1 | 0.2.2+ |
42
+ |---|---|---|---|
43
+ | All endpoints, `dsh_call`, `dsh_stream`, HTTP API | ✅ | ✅ | ✅ |
44
+ | `dsh_send_prompt` with `wait` | ✅ polls `session/list` | ✅ polls `session/list` | ✅ native `session/wait` |
45
+ | Calls run as a dedicated peer that never answers approvals | — (runs as the operator) | ✅ | ✅ |
46
+ | Long detail page under Plugins | README only | README only | ✅ |
47
+
48
+ Each harness version exposes its own set of endpoints; `dsh_list_endpoints` always shows what *your* DSH offers.
49
+
50
+ **Node.js:** `^22.19.0` or `>=24.0.0`. The plugin has no runtime dependencies and needs no other community plugin.
51
+
52
+ ## Install
53
+
54
+ ```sh
55
+ dsh plugin --profile web add dsh-control-mcp
56
+ ```
57
+
58
+ Or open **Plugins → Add plugin** in the GUI and enter `dsh-control-mcp`. Restart DSH if the plugin page does not appear.
59
+
60
+ See [Supported DSH versions](#supported-dsh-versions).
61
+
62
+ ## Turn it on
63
+
64
+ 1. Open **Plugins → dsh-control-mcp**.
65
+ 2. Switch on **MCP server** and/or **HTTP API**. Changes apply immediately, without a restart.
66
+ 3. Under **Client setup**, copy the configuration for your client.
67
+
68
+ ### MCP over HTTP (Claude Code, Cursor, Codex, any Streamable HTTP client)
69
+
70
+ ```json
71
+ {
72
+ "mcpServers": {
73
+ "dsh-control": {
74
+ "type": "http",
75
+ "url": "http://127.0.0.1:3080/dsh-control-mcp/mcp",
76
+ "headers": { "Authorization": "Bearer <token>" }
77
+ }
78
+ }
79
+ }
80
+ ```
81
+
82
+ Claude Code: `claude mcp add --transport http dsh-control http://127.0.0.1:3080/dsh-control-mcp/mcp --header "Authorization: Bearer <token>"`.
83
+
84
+ ### MCP over stdio (Claude Desktop and other stdio-only clients)
85
+
86
+ ```json
87
+ {
88
+ "mcpServers": {
89
+ "dsh-control": {
90
+ "command": "npx",
91
+ "args": ["-y", "dsh-control-mcp"],
92
+ "env": {
93
+ "DSH_CONTROL_URL": "http://127.0.0.1:3080/dsh-control-mcp/mcp",
94
+ "DSH_CONTROL_TOKEN": "<token>"
95
+ }
96
+ }
97
+ }
98
+ }
99
+ ```
100
+
101
+ The bridge relays newline-delimited JSON-RPC from stdin to the HTTP endpoint. It uses only Node.js built-ins.
102
+
103
+ Use the address of *your* DSH web server; the plugin page fills it in for you.
104
+
105
+ ## MCP tools
106
+
107
+ | Tool | What it does |
108
+ |---|---|
109
+ | `dsh_overview` | Version, control mode, namespaces and endpoint counts. Start here. |
110
+ | `dsh_list_sessions` | Sessions with id, title, directory and running state. |
111
+ | `dsh_create_session` | New session in a directory or workspace, optionally with an agent preset. |
112
+ | `dsh_send_prompt` | Send a message (`queue` or `steer`); with `wait: true`, return the reply. |
113
+ | `dsh_wait_session` | Wait until a session is idle or needs input. |
114
+ | `dsh_read_session` | Latest messages as role/text pairs (or raw page records). |
115
+ | `dsh_cancel_session` | Stop the running turn. |
116
+ | `dsh_list_workspaces` | Workspaces with ids, paths and sessions. |
117
+ | `dsh_list_models` | Every model the harness can route to. |
118
+ | `dsh_list_plugins` | Plugins and their state. |
119
+ | `dsh_list_endpoints` | Every harness endpoint, filterable, optionally with JSON Schemas. |
120
+ | `dsh_describe_endpoint` | One endpoint's argument schema. |
121
+ | `dsh_call` | Call any unary endpoint, e.g. `pluginManager/setPluginEnabled`. |
122
+ | `dsh_stream` | Read a stream endpoint (e.g. `job/list`) for a bounded time. |
123
+
124
+ **One MCP tool per endpoint** on the plugin page also lists every endpoint (150–220 depending on DSH version and plugins) as its own `dsh__<namespace>__<method>` tool. Many clients handle the 14 tools above better.
125
+
126
+ In read-only mode, write tools are hidden and write calls are refused.
127
+
128
+ ## HTTP API
129
+
130
+ Every request needs `Authorization: Bearer <token>`. Responses are `{"ok": true, "value": …}` or `{"ok": false, "error": {"code", "message"}}` with a matching HTTP status.
131
+
132
+ | Method and path | Purpose |
133
+ |---|---|
134
+ | `GET /dsh-control-mcp/api/v1/info` | Harness and plugin versions, mode, endpoint count. |
135
+ | `GET /dsh-control-mcp/api/v1/endpoints?namespace=&q=&schemas=1` | Endpoint catalog. |
136
+ | `GET /dsh-control-mcp/api/v1/endpoints/<ns>/<method>` | One endpoint with argument and result schemas. |
137
+ | `POST /dsh-control-mcp/api/v1/call/<ns>/<method>` | Call a unary endpoint. Body: its named arguments. |
138
+ | `POST /dsh-control-mcp/api/v1/stream/<ns>/<method>` | Body `{"args", "maxItems", "timeoutMs"}`. Returns collected items, or a live SSE relay with `Accept: text/event-stream`. |
139
+ | `GET /dsh-control-mcp/api/v1/tools`, `POST …/tools/<name>` | The curated tools above, over HTTP. |
140
+ | `GET /dsh-control-mcp/status` | Unauthenticated: which surfaces are on. No secrets. |
141
+
142
+ ```sh
143
+ TOKEN=…; BASE=http://127.0.0.1:3080/dsh-control-mcp/api/v1
144
+ curl -s -H "Authorization: Bearer $TOKEN" $BASE/info
145
+ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
146
+ -d '{"_request":{}}' $BASE/call/session/list
147
+ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
148
+ -d '{"sessionId":"<id>","text":"Summarize the README","wait":true}' $BASE/tools/dsh_send_prompt
149
+ curl -N -X POST -H "Authorization: Bearer $TOKEN" -H 'accept: text/event-stream' -H 'content-type: application/json' \
150
+ -d '{"args":{}}' $BASE/stream/workspace/follow
151
+ ```
152
+
153
+ Endpoint arguments are named exactly as the harness declares them. Check `GET …/endpoints/<ns>/<method>`. An argument resolved by the `agent` lookup (for example `agentId`) takes a session id.
154
+
155
+ ## Security
156
+
157
+ - **Full control means full control.** A prompt can run tools and shell commands. Anyone with the token, and network access to DSH, can do what you can do in the GUI. Treat the token like a password, rotate it if it leaks, and prefer read-only mode when a client only needs to look.
158
+ - Both surfaces are off until you turn them on, and turning one off takes effect on the next request.
159
+ - Tokens are 256-bit random values compared in constant time. The plugin page reads the token through an owner-only route that accepts only your signed-in DSH browser session from the same origin.
160
+ - Requests with a cross-site `Origin` are refused, so a web page you visit cannot use the API even if it guesses the URL.
161
+ - Calls run as a dedicated in-process owner peer that **never answers approvals or questions**; those still appear in the GUI. (`userQuestions/answer` remains callable explicitly.)
162
+ - DSH binds to loopback by default. For remote clients use an SSH tunnel or DSH's own `trustedHosts`/TLS options. Do not expose it publicly without TLS.
163
+ - The Host side makes no outbound network requests.
164
+
165
+ ## How it works
166
+
167
+ The Host plugin (`index.mjs`) registers one prefix route, `/dsh-control-mcp`, on the DSH web server. Requests are dispatched through `ctx.typertGateway.invoke()` and `ctx.typertGateway.stream()` with an owner `Peer` created by `ctx.connection.createPeer()`. Endpoint discovery and argument schemas come from the live Typert registry (`ctx.typert.local.list()`), so endpoints added by other plugins appear automatically.
168
+
169
+ | Identity | Value |
170
+ |---|---|
171
+ | npm package, bundle, Loader entry id/name, Host plugin name | `dsh-control-mcp` |
172
+ | Client module id and `plugins.bundle.config` key | `dsh-control-mcp` |
173
+ | Web route prefix | `/dsh-control-mcp` |
174
+ | Credential record | `dsh-control-mcp/access-token` (grant) |
175
+ | Config fields (all volatile) | `mcpEnabled`, `apiEnabled`, `readOnly`, `exposeAllEndpoints`, `blockedEndpoints`, `maxResultBytes` |
176
+ | Log prefix | `dsh-control-mcp:` |
177
+ | Injected Host services | `typert`, `typertGateway`, `connection`, `webServer`; optional `credentials`, `connection.authentication` (DSH 0.2.3+) |
178
+ | Injected client packages | `@deepseek-ai/dsh-client-ui-settings`, `@deepseek-ai/dsh-client-ui-plugin-manager` |
179
+
180
+ ### Source layout
181
+
182
+ | Path | Role |
183
+ |---|---|
184
+ | `index.mjs` | Host entry: Config, token store, gateway bridge, route registration. |
185
+ | `lib/core.mjs` | Transport-independent catalog, policy, curated tools and MCP JSON-RPC. |
186
+ | `lib/http.mjs` | HTTP routing, auth, MCP Streamable HTTP, REST and SSE. |
187
+ | `client/index.mjs` | Plugin page source (source of truth). |
188
+ | `lib/client.js` | **Generated** by `npm run build` from `client/index.mjs`. Do not edit. |
189
+ | `bin/dsh-control-mcp.mjs` | stdio bridge. |
190
+
191
+ ## Development
192
+
193
+ ```sh
194
+ npm run verify # build client bundle, unit tests, release gate (metadata, identities, packed files)
195
+ npm pack --dry-run
196
+ scripts/version-matrix.sh ./dsh-control-mcp-0.1.0.tgz /path/to/dsh/bin [port] # one DSH version, end to end
197
+ ```
198
+
199
+ `LOCAL-SETUP.md` covers testing against a disposable DSH profile, including the live MCP/API smoke test (`npm run test:live`) and the headless-Chrome page test (`npm run test:e2e`).
200
+
201
+ ## License
202
+
203
+ MIT
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * stdio ⇄ HTTP bridge for MCP clients that only launch stdio servers.
4
+ *
5
+ * DSH_CONTROL_URL=http://127.0.0.1:3080/dsh-control-mcp/mcp \
6
+ * DSH_CONTROL_TOKEN=dshc_… npx -y dsh-control-mcp
7
+ *
8
+ * Reads newline-delimited JSON-RPC from stdin, POSTs each message to the
9
+ * harness's MCP endpoint with the bearer token, and writes the responses to
10
+ * stdout. Diagnostics go to stderr only. Node built-ins only.
11
+ */
12
+ import { createInterface } from 'node:readline';
13
+ import { realpathSync } from 'node:fs';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ const DEFAULT_URL = 'http://127.0.0.1:3080/dsh-control-mcp/mcp';
17
+
18
+ export function bridgeConfig(env = process.env, argv = process.argv.slice(2)) {
19
+ const flags = {};
20
+ for (let i = 0; i < argv.length; i += 1) {
21
+ const match = /^--(url|token)(?:=(.*))?$/.exec(argv[i]);
22
+ if (match) flags[match[1]] = match[2] ?? argv[++i];
23
+ else if (argv[i] === '--help' || argv[i] === '-h') flags.help = true;
24
+ }
25
+ return { url: flags.url ?? env.DSH_CONTROL_URL ?? DEFAULT_URL, token: flags.token ?? env.DSH_CONTROL_TOKEN ?? '', help: flags.help === true };
26
+ }
27
+
28
+ function errorResponse(id, message) {
29
+ return { jsonrpc: '2.0', id: id ?? null, error: { code: -32603, message } };
30
+ }
31
+
32
+ export async function forward(message, { url, token, fetchImpl = fetch, protocolVersion }) {
33
+ const response = await fetchImpl(url, {
34
+ method: 'POST',
35
+ headers: {
36
+ 'content-type': 'application/json',
37
+ accept: 'application/json, text/event-stream',
38
+ authorization: `Bearer ${token}`,
39
+ ...(protocolVersion ? { 'mcp-protocol-version': protocolVersion } : {}),
40
+ },
41
+ body: JSON.stringify(message),
42
+ });
43
+ if (response.status === 202) return undefined;
44
+ const text = await response.text();
45
+ if (!response.ok) {
46
+ let detail = text.slice(0, 300);
47
+ try { detail = JSON.parse(text)?.error?.message ?? detail; } catch { /* plain text */ }
48
+ const hint = response.status === 401 ? ' (check DSH_CONTROL_TOKEN)' : response.status === 404 ? ' (is MCP mode on in Plugins → dsh-control-mcp?)' : '';
49
+ throw new Error(`harness answered ${response.status}: ${detail}${hint}`);
50
+ }
51
+ return JSON.parse(text);
52
+ }
53
+
54
+ async function main() {
55
+ const config = bridgeConfig();
56
+ if (config.help) {
57
+ process.stderr.write('Usage: dsh-control-mcp [--url <mcp url>] [--token <token>]\nEnvironment: DSH_CONTROL_URL (default ' + DEFAULT_URL + '), DSH_CONTROL_TOKEN.\n');
58
+ return;
59
+ }
60
+ if (!config.token) process.stderr.write('dsh-control-mcp: DSH_CONTROL_TOKEN is not set; requests will be refused. Copy the token from Plugins → dsh-control-mcp.\n');
61
+ let protocolVersion;
62
+ const write = value => { if (value !== undefined) process.stdout.write(`${JSON.stringify(value)}\n`); };
63
+ let pending = 0;
64
+ let closing = false;
65
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
66
+ lines.on('line', async line => {
67
+ if (line.trim() === '') return;
68
+ let message;
69
+ try { message = JSON.parse(line); } catch { write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); return; }
70
+ pending += 1;
71
+ try {
72
+ const response = await forward(message, { ...config, protocolVersion });
73
+ if (response?.result?.protocolVersion) protocolVersion = response.result.protocolVersion;
74
+ write(response);
75
+ } catch (error) {
76
+ process.stderr.write(`dsh-control-mcp: ${error.message}\n`);
77
+ if (message && typeof message === 'object' && !Array.isArray(message) && 'id' in message && typeof message.method === 'string') write(errorResponse(message.id, error.message));
78
+ } finally {
79
+ pending -= 1;
80
+ if (closing && pending === 0) process.exit(0);
81
+ }
82
+ });
83
+ lines.on('close', () => { closing = true; if (pending === 0) process.exit(0); });
84
+ }
85
+
86
+ function isMain() {
87
+ try { return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); } catch { return false; }
88
+ }
89
+
90
+ if (isMain()) {
91
+ main().catch(error => { process.stderr.write(`dsh-control-mcp: ${error.message}\n`); process.exit(1); });
92
+ }
@@ -0,0 +1,284 @@
1
+ /**
2
+ * Self-contained factory: scripts/build-client.mjs embeds it in lib/client.js
3
+ * without bundling another React.
4
+ *
5
+ * Registers this plugin's page in the Plugins view (`plugins.bundle.config`,
6
+ * keyed by the package name): MCP and HTTP API switches, read-only mode,
7
+ * per-endpoint tools, blocked endpoints, the access token (show, copy,
8
+ * rotate) and ready-to-paste client configuration. Settings live in the Host
9
+ * entry's volatile Config, edited through the `configForms` service. The
10
+ * token is read from the Host's owner-only `/dsh-control-mcp/token` route.
11
+ */
12
+ export function createClientPlugin(require) {
13
+ const React = require('react');
14
+ const { createElement: h, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } = React;
15
+ const PACKAGE = 'dsh-control-mcp';
16
+ const ENTRY_ID = 'dsh-control-mcp';
17
+ const ROUTE = '/dsh-control-mcp';
18
+ const inject = ['slots'];
19
+ const SAVE_ERROR = 'Could not save this setting. It may have changed elsewhere; review the current value and try again.';
20
+ const SWITCHES = [
21
+ { field: 'mcpEnabled', label: 'MCP server', hint: 'Serve the MCP endpoint so MCP clients (Claude, Codex, Cursor, another DSH…) can control this harness.' },
22
+ { field: 'apiEnabled', label: 'HTTP API', hint: 'Serve a JSON and Server-Sent Events API for scripts and other programs.' },
23
+ { field: 'readOnly', label: 'Read-only mode', hint: 'Allow only calls that read. Prompts, creating sessions, plugin changes and every other change are refused.' },
24
+ { field: 'exposeAllEndpoints', label: 'One MCP tool per endpoint', hint: 'Also list every harness endpoint as its own MCP tool (about 200). The curated tools and dsh_call already reach all of them.' },
25
+ ];
26
+
27
+ function isRecord(value) {
28
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
29
+ }
30
+
31
+ /** Settings namespace of this plugin's Host entry among the served ones. */
32
+ function findEntryNamespace(namespaces) {
33
+ const ids = (Array.isArray(namespaces) ? namespaces : []).map(view => view?.ns).filter(id => typeof id === 'string');
34
+ return ids.find(id => id === `include:${ENTRY_ID}`)
35
+ ?? ids.find(id => id === ENTRY_ID)
36
+ ?? ids.find(id => id.endsWith(`:${ENTRY_ID}`));
37
+ }
38
+
39
+ /** Parse the blocked-endpoints textarea: one pattern per line or comma. */
40
+ function parseBlocked(text) {
41
+ const items = String(text ?? '').split(/[\n,]/).map(item => item.trim()).filter(Boolean);
42
+ const invalid = items.filter(item => !/^[A-Za-z0-9_*-]+\/[A-Za-z0-9_*-]+$/.test(item));
43
+ return { items: [...new Set(items)], invalid };
44
+ }
45
+
46
+ function originUrl(path) {
47
+ try {
48
+ return new URL(path, window.location.href).toString();
49
+ } catch {
50
+ return path;
51
+ }
52
+ }
53
+
54
+ function mcpJsonConfig(url, token) {
55
+ return JSON.stringify({ mcpServers: { 'dsh-control': { type: 'http', url, headers: { Authorization: `Bearer ${token}` } } } }, null, 2);
56
+ }
57
+
58
+ function stdioConfig(url, token) {
59
+ return JSON.stringify({ mcpServers: { 'dsh-control': { command: 'npx', args: ['-y', 'dsh-control-mcp'], env: { DSH_CONTROL_URL: url, DSH_CONTROL_TOKEN: token } } } }, null, 2);
60
+ }
61
+
62
+ async function tokenRequest(path, method) {
63
+ const response = await fetch(`${ROUTE}${path}`, { method, credentials: 'same-origin', headers: { accept: 'application/json' } });
64
+ const body = await response.json().catch(() => undefined);
65
+ if (!response.ok || body?.ok !== true || typeof body?.value?.token !== 'string') throw new Error('token request failed');
66
+ return body.value.token;
67
+ }
68
+
69
+ const styles = {
70
+ page: { display: 'flex', flexDirection: 'column', gap: '16px', minWidth: 0, fontSize: '13px', lineHeight: '20px', color: 'var(--dsw-alias-label-primary)' },
71
+ head: { display: 'flex', flexDirection: 'column', gap: '4px' },
72
+ title: { margin: 0, fontSize: '14px', fontWeight: 500, lineHeight: '20px' },
73
+ lead: { margin: 0, color: 'var(--dsw-alias-label-secondary)' },
74
+ card: { display: 'flex', flexDirection: 'column', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l3)', background: 'var(--dsw-alias-bg-layer-1)' },
75
+ row: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '16px', padding: '12px 14px', borderBottom: '.5px solid var(--dsw-alias-border-l2)' },
76
+ rowLast: { borderBottom: 0 },
77
+ rowText: { display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0 },
78
+ label: { fontSize: '13.5px', fontWeight: 500 },
79
+ hint: { margin: 0, fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-tertiary)' },
80
+ section: { display: 'flex', flexDirection: 'column', gap: '8px' },
81
+ sectionTitle: { margin: 0, fontSize: '13px', fontWeight: 500 },
82
+ status: { margin: 0, color: 'var(--dsw-alias-label-tertiary)' },
83
+ error: { margin: 0, color: 'var(--dsw-alias-state-error-primary)', overflowWrap: 'anywhere' },
84
+ ok: { margin: 0, color: 'var(--dsw-alias-state-success-primary, #39a869)' },
85
+ warn: { margin: 0, padding: '8px 12px', borderRadius: 'var(--dsw-radius-md, 8px)', background: 'color-mix(in srgb, var(--dsw-alias-state-warning-primary, #d08a00) 12%, transparent)', color: 'var(--dsw-alias-label-secondary)', fontSize: '12px', lineHeight: '18px' },
86
+ code: { margin: 0, padding: '8px 10px', borderRadius: 'var(--dsw-radius-md, 8px)', background: 'var(--dsw-alias-bg-layer-3)', border: '.5px solid var(--dsw-alias-border-l3)', fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)', fontSize: '12px', lineHeight: '18px', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' },
87
+ inline: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' },
88
+ input: { flex: 1, minWidth: '220px', height: '30px', padding: '0 10px', boxSizing: 'border-box', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l4)', background: 'var(--dsw-alias-bg-layer-3)', color: 'inherit', font: 'inherit', fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)', fontSize: '12px' },
89
+ textarea: { width: '100%', minHeight: '64px', padding: '8px 10px', boxSizing: 'border-box', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l4)', background: 'var(--dsw-alias-bg-layer-3)', color: 'inherit', font: 'inherit', fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)', fontSize: '12px', resize: 'vertical' },
90
+ button: { height: '28px', padding: '0 12px', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l4)', background: 'var(--dsw-alias-bg-layer-3)', color: 'inherit', font: 'inherit', fontSize: '12.5px', cursor: 'pointer' },
91
+ primary: { background: 'var(--dsw-alias-brand-primary)', borderColor: 'transparent', color: 'var(--dsw-alias-label-on-brand, #fff)' },
92
+ disabled: { opacity: 0.5, cursor: 'not-allowed' },
93
+ tabs: { display: 'flex', gap: '6px', flexWrap: 'wrap' },
94
+ };
95
+
96
+ function buttonStyle(primary, disabled) {
97
+ return { ...styles.button, ...primary ? styles.primary : {}, ...disabled ? styles.disabled : {} };
98
+ }
99
+
100
+ const emptyMirror = { view: undefined };
101
+ const unavailableSnapshot = { status: 'unavailable', value: undefined, revision: undefined, writable: false };
102
+ const noForm = { getSnapshot: () => unavailableSnapshot, subscribe: () => () => {}, mutate: async () => false };
103
+
104
+ function useStore(store, fallback) {
105
+ const subscribe = useCallback(listener => (store ? store.subscribe(listener) : () => {}), [store]);
106
+ const getSnapshot = useCallback(() => (store ? store.getSnapshot() : fallback), [store, fallback]);
107
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
108
+ }
109
+
110
+ function Switch({ id, checked, disabled, label, onChange }) {
111
+ return h('input', {
112
+ id, type: 'checkbox', role: 'switch', checked, disabled, 'aria-label': label,
113
+ style: { width: '18px', height: '18px', flex: 'none', marginTop: '2px', cursor: disabled ? 'not-allowed' : 'pointer' },
114
+ onChange: event => onChange(event.target.checked),
115
+ });
116
+ }
117
+
118
+ function CopyButton({ text, label = 'Copy', disabled }) {
119
+ const [copied, setCopied] = useState(false);
120
+ useEffect(() => { if (!copied) return undefined; const timer = setTimeout(() => setCopied(false), 1500); return () => clearTimeout(timer); }, [copied]);
121
+ return h('button', {
122
+ type: 'button', style: buttonStyle(false, disabled), disabled,
123
+ onClick: async () => { try { await navigator.clipboard.writeText(text); setCopied(true); } catch { /* clipboard blocked; text stays selectable */ } },
124
+ }, copied ? 'Copied' : label);
125
+ }
126
+
127
+ function TokenSection({ enabled }) {
128
+ const [token, setToken] = useState('');
129
+ const [state, setState] = useState('idle');
130
+ const [visible, setVisible] = useState(false);
131
+ const [tab, setTab] = useState('http');
132
+ const mounted = useRef(true);
133
+ useEffect(() => () => { mounted.current = false; }, []);
134
+
135
+ const load = useCallback(async () => {
136
+ setState('loading');
137
+ try {
138
+ const value = await tokenRequest('/token', 'GET');
139
+ if (mounted.current) { setToken(value); setState('ready'); }
140
+ } catch {
141
+ if (mounted.current) setState('error');
142
+ }
143
+ }, []);
144
+ useEffect(() => { if (enabled) void load(); }, [enabled, load]);
145
+
146
+ const rotate = async () => {
147
+ if (!window.confirm('Rotate the access token? Every MCP and API client using the current token stops working until you update it.')) return;
148
+ setState('loading');
149
+ try {
150
+ const value = await tokenRequest('/token/rotate', 'POST');
151
+ if (mounted.current) { setToken(value); setVisible(true); setState('rotated'); }
152
+ } catch {
153
+ if (mounted.current) setState('error');
154
+ }
155
+ };
156
+
157
+ if (!enabled) return h('p', { style: styles.status }, 'Turn on the MCP server or the HTTP API to see the access token and client setup.');
158
+ const mcpUrl = originUrl(`${ROUTE}/mcp`);
159
+ const apiUrl = originUrl(`${ROUTE}/api/v1`);
160
+ const shown = visible ? token : token.replace(/^(dshc_.{4}).*$/, '$1••••••••••••••••••••••');
161
+ const snippetsFor = value => ({
162
+ http: { label: 'MCP over HTTP', text: mcpJsonConfig(mcpUrl, value) },
163
+ stdio: { label: 'MCP over stdio', text: stdioConfig(mcpUrl, value) },
164
+ curl: { label: 'HTTP API', text: `curl -s -H 'Authorization: Bearer ${value}' ${apiUrl}/info\ncurl -s -X POST -H 'Authorization: Bearer ${value}' -H 'content-type: application/json' \\\n -d '{"_request":{}}' ${apiUrl}/call/session/list` },
165
+ });
166
+ // Displayed text follows the Show/Hide state; copying always uses the real token.
167
+ const snippets = snippetsFor(token);
168
+ const displayed = snippetsFor(shown);
169
+ return h('div', { style: styles.section },
170
+ h('h5', { style: styles.sectionTitle }, 'Access token'),
171
+ h('p', { style: styles.hint }, 'MCP and API clients send this as "Authorization: Bearer <token>". It grants full control of this harness (or read access in read-only mode). Keep it secret.'),
172
+ state === 'error' ? h('p', { role: 'alert', style: styles.error }, 'Could not read the token. Reload this page from the DSH web GUI you are signed in to.') : null,
173
+ h('div', { style: styles.inline },
174
+ h('input', { readOnly: true, value: state === 'loading' && !token ? 'Loading…' : shown, style: styles.input, 'aria-label': 'Access token', onFocus: event => event.target.select() }),
175
+ h('button', { type: 'button', style: buttonStyle(false, !token), disabled: !token, onClick: () => setVisible(!visible) }, visible ? 'Hide' : 'Show'),
176
+ h(CopyButton, { text: token, disabled: !token }),
177
+ h('button', { type: 'button', style: buttonStyle(false, state === 'loading'), disabled: state === 'loading', onClick: () => { void rotate(); } }, 'Rotate')),
178
+ state === 'rotated' ? h('p', { role: 'status', style: styles.ok }, 'New token issued. The old one no longer works.') : null,
179
+ h('h5', { style: { ...styles.sectionTitle, marginTop: '8px' } }, 'Client setup'),
180
+ h('div', { style: styles.tabs, role: 'tablist' }, Object.entries(snippets).map(([key, snippet]) => h('button', {
181
+ key, type: 'button', role: 'tab', 'aria-selected': tab === key, style: buttonStyle(tab === key, false), onClick: () => setTab(key),
182
+ }, snippet.label))),
183
+ h('pre', { style: styles.code, 'data-dsh-control-mcp-snippet': tab }, token ? displayed[tab].text : '…'),
184
+ h('div', { style: styles.inline }, h(CopyButton, { text: snippets[tab].text, label: 'Copy configuration', disabled: !token })),
185
+ h('p', { style: styles.hint }, `MCP endpoint: ${mcpUrl} · API base: ${apiUrl}. DSH listens on this machine only unless you started it with a trusted host; remote clients need a tunnel or a trusted host.`));
186
+ }
187
+
188
+ function ControlPage({ source }) {
189
+ const mirrorSnapshot = useStore(source.describe, emptyMirror);
190
+ const namespaces = mirrorSnapshot?.view?.namespaces ?? [];
191
+ const form = source.formFor(namespaces);
192
+ const snapshot = useStore(form ?? noForm, unavailableSnapshot);
193
+ const [pending, setPending] = useState('');
194
+ const [failure, setFailure] = useState('');
195
+ const [blockedDraft, setBlockedDraft] = useState(undefined);
196
+ const busy = useRef(false);
197
+
198
+ useEffect(() => { try { void source.describe?.ensure?.(); } catch { /* the mirror reports its own failure */ } }, [source]);
199
+
200
+ const value = isRecord(snapshot.value) ? snapshot.value : {};
201
+ const writable = snapshot.status === 'ready' && snapshot.writable === true && (snapshot.mode === undefined || snapshot.mode === 'host');
202
+ const storedBlocked = useMemo(() => (Array.isArray(value.blockedEndpoints) ? value.blockedEndpoints : []).join('\n'), [snapshot.value]);
203
+ const blockedText = blockedDraft ?? storedBlocked;
204
+ const blocked = parseBlocked(blockedText);
205
+
206
+ async function write(field, next) {
207
+ if (!writable || busy.current || form === undefined) return;
208
+ busy.current = true;
209
+ setPending(field);
210
+ setFailure('');
211
+ try {
212
+ await form.mutate([{ op: 'set', path: [field], value: next }], snapshot.revision);
213
+ const settled = form.getSnapshot();
214
+ if (settled.status !== 'ready' || JSON.stringify(settled.value?.[field]) !== JSON.stringify(next)) throw new Error('not confirmed');
215
+ if (field === 'blockedEndpoints') setBlockedDraft(undefined);
216
+ } catch {
217
+ setFailure(SAVE_ERROR);
218
+ } finally {
219
+ busy.current = false;
220
+ setPending('');
221
+ }
222
+ }
223
+
224
+ let status = null;
225
+ if (mirrorSnapshot?.view === undefined && form === undefined) status = 'Loading settings…';
226
+ else if (form === undefined || snapshot.status === 'unavailable') status = 'The dsh-control-mcp host plugin is not running, so these settings cannot be changed. Check the dsh startup output.';
227
+ else if (snapshot.status === 'loading') status = 'Loading settings…';
228
+ else if (!writable) status = 'These settings are read-only in this browser.';
229
+
230
+ const anyEnabled = value.mcpEnabled === true || value.apiEnabled === true;
231
+ return h('section', { style: styles.page, 'data-dsh-control-mcp': '' },
232
+ h('div', { style: styles.head },
233
+ h('h4', { style: styles.title }, 'Harness control'),
234
+ h('p', { style: styles.lead }, 'Let MCP clients and programs drive this harness through the same API the web GUI uses: sessions and prompts, workspaces, models, plugins, schedules, goals, terminals and settings. Both surfaces are off until you turn them on.')),
235
+ status === null ? null : h('p', { role: 'status', style: styles.status }, status),
236
+ h('div', { style: styles.card }, SWITCHES.map((item, index) => h('div', { key: item.field, style: { ...styles.row, ...index === SWITCHES.length - 1 ? styles.rowLast : {} } },
237
+ h('label', { htmlFor: `dsh-control-mcp-${item.field}`, style: styles.rowText },
238
+ h('span', { style: styles.label }, item.label),
239
+ h('span', { style: styles.hint }, item.hint)),
240
+ h(Switch, {
241
+ id: `dsh-control-mcp-${item.field}`, label: item.label, checked: value[item.field] === true,
242
+ disabled: !writable || pending !== '',
243
+ onChange: checked => { void write(item.field, checked); },
244
+ })))),
245
+ anyEnabled && value.readOnly !== true ? h('p', { style: styles.warn, role: 'note' }, 'Full control is on: a client with the token can run prompts (which run tools and shell commands), change plugins and settings, and read every session. Use read-only mode or blocked endpoints to narrow it.') : null,
246
+ failure ? h('p', { role: 'alert', style: styles.error }, failure) : null,
247
+ h('div', { style: styles.section },
248
+ h('label', { htmlFor: 'dsh-control-mcp-blocked', style: styles.sectionTitle }, 'Blocked endpoints'),
249
+ h('p', { style: styles.hint }, 'One pattern per line, "*" matches anything: account/*, pluginManager/removeBundle, */delete. Blocked endpoints are hidden and refused.'),
250
+ h('textarea', { id: 'dsh-control-mcp-blocked', style: styles.textarea, value: blockedText, disabled: !writable, spellCheck: false, onChange: event => setBlockedDraft(event.target.value) }),
251
+ blocked.invalid.length > 0 ? h('p', { role: 'alert', style: styles.error }, `Not a "namespace/method" pattern: ${blocked.invalid.join(', ')}`) : null,
252
+ h('div', { style: styles.inline },
253
+ h('button', {
254
+ type: 'button', style: buttonStyle(true, !writable || blockedDraft === undefined || blocked.invalid.length > 0 || pending !== ''),
255
+ disabled: !writable || blockedDraft === undefined || blocked.invalid.length > 0 || pending !== '',
256
+ onClick: () => { void write('blockedEndpoints', blocked.items); },
257
+ }, pending === 'blockedEndpoints' ? 'Saving…' : 'Save'),
258
+ blockedDraft !== undefined ? h('button', { type: 'button', style: buttonStyle(false, false), onClick: () => setBlockedDraft(undefined) }, 'Discard') : null)),
259
+ h(TokenSection, { enabled: anyEnabled }));
260
+ }
261
+
262
+ function apply(ctx) {
263
+ ctx.inject(['configForms'], child => {
264
+ const forms = child.configForms;
265
+ let cached;
266
+ const source = {
267
+ describe: forms.describe(),
268
+ formFor(namespaces) {
269
+ const ns = findEntryNamespace(namespaces);
270
+ if (ns === undefined) return undefined;
271
+ if (cached?.ns !== ns) cached = { ns, form: forms.get(ns) };
272
+ return cached.form;
273
+ },
274
+ };
275
+ child.slots.inject('plugins.bundle.config', () => child.slots.register({
276
+ name: 'plugins.bundle.config',
277
+ key: PACKAGE,
278
+ inject: () => ({ source }),
279
+ }, ControlPage));
280
+ });
281
+ }
282
+
283
+ return { inject, apply, findEntryNamespace, parseBlocked, mcpJsonConfig, stdioConfig };
284
+ }
@@ -0,0 +1,5 @@
1
+ # Mount the dsh-control-mcp Host plugin. MCP and API start switched off;
2
+ # turn them on in Plugins → dsh-control-mcp.
3
+ - insert:
4
+ - id: dsh-control-mcp
5
+ name: dsh-control-mcp
package/docs/DETAIL.md ADDED
@@ -0,0 +1,34 @@
1
+ # Harness control (MCP and API)
2
+
3
+ Lets MCP clients and other programs drive this DeepSeek Harness through the same API the web GUI uses.
4
+
5
+ ## What you can do
6
+
7
+ - List, create and cancel sessions; send prompts and wait for the reply; read session history.
8
+ - List workspaces, models and plugins; enable or disable plugins.
9
+ - Reach every other harness action (schedules, goals, terminals, jobs, settings, plugin installs, …) through `dsh_call` and `dsh_stream`, or through the HTTP API.
10
+
11
+ ## Turn it on
12
+
13
+ 1. Open **Plugins → dsh-control-mcp**.
14
+ 2. Switch on **MCP server**, **HTTP API**, or both. Both start off.
15
+ 3. Copy the access token and a ready-made client configuration from the same page.
16
+
17
+ | Surface | Address |
18
+ |---|---|
19
+ | MCP (Streamable HTTP) | `<harness URL>/dsh-control-mcp/mcp` |
20
+ | HTTP API | `<harness URL>/dsh-control-mcp/api/v1` |
21
+ | MCP over stdio | `npx -y dsh-control-mcp` with `DSH_CONTROL_URL` and `DSH_CONTROL_TOKEN` |
22
+
23
+ Every call needs `Authorization: Bearer <token>`. **Rotate** issues a new token and invalidates the old one.
24
+
25
+ ## Limit what clients may do
26
+
27
+ - **Read-only mode** refuses every call that changes harness state.
28
+ - **Blocked endpoints** hide and refuse endpoints by pattern, for example `account/*` or `pluginManager/removeBundle`.
29
+
30
+ ## Limitations
31
+
32
+ - With full control on, a client holding the token can run prompts, and prompts can run tools and shell commands. Treat the token like a password.
33
+ - DSH listens on this machine only unless it was started with a trusted host; remote clients need a tunnel or a trusted-host setup.
34
+ - Calls never answer approvals or questions on your behalf; those still appear in the GUI.