dsh-windows-parallel-mcp 0.6.0 → 0.8.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.
@@ -0,0 +1,350 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lib/mcp-server.mjs -- the 0.8.0 second delivery form: the same engine over MCP stdio.
4
+ *
5
+ * WHY THIS FILE EXISTS AND NOTHING UNDER src/engine/ CHANGED. The MCP Registry accepts MCP servers
6
+ * only, and DSH can bridge an MCP server through @deepseek-ai/dsh-mcp-client, so one implementation
7
+ * reaches two channels. That is a deliberate reversal of the 2026-11-19 decision (form = A, no MCP),
8
+ * and the reversal is safe precisely because nothing here re-implements anything: the tool object is
9
+ * the one `apply()` already builds for the host half, so `toRequest()`, the gate order, the refusal
10
+ * vocabulary, the audit line and `format()` are shared rather than copied. A second implementation of
11
+ * a permission is a permission that can be reached around by using the other copy -- which is also why
12
+ * the schema below is GENERATED from src/schema/tools.json instead of transcribed (risk R6).
13
+ *
14
+ * FOUR THINGS THIS FILE OWNS, none of which is an action:
15
+ * 1. JSON-RPC 2.0 framing over stdio -- one JSON object per line, replies keyed by `id`, so two
16
+ * calls in flight may answer in any order (the worker is asynchronous; assuming FIFO would be
17
+ * inventing a second protocol).
18
+ * 2. stdout is the protocol channel. Anything that is not a protocol line goes to stderr, which is
19
+ * why the plugin is handed a logger that writes there: `ctx.logger ?? console` in lib/index.js
20
+ * would otherwise print a warning INTO the JSON stream and break every client reading it.
21
+ * 3. The transport never dies on bad input: a non-JSON line gets a -32700 with a null id, an unknown
22
+ * method gets -32601, and a notification (no id) gets no reply at all -- answering a notification
23
+ * makes a client wait for a response it never asked for.
24
+ * 4. Settings come from the ENVIRONMENT, never from the call. A client that could raise its own
25
+ * `policy` ceiling or add itself to `appLaunchAllow` would make the authorization model decorative;
26
+ * the process owner configures this server exactly the way a DSH profile configures the plugin.
27
+ */
28
+ import { readFileSync } from 'node:fs';
29
+ import { createInterface } from 'node:readline';
30
+ import { fileURLToPath } from 'node:url';
31
+ import { dirname, join } from 'node:path';
32
+
33
+ import { apply } from './index.js';
34
+ import { POLICY_LEVELS } from './policy.js';
35
+
36
+ const here = dirname(fileURLToPath(import.meta.url));
37
+ const pkg = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8'));
38
+
39
+ /**
40
+ * Protocol revisions this server is willing to speak, newest first. Verified against the constants of
41
+ * the MCP SDK this machine's DSH install ships (@modelcontextprotocol/core 2.2.0: latest 2025-11-25,
42
+ * supported back through 2025-06-18). The list is ours on purpose -- a zero-dependency server cannot
43
+ * read the client's table at run time -- which is exactly why the negotiation below answers with the
44
+ * newest entry we know rather than echoing anything it is handed.
45
+ */
46
+ const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
47
+ const SERVER_NAME = 'wpm-mcp';
48
+ /** The single tool name. One tool with an action discriminator, in this form too: the token argument
49
+ * from 0.5.0 does not weaken over a transport, and `tools/call` accepts an arbitrary argument object. */
50
+ const MCP_TOOL_NAME = 'wpm';
51
+
52
+ const log = (/** @type {any[]} */ ...a) => process.stderr.write(a.map((x) => String(x)).join(' ') + '\n');
53
+
54
+ // ---- the contract, read once ------------------------------------------------------------
55
+ /**
56
+ * The shape this file reads out of src/schema/tools.json -- and deliberately only the parts it reads.
57
+ * It is not a second description of the contract: nothing here names an action, a parameter or a code.
58
+ * @typedef {Object} ContractAction
59
+ * @property {string} name
60
+ * @property {string} action
61
+ * @property {string} requiresTier
62
+ * @property {Record<string, string>} [requiresTierFor]
63
+ * @property {string} description
64
+ * @property {ContractSchema} inputSchema
65
+ * @property {Array<{code: string}>} [refusals]
66
+ *
67
+ * @typedef {Object} ContractSchema
68
+ * @property {Record<string, any>} [properties]
69
+ * @property {string[]} [required]
70
+ * @property {boolean} [additionalProperties]
71
+ *
72
+ * @typedef {Object} Contract
73
+ * @property {Array<ContractAction>} tools
74
+ * @property {Array<{code: string, layer?: string, summary: string}>} refusals
75
+ * @property {string[]} notes
76
+ * @property {{form?: string, tool?: string, bin?: string, entry?: string, discriminator?: string, schemaSource?: string, implementationSource?: string, settingsSource?: string, imageContent?: string, transportDiscipline?: string, reversal?: string, why?: string}} [mcpProjection]
77
+ * @property {Record<string, Record<string, string>>} [hostProjection]
78
+ */
79
+ /**
80
+ * Parsed from src/schema/tools.json at start-up. This is the only copy of the action surface in the
81
+ * process: if a field is renamed there, `tools/list` follows it, because nothing below spells out an
82
+ * action name, a parameter name, or a refusal code. scripts/check-mcp-schema.mjs is the gate that
83
+ * keeps that claim true (and has been seen red on a mutated schema).
84
+ */
85
+ /** @type {Contract} */
86
+ const schema = JSON.parse(readFileSync(join(here, '..', 'src', 'schema', 'tools.json'), 'utf8'));
87
+
88
+ /** First sentence of a description -- the contract file writes those as one paragraph per action. */
89
+ const lead = (/** @type {string} */ s) => String(s).split(/(?<=\.)\s/)[0] || String(s);
90
+
91
+ /** @returns {Record<string, any>} */
92
+ function buildInputSchema() {
93
+ /** @type {Array<Record<string, any>>} */
94
+ const branches = schema.tools.map((t) => ({
95
+ type: 'object',
96
+ description: `${t.name}: ${t.description}`,
97
+ properties: {
98
+ action: { const: t.action, description: `${t.action} -- requires the '${t.requiresTier}' rung of the policy ladder.` },
99
+ ...t.inputSchema.properties,
100
+ },
101
+ required: ['action', ...(t.inputSchema.required ?? [])],
102
+ additionalProperties: t.inputSchema.additionalProperties === true,
103
+ }));
104
+ return {
105
+ type: 'object',
106
+ properties: {
107
+ action: { type: 'string', enum: schema.tools.map((t) => t.action), description: 'Which of the declared actions to run. Each action carries its own required arguments; the branches below are generated from src/schema/tools.json.' },
108
+ },
109
+ required: ['action'],
110
+ oneOf: branches,
111
+ };
112
+ }
113
+
114
+ /** @returns {string} */
115
+ function buildDescription() {
116
+ const lines = [
117
+ `Drive one Windows window through ${schema.tools.length} declared actions, choosing the cheapest door that can reach the target and reporting what actually happened rather than what was sent.`,
118
+ 'ACTIONS (name | policy rung | what it does):',
119
+ ...schema.tools.map((t) => ` - action=${t.action} | ${t.requiresTier}${t.requiresTierFor ? ` (per op: ${Object.entries(t.requiresTierFor).map(([k, v]) => `${k}=${v}`).join(', ')})` : ''} | ${lead(t.description)}`),
120
+ 'REFUSAL CODES (the refusal names which switch or which fact, so the next step is not guesswork):',
121
+ ...schema.refusals.map((r) => ` - ${r.code}: ${r.summary}`),
122
+ `Authorization is one ceiling (\`policy\`: ${POLICY_LEVELS.join('|')}) over the rungs above, and it is set by whoever starts this process, never by a call.`,
123
+ 'Every action -- allowed or refused -- appends one JSONL row to the audit log, which records decisions and lengths and never the content of what was typed or copied.',
124
+ ...schema.notes.map((n) => `NOTE: ${n}`),
125
+ ];
126
+ return lines.join('\n');
127
+ }
128
+
129
+ const mcpTool = {
130
+ name: MCP_TOOL_NAME,
131
+ title: 'Windows Parallel',
132
+ description: buildDescription(),
133
+ inputSchema: buildInputSchema(),
134
+ };
135
+
136
+ // ---- the tool, from the same apply() the DSH form uses ----------------------------------
137
+ /**
138
+ * `apply(ctx, config)` is the whole host half. It expects `ctx.tools.register`, an optional logger and
139
+ * an optional `on('dispose')`. Under MCP there is no host to dispose us, so the stdin close handler
140
+ * calls the registered disposers itself -- otherwise the resident PowerShell worker outlives the server.
141
+ */
142
+ /** @type {Array<{execute: (args: any, exec?: any) => Promise<any>}>} */
143
+ const registered = [];
144
+ /** @type {Array<() => any>} */
145
+ const disposers = [];
146
+ apply({
147
+ tools: { register: (t) => registered.push(t) },
148
+ // stderr, always: stdout carries the protocol and one stray console.log would corrupt it.
149
+ logger: { info: (m) => log('[info]', m), warn: (m) => log('[warn]', m) },
150
+ on: (event, fn) => { if (event === 'dispose') disposers.push(fn); },
151
+ }, settingsFromEnv());
152
+ if (registered.length !== 1) throw new Error(`expected exactly one registered tool, got ${registered.length}`);
153
+ const tool = registered[0];
154
+
155
+ /**
156
+ * Environment to plugin settings, mapping ONLY the keys that are actually present. Defaults live in
157
+ * lib/index.js and are not repeated here: a second copy of a default is a default that drifts.
158
+ * @returns {Record<string, any>}
159
+ */
160
+ function settingsFromEnv() {
161
+ /** @type {Record<string, [name: string, kind: 'bool'|'int'|'str'|'list']>} */
162
+ const MAP = {
163
+ WPM_ENABLED: ['enabled', 'bool'],
164
+ WPM_SETTLE_MS: ['settleMs', 'int'],
165
+ WPM_REQUEST_TIMEOUT_MS: ['requestTimeoutMs', 'int'],
166
+ WPM_POWERSHELL_PATH: ['powershellPath', 'str'],
167
+ WPM_OVERLAY: ['overlay', 'bool'],
168
+ WPM_LOG_WORKER_STDERR: ['logWorkerStderr', 'bool'],
169
+ WPM_TAKEOVER_ALLOWED: ['takeoverAllowed', 'bool'],
170
+ WPM_KEY_INJECT_ALLOWED: ['keyInjectAllowed', 'bool'],
171
+ WPM_TAKEOVER_MAX_MS: ['takeoverMaxMs', 'int'],
172
+ WPM_TAKEOVER_ARM_MS: ['takeoverArmMs', 'int'],
173
+ WPM_SNAPSHOT_MAX_ELEMENTS: ['snapshotMaxElements', 'int'],
174
+ WPM_SCREENSHOT_MAX_WIDTH: ['screenshotMaxWidth', 'int'],
175
+ WPM_SHOTS_KEEP: ['shotsKeep', 'int'],
176
+ WPM_POLICY: ['policy', 'str'],
177
+ WPM_POLICY_IDLE_MS: ['policyIdleMs', 'int'],
178
+ WPM_AUDIT_KEEP: ['auditKeep', 'int'],
179
+ WPM_APP_LAUNCH_ALLOWED: ['appLaunchAllowed', 'bool'],
180
+ WPM_APP_LAUNCH_ALLOW: ['appLaunchAllow', 'list'],
181
+ };
182
+ /** @type {Record<string, any>} */
183
+ const out = {};
184
+ for (const [envName, [key, kind]] of Object.entries(MAP)) {
185
+ const raw = process.env[envName];
186
+ if (raw === undefined) continue;
187
+ if (kind === 'bool') out[key] = /^(1|true|yes|on)$/i.test(raw.trim());
188
+ else if (kind === 'int') out[key] = Number.parseInt(raw, 10);
189
+ else if (kind === 'list') out[key] = raw.split(',').map((s) => s.trim()).filter(Boolean);
190
+ else out[key] = raw;
191
+ }
192
+ return out;
193
+ }
194
+
195
+ // ---- JSON-RPC 2.0 over stdio ------------------------------------------------------------
196
+ /** @type {Map<string, AbortController>} */
197
+ const aborts = new Map();
198
+ let callSeq = 0;
199
+
200
+ /** @param {Record<string, any>} msg @returns {void} */
201
+ function send(msg) {
202
+ process.stdout.write(JSON.stringify(msg) + '\n');
203
+ }
204
+ /** @param {string|number|null} id @param {any} result @returns {void} */
205
+ const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
206
+ /** @param {string|number|null} id @param {number} code @param {string} message @param {string} [data] @returns {void} */
207
+ const fail = (id, code, message, data) => send({ jsonrpc: '2.0', id, error: { code, message, ...(data ? { data } : {}) } });
208
+
209
+ /** @param {string|number} id @param {Record<string, any>|undefined} params @returns {void} */
210
+ function onInitialize(id, params) {
211
+ const asked = String(params?.protocolVersion ?? '');
212
+ // Echo what the client asked for when we speak it; otherwise answer with the newest version we do
213
+ // speak. Declining to echo an unknown version is how a client learns to negotiate instead of
214
+ // assuming the server silently understood it.
215
+ reply(id, {
216
+ protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
217
+ capabilities: { tools: { listChanged: false } },
218
+ serverInfo: { name: SERVER_NAME, title: 'Windows Parallel (wpm)', version: pkg.version },
219
+ instructions: 'Start with action=windows to enumerate targets, action=snapshot to read an element frame, or action=status to see what currently holds the foreground. Refusals are data: read the code, then change the setting or the facts it names -- do not retry the same call.',
220
+ });
221
+ }
222
+
223
+ /** @param {string|number} id @returns {void} */
224
+ function onToolsList(id) {
225
+ reply(id, { tools: [mcpTool] });
226
+ }
227
+
228
+ /** A picture is a file path here because the DSH form renders that file. Over stdio a path means
229
+ * nothing to the caller, so the PNG is attached as base64 as well -- WPM_MCP_NO_IMAGE=1 opts out for
230
+ * a client that only reads the numbers. */
231
+ /** @param {any} r @returns {Array<Record<string, any>>} */
232
+ function contentBlocks(r) {
233
+ /** @type {Array<Record<string, any>>} */
234
+ const blocks = [{ type: 'text', text: String(r?.text ?? '') }];
235
+ if (process.env.WPM_MCP_NO_IMAGE === '1') return blocks;
236
+ const file = r?.file;
237
+ if (typeof file === 'string' && /\.(png|jpe?g)$/i.test(file) && r?.refusal !== 'stale_ref') {
238
+ try {
239
+ const buf = readFileSync(file);
240
+ blocks.push({ type: 'image', data: buf.toString('base64'), mimeType: /\.jpe?g$/i.test(file) ? 'image/jpeg' : 'image/png' });
241
+ } catch (err) {
242
+ // The text already told the caller the file was produced; a read failure is the transport's
243
+ // problem, so it is said on stderr and never dressed up as an engine refusal.
244
+ log('[warn] the picture could not be attached:', String(err));
245
+ blocks.push({ type: 'text', text: `image-note=the engine wrote ${file} but this server could not read it back` });
246
+ }
247
+ }
248
+ return blocks;
249
+ }
250
+
251
+ /** @param {string|number} id @param {Record<string, any>|undefined} params @returns {Promise<void>} */
252
+ async function onToolsCall(id, params) {
253
+ const name = params?.name;
254
+ if (name !== MCP_TOOL_NAME) {
255
+ return fail(id, -32602, `unknown tool '${String(name)}' -- this server exposes exactly one tool: ${MCP_TOOL_NAME}`);
256
+ }
257
+ const args = params?.arguments ?? {};
258
+ const callId = `${++callSeq}`;
259
+ const ac = new AbortController();
260
+ aborts.set(callId, ac);
261
+ try {
262
+ const r = await tool.execute(args, { signal: ac.signal });
263
+ // isError mirrors the engine's own answer. A refusal is NOT a transport failure and the code
264
+ // stays verbatim in the text block: this file must not soften, renumber or re-explain a refusal,
265
+ // because the whole vocabulary was built so the caller can branch on the code.
266
+ reply(id, {
267
+ content: contentBlocks(r),
268
+ structuredContent: r,
269
+ isError: r?.ok !== true,
270
+ });
271
+ } catch (err) {
272
+ /** @type {any} */
273
+ const e = err;
274
+ // Two kinds of thrown answer reach here, and neither is an internal error:
275
+ // * `refusal(code, reason)` -- the vocabulary the engine uses when the CALL is not executable;
276
+ // * `ToolArgsError` -- argument validation from the tool definition (`action` outside the declared
277
+ // set, a missing required argument). Both are the caller's, so they come back as a tool-level
278
+ // error whose text starts with the code or names the argument. Answering -32603 instead would
279
+ // tell a client its own request was a server fault, which is the kind of misattribution this
280
+ // project refuses on every other surface.
281
+ const code = typeof e?.code === 'string' ? e.code : '';
282
+ const argsError = e?.name === 'ToolArgsError';
283
+ if (code || argsError) {
284
+ const head = code ? `${code}: ` : '';
285
+ reply(id, { content: [{ type: 'text', text: `${head}${String(e.message ?? e)}` }], isError: true });
286
+ return;
287
+ }
288
+ fail(id, -32603, `wpm-mcp internal error: ${String(e?.message ?? e)}`);
289
+ } finally {
290
+ aborts.delete(callId);
291
+ }
292
+ }
293
+
294
+ /** @param {any} msg @returns {Promise<void>} */
295
+ async function handle(msg) {
296
+ if (msg === null || typeof msg !== 'object' || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
297
+ // A line that is JSON but not a request. Answering with -32600 keeps the client from timing out on
298
+ // a message it believed was sent; a notification never gets here because `method` exists.
299
+ if (msg && msg.id !== undefined) { fail(msg.id, -32600, 'not a JSON-RPC 2.0 request'); return; }
300
+ log('[warn] ignored a non-request line:', JSON.stringify(msg).slice(0, 120));
301
+ return;
302
+ }
303
+ const { id, method, params } = msg;
304
+ const isNotification = id === undefined || id === null;
305
+ if (method === 'notifications/cancelled') {
306
+ const target = String(params?.requestId ?? '');
307
+ const ac = aborts.get(target);
308
+ if (ac) ac.abort();
309
+ return;
310
+ }
311
+ if (isNotification) return; // initialized, cancelled-progress, roots/list_changed ...: silent by protocol
312
+ switch (method) {
313
+ case 'initialize': return onInitialize(id, params);
314
+ case 'ping': return reply(id, {});
315
+ case 'tools/list': return onToolsList(id);
316
+ case 'tools/call': return await onToolsCall(id, params);
317
+ default:
318
+ return fail(id, -32601, `Method not found: ${method} (this server implements initialize, ping, tools/list, tools/call)`);
319
+ }
320
+ }
321
+
322
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
323
+ rl.on('line', (line) => {
324
+ const trimmed = line.trim();
325
+ if (!trimmed) return;
326
+ let msg;
327
+ try {
328
+ msg = JSON.parse(trimmed);
329
+ } catch {
330
+ // The one case where a reply is sent with id null: JSON-RPC cannot know whom to answer, and the
331
+ // alternative -- killing the transport over a stray keystroke on stdin -- would let a single
332
+ // malformed line end the whole server.
333
+ fail(null, -32700, 'Parse error: the line was not JSON');
334
+ return;
335
+ }
336
+ handle(msg).catch((err) => log('[error] handler threw:', String((/** @type {any} */ (err))?.stack ?? err)));
337
+ });
338
+
339
+ /** @param {string} reason @returns {Promise<void>} */
340
+ const shutdown = async (reason) => {
341
+ log(`[info] shutting down (${reason})`);
342
+ for (const ac of aborts.values()) ac.abort();
343
+ aborts.clear();
344
+ for (const fn of disposers) {
345
+ try { await fn(); } catch (err) { log('[warn] a disposer threw:', String(err)); }
346
+ }
347
+ process.exit(0);
348
+ };
349
+ rl.on('close', () => { void shutdown('stdin closed'); });
350
+ process.stdin.on('error', () => { void shutdown('stdin error'); });
package/lib/policy.js ADDED
@@ -0,0 +1,127 @@
1
+ // policy.js -- the authorization ladder, as one pure module.
2
+ //
3
+ // WHY TWO AXES AND NOT ELEVEN SWITCHES. Every action declares the LOWEST rung it can ever need
4
+ // (`requiresTier` in src/schema/tools.json); the owner sets ONE ceiling (`policy`). A caller asking for
5
+ // more than the ceiling is refused with `policy_denied` whose next step is named: raise the setting, do
6
+ // not retry. The alternative -- a boolean per action -- would need eleven settings for eleven actions and
7
+ // a twelfth the moment a capability is added, and the pair that actually drifts is the setting nobody
8
+ // reads and the action nobody thought about.
9
+ //
10
+ // THE RUNGS ARE ABOUT DISTURBANCE, NOT ABOUT RISK CATEGORY:
11
+ // readonly touches nothing: reads a window list, a tree, a screen, a clipboard VALUE;
12
+ // quiet writes into one named window through its message door -- zero foreground change, measured;
13
+ // flash the same write when only UI Automation can reach it: one bounded flash that reverses itself;
14
+ // takeover the real cursor moves and the focus is held until the action ends, HUD mandatory.
15
+ // `launch` sits at takeover because it is the one action whose consequences outlive the call; it ALSO
16
+ // needs its own gate (appLaunchAllowed) and its own whitelist, which no tier ordering can express.
17
+ //
18
+ // NO IO, NO STATE, NO CLOCK. Every function here is answerable from its arguments, which is what makes
19
+ // the table testable without a desktop and what keeps a policy decision from depending on when it was
20
+ // asked. Drift between this set and tools.json is a gate (scripts/check-policy-table.mjs), not a comment.
21
+
22
+ /** The four rungs, lowest first. Order is the semantics: `tierAtLeast` compares positions here. */
23
+ export const TIER_ORDER = ['readonly', 'quiet', 'flash', 'takeover'];
24
+
25
+ /** The four settings levels, lowest first, each naming the highest rung it permits. */
26
+ export const POLICY_LEVELS = ['readonly', 'quiet', 'balanced', 'full'];
27
+
28
+ /**
29
+ * Which rung each `policy` level allows at most. `balanced` is the default and stops at `flash`: the
30
+ * quiet door and the self-reversing UIA path are permitted, the takeover tier and `launch` are not.
31
+ * @type {Record<string, string>}
32
+ */
33
+ export const POLICY_CEILINGS = {
34
+ readonly: 'readonly',
35
+ quiet: 'quiet',
36
+ balanced: 'flash',
37
+ full: 'takeover',
38
+ };
39
+
40
+ /**
41
+ * Is `required` at or below what `policy` permits?
42
+ *
43
+ * An unknown `policy` or unknown `required` answers FALSE. That is the whole safety argument of this
44
+ * function: a typo in a bundle patch, a tier someone added to tools.json without adding it here, or a
45
+ * caller that invents a level must all fall on the refusing side, because "unparseable setting" and
46
+ * "everything allowed" reading the same way is how a permission system becomes decoration.
47
+ * @param {string} policy @param {string} required @returns {boolean}
48
+ */
49
+ export function tierAtLeast(policy, required) {
50
+ const ceiling = POLICY_CEILINGS[policy];
51
+ if (!ceiling) return false;
52
+ const need = TIER_ORDER.indexOf(required);
53
+ if (need < 0) return false;
54
+ return need <= TIER_ORDER.indexOf(ceiling);
55
+ }
56
+
57
+ /**
58
+ * The rung a (action, requestedTier) pair needs. When the caller explicitly asks for the takeover tier
59
+ * that outranks the action's declared minimum, because asking for the cursor to move IS the higher
60
+ * request; otherwise the declared rung decides.
61
+ * @param {string} required the action's declared `requiresTier`
62
+ * @param {boolean} takeoverRequested
63
+ * @param {boolean} keyInjectRequested
64
+ * @returns {string}
65
+ */
66
+ export function effectiveTier(required, takeoverRequested = false, keyInjectRequested = false) {
67
+ if (takeoverRequested || keyInjectRequested) return 'takeover';
68
+ return TIER_ORDER.includes(required) ? required : 'takeover';
69
+ }
70
+
71
+ /**
72
+ * The action's declared rung, or `takeover` for an action nobody declared -- an undeclared action is
73
+ * treated as the loudest one until a human says otherwise. Silence about a capability must not read as
74
+ * permission for it.
75
+ *
76
+ * `op` consults `requiresTierFor` for the one action whose halves live on different rungs: reading the
77
+ * clipboard touches nothing, writing it replaces something the owner put there, and a single rung for
78
+ * both would have to be either too loose or too tight. An op that the table does not refine falls back
79
+ * to the action's rung -- it never falls back to "allowed".
80
+ * @param {Record<string, any>} table action -> requiresTier (and optionally requiresTierFor)
81
+ * @param {string} action @param {string} [op] @returns {string}
82
+ */
83
+ export function actionTier(table, action, op) {
84
+ const entry = table ? table[action] : undefined;
85
+ if (entry && typeof entry === 'object') {
86
+ const perOp = op && entry.requiresTierFor ? entry.requiresTierFor[op] : undefined;
87
+ if (typeof perOp === 'string') return TIER_ORDER.includes(perOp) ? perOp : 'takeover';
88
+ return TIER_ORDER.includes(entry.requiresTier) ? entry.requiresTier : 'takeover';
89
+ }
90
+ if (typeof entry === 'string') return TIER_ORDER.includes(entry) ? entry : 'takeover';
91
+ return 'takeover';
92
+ }
93
+
94
+ /**
95
+ * The tier table as `lib/index.js` and the gate both want it: one object per action, carrying the
96
+ * declared rung and, where the action has halves, the per-op refinement. Reading it through THIS
97
+ * function is the single place the shape is understood; the contract file stays the source of truth.
98
+ * @param {Array<{action:string, requiresTier?:string, requiresTierFor?:Record<string,string>}>} tools
99
+ * @returns {Record<string, {requiresTier: string, requiresTierFor: Record<string,string>}>}
100
+ */
101
+ export function tierTable(tools) {
102
+ /** @type {Record<string, {requiresTier: string, requiresTierFor: Record<string,string>}>} */
103
+ const out = {};
104
+ for (const t of tools ?? []) {
105
+ if (!t || typeof t.action !== 'string') continue;
106
+ out[t.action] = {
107
+ requiresTier: typeof t.requiresTier === 'string' ? t.requiresTier : '',
108
+ requiresTierFor: (t.requiresTierFor && typeof t.requiresTierFor === 'object') ? t.requiresTierFor : {},
109
+ };
110
+ }
111
+ return out;
112
+ }
113
+ /**
114
+ * Should this action be refused for being above the ceiling? Returns the decision so the caller
115
+ * cannot accidentally invert the boolean: `denied` is the refusal, and the two facts a reader
116
+ * needs (what the action needed, what the policy allows) come back already formatted.
117
+ * @param {{policy: string, table: Record<string,any>, action: string, op?: string, takeoverRequested?: boolean, keyInjectRequested?: boolean}} q
118
+ * @returns {{denied: boolean, required: string, ceiling: string}}
119
+ */
120
+ export function policyDecision(q) {
121
+ const required = effectiveTier(actionTier(q.table, q.action, q.op), q.takeoverRequested, q.keyInjectRequested);
122
+ return {
123
+ denied: !tierAtLeast(q.policy, required),
124
+ required,
125
+ ceiling: POLICY_CEILINGS[q.policy] ?? '(unknown policy)',
126
+ };
127
+ }
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "dsh-windows-parallel-mcp",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest",
7
7
  "registry": "https://registry.npmjs.org/"
