dsh-control-mcp 0.1.0 → 0.2.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/lib/core.mjs CHANGED
@@ -9,6 +9,8 @@
9
9
  * bridge.stream(ns, method, args, signal) -> Promise<AsyncIterable<unknown>>
10
10
  * bridge.settings() -> { readOnly, exposeAllEndpoints, blockedEndpoints, maxResultBytes }
11
11
  * bridge.info() -> { dshVersion, pluginVersion }
12
+ * bridge.caller? -> { keyName, mode: 'full'|'scoped', access: 'read'|'prompt' } (per request)
13
+ * bridge.precheck?(endpoint) -> throws when the caller may not use the endpoint
12
14
  *
13
15
  * The Host entry (index.mjs) supplies the real bridge over ctx.typertGateway.
14
16
  */
@@ -200,7 +202,16 @@ export function catalog(bridge) {
200
202
  rows.push(descriptor);
201
203
  }
202
204
  rows.sort((a, b) => `${a.namespace}/${a.method}`.localeCompare(`${b.namespace}/${b.method}`));
203
- return rows.filter(descriptor => !isBlocked(settings, `${descriptor.namespace}/${descriptor.method}`));
205
+ return rows.filter(descriptor => {
206
+ const endpoint = `${descriptor.namespace}/${descriptor.method}`;
207
+ if (isBlocked(settings, endpoint)) return false;
208
+ try { bridge.precheck?.(endpoint); return true; } catch { return false; }
209
+ });
210
+ }
211
+
212
+ /** True for a key confined to chosen workspaces/sessions. */
213
+ export function isScoped(bridge) {
214
+ return bridge.caller?.mode === 'scoped';
204
215
  }
205
216
 
206
217
  function isBlocked(settings, endpoint) {
@@ -222,6 +233,7 @@ export function authorize(bridge, endpoint) {
222
233
  if (settings.readOnly === true && !isReadOnlyEndpoint(namespace, method)) {
223
234
  throw new ControlError('dsh-control/read-only', `${endpoint} changes harness state, and read-only mode is on. Turn off read-only mode on the plugin page to allow it.`, 403);
224
235
  }
236
+ bridge.precheck?.(endpoint);
225
237
  return { namespace, method };
226
238
  }
227
239
 
@@ -374,6 +386,7 @@ export const CURATED_TOOLS = Object.freeze([
374
386
  return {
375
387
  ...bridge.info(),
376
388
  readOnly: settings.readOnly === true,
389
+ ...(bridge.caller ? { key: bridge.caller } : {}),
377
390
  blockedEndpoints: settings.blockedEndpoints ?? [],
378
391
  namespaces,
379
392
  hint: 'Use dsh_list_endpoints to discover an endpoint, dsh_describe_endpoint for its argument schema, then dsh_call (unary) or dsh_stream (stream). Endpoints are the same Remote API the DSH Web UI uses.',
@@ -738,9 +751,22 @@ function endpointTools(bridge) {
738
751
  return tools;
739
752
  }
740
753
 
754
+ /**
755
+ * Tools that only make sense with harness-wide access; hidden from scoped
756
+ * keys (they would be refused anyway). dsh_call/dsh_stream stay: they reach
757
+ * every endpoint the key's scope allows.
758
+ */
759
+ const FULL_ACCESS_TOOLS = new Set(['dsh_list_plugins']);
760
+ /** Tools that change a session; hidden from read-only scoped keys. */
761
+ const PROMPT_TOOLS = new Set(['dsh_create_session', 'dsh_send_prompt', 'dsh_cancel_session']);
762
+
741
763
  export function listTools(bridge) {
742
764
  const settings = bridge.settings();
743
- const curated = CURATED_TOOLS.filter(tool => !(settings.readOnly === true && tool.readOnly === false));
765
+ const scoped = isScoped(bridge);
766
+ const readOnlyKey = scoped && bridge.caller?.access !== 'prompt';
767
+ const curated = CURATED_TOOLS.filter(tool => !(settings.readOnly === true && tool.readOnly === false))
768
+ .filter(tool => !(scoped && FULL_ACCESS_TOOLS.has(tool.name)))
769
+ .filter(tool => !(readOnlyKey && PROMPT_TOOLS.has(tool.name)));
744
770
  return settings.exposeAllEndpoints === true ? [...curated, ...endpointTools(bridge)] : [...curated];
745
771
  }
746
772
 
@@ -756,10 +782,11 @@ export function toolDefinition(tool) {
756
782
 
757
783
  export async function runTool(bridge, name, args = {}, signal) {
758
784
  if (typeof name !== 'string') throw new ControlError('dsh-control/tool-unknown', 'Tool name is required.', 400);
759
- const tool = listTools(bridge).find(candidate => candidate.name === name)
760
- ?? (bridge.settings().readOnly === true && CURATED_TOOLS.some(candidate => candidate.name === name)
761
- ? (() => { throw new ControlError('dsh-control/read-only', `${name} changes harness state, and read-only mode is on.`, 403); })()
762
- : undefined);
785
+ const tool = listTools(bridge).find(candidate => candidate.name === name);
786
+ if (tool === undefined && CURATED_TOOLS.some(candidate => candidate.name === name)) {
787
+ if (bridge.settings().readOnly === true) throw new ControlError('dsh-control/read-only', `${name} changes harness state, and read-only mode is on.`, 403);
788
+ if (isScoped(bridge)) throw new ControlError('dsh-control/key-scope', `${name} is not available to this key (${bridge.caller.access === 'prompt' ? 'it needs full access' : 'it has read-only access'}).`, 403);
789
+ }
763
790
  if (tool === undefined) throw new ControlError('dsh-control/tool-unknown', `Unknown tool ${name}.`, 404);
764
791
  if (!isRecord(args)) throw new ControlError('dsh-control/arguments-invalid', 'Tool arguments must be a JSON object.', 400);
765
792
  return tool.run(bridge, args, signal);
@@ -808,7 +835,7 @@ async function handleOne(bridge, message, signal) {
808
835
  protocolVersion,
809
836
  capabilities: { tools: { listChanged: false } },
810
837
  serverInfo: { name: PLUGIN_NAME, title: SERVER_TITLE, version: info.pluginVersion ?? '0.0.0' },
811
- instructions: `Controls the DeepSeek Harness this server runs in${bridge.settings().readOnly ? ' (read-only mode)' : ''}. Start with dsh_overview. dsh_list_sessions / dsh_create_session / dsh_send_prompt drive conversations; dsh_list_endpoints + dsh_call reach every other Web UI action (workspaces, models, plugins, schedules, goals, terminals, settings).`,
838
+ instructions: `Controls the DeepSeek Harness this server runs in${bridge.settings().readOnly ? ' (read-only mode)' : ''}${isScoped(bridge) ? `. This key ("${bridge.caller.keyName}") is limited to chosen workspaces and sessions with ${bridge.caller.access === 'prompt' ? 'read and prompt' : 'read-only'} access; lists only show what it may see` : ''}. Start with dsh_overview. dsh_list_sessions / dsh_create_session / dsh_send_prompt drive conversations; dsh_list_endpoints + dsh_call reach every other Web UI action (workspaces, models, plugins, schedules, goals, terminals, settings).`,
812
839
  },
813
840
  };
814
841
  }
package/lib/http.mjs CHANGED
@@ -11,10 +11,16 @@
11
11
  * GET {prefix}/api/v1/tools curated tool list
12
12
  * POST {prefix}/api/v1/tools/:name body = tool arguments -> {ok,value}
13
13
  * GET {prefix}/status public: which surfaces are enabled (no secrets)
14
- * GET {prefix}/token owner browser session only: current access token
15
- * POST {prefix}/token/rotate owner browser session only: mint a new token
14
+ * GET {prefix}/token owner session only: the built-in owner token
15
+ * POST {prefix}/token/rotate owner session only: mint a new owner token
16
+ * GET {prefix}/keys owner session only: API keys (never their tokens)
17
+ * POST {prefix}/keys owner session only: create a key -> { key, token } (token shown once)
18
+ * PATCH/DELETE {prefix}/keys/:id owner session only: edit or delete a key
19
+ * POST {prefix}/keys/:id/rotate owner session only: new token for a key
20
+ * GET {prefix}/scope-options owner session only: workspaces and sessions to choose from
16
21
  *
17
- * MCP and API calls need `Authorization: Bearer <token>`. The token routes
22
+ * MCP and API calls need `Authorization: Bearer <token>`: the owner token, or
23
+ * an API key (see lib/access.mjs), each enabled for MCP and/or the API. The owner routes
18
24
  * accept only the DSH browser session cookie (checked by ctx.connection) from
19
25
  * a same-origin request, so the GUI page can show the token to its owner.
20
26
  */
@@ -115,7 +121,15 @@ function requestSignal(req, res) {
115
121
  * @param {(req) => boolean} options.isOwnerBrowser - DSH browser-session check.
116
122
  * @param {(message: string) => void} [options.warn]
117
123
  */
118
- export function createHttpHandler({ bridge, getToken, rotateToken, isOwnerBrowser, warn = () => {}, prefix = ROUTE_PREFIX }) {
124
+ /**
125
+ * @param {object} options
126
+ * @param {object} options.bridge - owner bridge (lib/core.mjs).
127
+ * @param {(caller) => object} [options.bridgeFor] - bridge speaking for an API key; defaults to the owner bridge.
128
+ * @param {object} [options.keys] - key registry (lib/access.mjs); absent disables API keys.
129
+ * @param {(signal) => Promise<object>} [options.scopeOptions] - workspaces and sessions for the key editor.
130
+ * @param {() => boolean} [options.scopedSupported] - whether DSH can confine scoped keys.
131
+ */
132
+ export function createHttpHandler({ bridge, bridgeFor = () => bridge, keys, scopeOptions, scopedSupported = () => true, getToken, rotateToken, isOwnerBrowser, warn = () => {}, prefix = ROUTE_PREFIX }) {
119
133
  return async function handle(req, res) {
120
134
  let url;
121
135
  try {
@@ -146,6 +160,17 @@ export function createHttpHandler({ bridge, getToken, rotateToken, isOwnerBrowse
146
160
  return;
147
161
  }
148
162
 
163
+ // ── owner browser: API key management ──
164
+ if (path === '/keys' || path.startsWith('/keys/') || path === '/scope-options') {
165
+ if (!sameOrigin(req) || !isOwnerBrowser(req)) {
166
+ send(res, 401, { ok: false, error: { code: 'dsh-control/unauthorized', message: 'Open this from the DSH web GUI you are signed in to.' } });
167
+ return;
168
+ }
169
+ if (keys === undefined) throw new ControlError('dsh-control/keys-unavailable', 'API keys are unavailable.', 503);
170
+ await handleKeys(req, res, method, path, { keys, scopeOptions, scopedSupported });
171
+ return;
172
+ }
173
+
149
174
  const isMcp = path === '/mcp';
150
175
  const isApi = path === '/api/v1' || path.startsWith('/api/v1/');
151
176
  if (!isMcp && !isApi) { send(res, 404, { ok: false, error: { code: 'dsh-control/not-found', message: 'Not found.' } }); return; }
@@ -161,13 +186,34 @@ export function createHttpHandler({ bridge, getToken, rotateToken, isOwnerBrowse
161
186
  }
162
187
  // Browsers are never legitimate callers here; refuse cross-site pages outright.
163
188
  if (!sameOrigin(req)) { send(res, 403, { ok: false, error: { code: 'dsh-control/cross-origin', message: 'Cross-origin requests are refused.' } }); return; }
164
- if (!tokensEqual(getToken(), bearerOf(req))) {
165
- send(res, 401, { ok: false, error: { code: 'dsh-control/unauthorized', message: 'Missing or wrong bearer token. Copy it from Plugins → dsh-control-mcp.' } }, { 'www-authenticate': 'Bearer realm="dsh-control-mcp"' });
189
+ const presented = bearerOf(req);
190
+ let caller;
191
+ if (tokensEqual(getToken(), presented)) caller = { keyName: 'owner', mode: 'full', access: 'prompt', owner: true };
192
+ else {
193
+ const key = keys?.authenticate(presented);
194
+ if (key !== undefined) caller = { keyId: key.id, keyName: key.name, mode: key.mode, access: key.mode === 'full' ? 'prompt' : key.access, mcp: key.mcp, api: key.api, key };
195
+ }
196
+ if (caller === undefined) {
197
+ send(res, 401, { ok: false, error: { code: 'dsh-control/unauthorized', message: 'Missing, wrong, disabled or expired bearer token. Copy one from Plugins → dsh-control-mcp.' } }, { 'www-authenticate': 'Bearer realm="dsh-control-mcp"' });
166
198
  return;
167
199
  }
200
+ if (!caller.owner) {
201
+ if ((isMcp && caller.mcp !== true) || (isApi && caller.api !== true)) {
202
+ send(res, 403, { ok: false, error: { code: 'dsh-control/key-surface', message: `This key is not enabled for ${isMcp ? 'MCP' : 'the HTTP API'}. Change it in Plugins → dsh-control-mcp.` } });
203
+ return;
204
+ }
205
+ if (caller.mode === 'scoped' && !scopedSupported()) {
206
+ send(res, 403, { ok: false, error: { code: 'dsh-control/scoped-unsupported', message: 'Scoped keys need DSH 0.2.1 or later. Use a full-access key on this harness.' } });
207
+ return;
208
+ }
209
+ keys.touch(caller.key);
210
+ }
211
+ const { key: _key, ...publicCaller } = caller;
212
+ void _key;
213
+ const callerBridge = caller.owner ? bridge : bridgeFor(publicCaller);
168
214
 
169
- if (isMcp) { await handleMcpHttp(bridge, req, res, method); return; }
170
- await handleApi(bridge, req, res, method, path.slice('/api/v1'.length) || '/', url);
215
+ if (isMcp) { await handleMcpHttp(callerBridge, req, res, method); return; }
216
+ await handleApi(callerBridge, req, res, method, path.slice('/api/v1'.length) || '/', url);
171
217
  } catch (error) {
172
218
  const info = errorInfo(error);
173
219
  if (info.status >= 500) warn(`request ${method} ${url.pathname} failed: ${info.message}`);
@@ -244,6 +290,32 @@ async function handleApi(bridge, req, res, method, path, url) {
244
290
  send(res, 404, { ok: false, error: { code: 'dsh-control/not-found', message: `No API route ${method} ${path}.` } });
245
291
  }
246
292
 
293
+ async function handleKeys(req, res, method, path, { keys, scopeOptions, scopedSupported }) {
294
+ const ok = value => send(res, 200, { ok: true, value });
295
+ if (path === '/scope-options') {
296
+ if (method !== 'GET') { send(res, 405, { ok: false, error: { code: 'dsh-control/method-not-allowed', message: 'Use GET.' } }, { allow: 'GET' }); return; }
297
+ ok({ ...(scopeOptions ? await scopeOptions() : { workspaces: [], sessions: [] }), scopedSupported: scopedSupported() });
298
+ return;
299
+ }
300
+ if (path === '/keys') {
301
+ if (method === 'GET') { ok({ keys: keys.list(), scopedSupported: scopedSupported() }); return; }
302
+ if (method === 'POST') { ok(await keys.create(await readJson(req))); return; }
303
+ send(res, 405, { ok: false, error: { code: 'dsh-control/method-not-allowed', message: 'Use GET or POST.' } }, { allow: 'GET, POST' });
304
+ return;
305
+ }
306
+ const match = /^\/keys\/([A-Za-z0-9-]{1,64})(\/rotate)?$/.exec(path);
307
+ if (!match) { send(res, 404, { ok: false, error: { code: 'dsh-control/not-found', message: 'Not found.' } }); return; }
308
+ const [, id, rotate] = match;
309
+ if (rotate) {
310
+ if (method !== 'POST') { send(res, 405, { ok: false, error: { code: 'dsh-control/method-not-allowed', message: 'Use POST.' } }, { allow: 'POST' }); return; }
311
+ ok(await keys.rotate(id));
312
+ return;
313
+ }
314
+ if (method === 'PATCH') { ok({ key: await keys.update(id, await readJson(req)) }); return; }
315
+ if (method === 'DELETE') { await keys.remove(id); ok({ deleted: id }); return; }
316
+ send(res, 405, { ok: false, error: { code: 'dsh-control/method-not-allowed', message: 'Use PATCH or DELETE.' } }, { allow: 'PATCH, DELETE' });
317
+ }
318
+
247
319
  /** Live Server-Sent Events relay of one stream endpoint until the client disconnects or a limit is hit. */
248
320
  async function streamSse(bridge, res, endpoint, args, options, signal) {
249
321
  const maxItems = Number.isFinite(Number(options.maxItems)) ? Math.min(Math.max(1, Math.trunc(options.maxItems)), 100000) : 100000;
package/locale/en.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Harness control (MCP and API)",
4
- "description": "Control this DeepSeek Harness from MCP clients and an opt-in HTTP API: list and create sessions, send prompts and read replies, manage workspaces, models, plugins, schedules, goals, terminals and settings. Both surfaces are off until you turn them on in this plugin's page, and every call needs the access token shown there. Read-only mode and blocked endpoints narrow what clients may do.",
4
+ "description": "Control this DeepSeek Harness from MCP clients and an opt-in HTTP API: list and create sessions, send prompts and read replies, manage workspaces, models, plugins, schedules, goals, terminals and settings. Both surfaces are off until you turn them on in this plugin's page. Create an API key per client: full access, or only the workspaces and chats you choose, read only or read and prompt.",
5
5
  "detail": "docs/DETAIL.md"
6
6
  }
7
7
  }
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Harness 控制(MCP 与 API)",
4
- "description": "通过 MCP 客户端和可选的 HTTP API 控制当前 DeepSeek Harness:列出和创建会话、发送提示并读取回复、管理工作区、模型、插件、定时任务、目标、终端和设置。两种接口默认关闭,需在本插件页面中开启;每次调用都需要页面上显示的访问令牌。只读模式和禁用端点可限制客户端的权限。",
4
+ "description": "通过 MCP 客户端和可选的 HTTP API 控制当前 DeepSeek Harness:列出和创建会话、发送提示并读取回复、管理工作区、模型、插件、定时任务、目标、终端和设置。两种接口默认关闭,需在本插件页面中开启。可为每个客户端创建 API 密钥:完全访问,或仅限所选工作区和会话,只读或可读可发送。",
5
5
  "detail": "docs/DETAIL.md"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-control-mcp",
3
- "version": "0.1.0",
4
- "description": "Control DeepSeek Harness itself from MCP clients and an opt-in HTTP API: sessions, prompts, workspaces, models, plugins, schedules and every other Web UI action.",
3
+ "version": "0.2.0",
4
+ "description": "Control DeepSeek Harness itself from MCP clients and an opt-in HTTP API, with multiple API keys scoped to chosen workspaces and chats.",
5
5
  "author": "mrbeandev and contributors",
6
6
  "license": "MIT",
7
7
  "type": "module",
@@ -22,6 +22,7 @@
22
22
  "index.mjs",
23
23
  "lib/core.mjs",
24
24
  "lib/http.mjs",
25
+ "lib/access.mjs",
25
26
  "lib/client.js",
26
27
  "client/index.mjs",
27
28
  "bin/dsh-control-mcp.mjs",
@@ -66,7 +67,8 @@
66
67
  "verify": "npm run build && npm test && node scripts/check-release.mjs",
67
68
  "check": "npm run verify && npm pack --dry-run",
68
69
  "prepack": "npm run build && npm test",
69
- "prepublishOnly": "node scripts/check-release.mjs"
70
+ "prepublishOnly": "node scripts/check-release.mjs",
71
+ "test:scope": "node scripts/scope-smoke.mjs"
70
72
  },
71
73
  "peerDependencies": {
72
74
  "@deepseek-ai/dsh": ">=0.2.0-0 <0.3.0-0"