8
8
  },
9
- "description": "Drive a Windows window quietly by default and visibly on request: one tool, eight actions (windows, status, click, type, focus, snapshot, screenshot, preview), a channel decision table that prefers the quiet door, a bounded self-reversing focus flash when only UI Automation can reach the control, an opt-in takeover tier (HUD mandatory, cursor always restored, keyboard injection only when asked and only for the foreground target), and a read surface that hands the model a numbered element frame plus screenshot coordinates as data so it never multiplies a scale factor. Since 0.6.0 a write is read back: effect=readback-verified is granted only when the value in the field matches a prediction built from the control's own measurements, caretPosition places the caret (start/end, with the applied selection reported), disabled and focus-moved targets are named in the result, and the screenshot says which path painted it (captureBackend=bitblt|gdiplus). Windows PowerShell 5.1 sidecar, zero install dependencies, no mouse injection.",
9
+ "description": "Drive a Windows window quietly by default and visibly on request: one tool, eleven actions (windows, status, click, type, focus, snapshot, screenshot, preview, launch, clipboard, window), a channel decision table that prefers the quiet door, a bounded self-reversing focus flash when only UI Automation can reach the control, an opt-in takeover tier (policy full AND takeoverAllowed) where the real cursor moves to the action point and is always restored, a read surface that hands the model a numbered element frame plus screenshot coordinates as data so it never multiplies a scale factor, and since 0.6.0 a read-back of every write: effect=readback-verified only when the field's own value matches a prediction built from the control's measurements, with caretPosition, disabled/focus reporting and the capture path named as captureBackend. 0.7.0 adds the three desktop capabilities behind one ceiling (policy), an exact launch whitelist, an idle check that refuses instead of interrupting the owner, and an append-only JSONL audit log that records decisions and lengths but never payloads. Windows PowerShell 5.1 sidecar, zero install dependencies, no mouse injection.",
10
10
  "keywords": [
11
11
  "deepseek",
12
12
  "deepseek-harness",
@@ -30,6 +30,9 @@
30
30
  "type": "module",
31
31
  "main": "lib/index.js",
32
32
  "types": "types/index.d.ts",
33
+ "bin": {
34
+ "wpm-mcp": "./lib/mcp-server.mjs"
35
+ },
33
36
  "exports": {
34
37
  ".": {
35
38
  "types": "./types/index.d.ts",
@@ -37,6 +40,7 @@
37
40
  },
38
41
  "./cordis.patch.yml": "./cordis.patch.yml",
39
42
  "./dsh.plugin.json": "./dsh.plugin.json",
43
+ "./server.json": "./server.json",
40
44
  "./src/engine/*": "./src/engine/*",
41
45
  "./package.json": "./package.json"
42
46
  },
@@ -45,6 +49,7 @@
45
49
  "types/",
46
50
  "src/engine/",
47
51
  "src/schema/",
52
+ "server.json",
48
53
  "docs/refusals.md",
49
54
  "docs/takeover.md",
50
55
  "CHANGELOG.md",
@@ -102,6 +107,8 @@
102
107
  "test": "node scripts/check.mjs && node test/plugin-test.mjs && node test/worker-smoke.mjs",
103
108
  "test:decide": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File test/decide-test.ps1",
104
109
  "test:refusals": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File test/refusals-test.ps1",
110
+ "test:mcp": "node test/mcp-stdio.mjs",
111
+ "mcp": "node lib/mcp-server.mjs",
105
112
  "test:hud": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -STA -File test/hud-test.ps1",
106
113
  "test:takeover": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -STA -File test/takeover-test.ps1",
107
114
  "test:keyinject": "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -STA -File test/keyinject-test.ps1",
package/server.json ADDED
@@ -0,0 +1,109 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
+ "name": "io.github.drscrewdriver/dsh-windows-parallel-mcp",
4
+ "title": "Windows Parallel",
5
+ "description": "Drive one Windows window through eleven declared actions, choosing the cheapest door that can reach the target: window messages for a classic control (zero foreground changes), one bounded self-reversing UI Automation flash when only a pattern can reach it, and an opt-in takeover tier where the real cursor moves and is always restored. Writes are read back and the effect value names who reported success; screenshots name the capture path that painted them. Refusals carry a code that names the switch or the missing fact, the policy ceiling is set by the process owner and never by a call, and every action appends one audit row that records decisions and lengths but never the content typed or copied. Windows only, PowerShell 5.1 sidecar, zero install dependencies, no mouse-event injection.",
6
+ "version": "0.8.0",
7
+ "repository": {
8
+ "url": "https://github.com/drscrewdriver/dsh-windows-parallel-mcp",
9
+ "source": "github"
10
+ },
11
+ "websiteUrl": "https://github.com/drscrewdriver/dsh-windows-parallel-mcp#readme",
12
+ "packages": [
13
+ {
14
+ "registryType": "npm",
15
+ "registryBaseUrl": "https://registry.npmjs.org",
16
+ "identifier": "dsh-windows-parallel-mcp",
17
+ "version": "0.8.0",
18
+ "transport": {
19
+ "type": "stdio"
20
+ },
21
+ "environmentVariables": [
22
+ {
23
+ "name": "WPM_POLICY",
24
+ "description": "Authorization ceiling over all eleven actions: readonly | quiet | balanced | full. Default balanced. A call above it is refused with policy_denied, and the next step is to raise this setting, not to retry."
25
+ },
26
+ {
27
+ "name": "WPM_TAKEOVER_ALLOWED",
28
+ "description": "Capability switch for the takeover tier (the real cursor moving to the action point). Default false, and it is not implied by WPM_POLICY=full: both are needed."
29
+ },
30
+ {
31
+ "name": "WPM_KEY_INJECT_ALLOWED",
32
+ "description": "Capability switch for keyInput:'inject' (synthetic keyboard input into the foreground target). Default false."
33
+ },
34
+ {
35
+ "name": "WPM_APP_LAUNCH_ALLOWED",
36
+ "description": "Capability switch for the launch action. Default false; nothing may start while it is off."
37
+ },
38
+ {
39
+ "name": "WPM_APP_LAUNCH_ALLOW",
40
+ "description": "Comma-separated exact-name whitelist for launch (case-folded, no wildcard, no prefix match). Empty by default. A whitelist vouches for a program, not for the arguments it is given; both the target and the arguments are written to the audit log."
41
+ },
42
+ {
43
+ "name": "WPM_POLICY_IDLE_MS",
44
+ "description": "How long the owner must have been away from the keyboard before a takeover-grade action is allowed. Default 3000. While they are active the call is refused with user_active rather than interrupting them; no dialog is offered instead."
45
+ },
46
+ {
47
+ "name": "WPM_OVERLAY",
48
+ "description": "The click-through overlay and the global pause chord (Ctrl+Alt+Q). Default true -- a visible aid that tells the human something is being driven. Set false only if the hotkey cannot be registered on this machine."
49
+ },
50
+ {
51
+ "name": "WPM_ENABLED",
52
+ "description": "Master switch. Default true. False refuses every action with paused before anything is touched -- a switched-off plugin does not so much as start its sidecar."
53
+ },
54
+ {
55
+ "name": "WPM_SETTLE_MS",
56
+ "description": "How long the engine waits after a write before it reads the control back. Default 350. The read-back prediction is built after this window, so a value that is too small reports readbackMismatch rather than lying about success."
57
+ },
58
+ {
59
+ "name": "WPM_REQUEST_TIMEOUT_MS",
60
+ "description": "Budget for one sidecar round trip. Default 20000."
61
+ },
62
+ {
63
+ "name": "WPM_POWERSHELL_PATH",
64
+ "description": "Absolute path to the PowerShell executable, for a machine where powershell.exe is not on PATH. Default empty (find it the usual way)."
65
+ },
66
+ {
67
+ "name": "WPM_LOG_WORKER_STDERR",
68
+ "description": "Forward the sidecar's stderr to this server's stderr. Default false; switch it on when a worker dies before answering."
69
+ },
70
+ {
71
+ "name": "WPM_TAKEOVER_MAX_MS",
72
+ "description": "Longest a single takeover may hold the cursor. Default 10000, clamped 500-60000; it is a ceiling on the tier, not a way to opt in."
73
+ },
74
+ {
75
+ "name": "WPM_TAKEOVER_ARM_MS",
76
+ "description": "The HUD's arm phase before the cursor moves. Default 800, so a human sees it coming and can use the stop button or the pause chord."
77
+ },
78
+ {
79
+ "name": "WPM_SNAPSHOT_MAX_ELEMENTS",
80
+ "description": "Element cap for one snapshot. Default 300, clamped 1-5000, and the number actually used is reported back on the result rather than assumed."
81
+ },
82
+ {
83
+ "name": "WPM_SCREENSHOT_MAX_WIDTH",
84
+ "description": "Resize width for screenshots. Default 0 = no scaling, because a silently rescaled picture makes every coordinate the model reads wrong. Any scaling is stated on the result as scale/identity."
85
+ },
86
+ {
87
+ "name": "WPM_SHOTS_KEEP",
88
+ "description": "How many recent screenshots to retain. Default 10, clamped 1-200."
89
+ },
90
+ {
91
+ "name": "WPM_AUDIT_KEEP",
92
+ "description": "How many newest rows of %LOCALAPPDATA%\\wpm\\audit.log to retain. Default 2000."
93
+ },
94
+ {
95
+ "name": "WPM_MCP_NO_IMAGE",
96
+ "description": "Set to 1 to stop attaching screenshot pixels as base64 image content; the text result still names the file, the rect, the scale and the capture backend."
97
+ }
98
+ ]
99
+ }
100
+ ],
101
+ "_meta": {
102
+ "io.modelcontextprotocol.registry/publisher-provided": {
103
+ "platform": "windows",
104
+ "requires": "Windows PowerShell 5.1 (ships with Windows) and Node >= 20. No install dependencies; no build step.",
105
+ "sameEngineTwoForms": "lib/index.js is the DSH plugin half and lib/mcp-server.mjs is this stdio half; both drive one PowerShell engine, so the actions, the refusal vocabulary, the gates and the audit log are identical in either form.",
106
+ "schemaSource": "tools/list is generated from src/schema/tools.json at start-up -- the action surface is declared once."
107
+ }
108
+ }
109
+ }