dsh-windows-parallel-mcp 0.7.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.
package/README.zh.md CHANGED
@@ -5,7 +5,7 @@
5
5
  > 一个让代理驱动**自己**的 Windows 窗口的 DSH 插件——默认静默,按需可见。窗口接受窗口消息时完全不夺焦点;只有 UI Automation 可达时,焦点仅发生一次有界闪烁并自动还原;显式请求接管档时,光标移动到目标点并始终还原,HUD 提供三种中断方式。其他情况一律拒绝,并给出代码与原因。
6
6
 
7
7
  > **English canonical text follows.** The localized summary above is the orientation; the text below is the authoritative specification (structure, commands and numbers are identical across all 10 languages).
8
- > **Current release: 0.7.0** — this document describes the contract as of that version. What
8
+ > **Current release: 0.8.0** — this document describes the contract as of that version. What
9
9
  > changed in it, and in every version before it, is in [CHANGELOG.md](CHANGELOG.md), newest first.
10
10
 
11
11
  A DSH plugin that lets an agent drive **its own** Windows windows — quietly by default, and visibly
@@ -15,6 +15,11 @@ explicitly ask for the takeover tier, the cursor moves to the point and is alway
15
15
  HUD that can stop it three ways. Everywhere else it refuses, with a code and a reason — never with
16
16
  silence: every refusal carries a code from a closed set of seventeen and the next step.
17
17
 
18
+ **It ships in two forms over one engine, and 0.8.0 did not replace the first one.** Inside DSH it is a
19
+ plugin (`apply()` on the host half, PowerShell sidecar underneath). Outside it, the same package is an
20
+ MCP server over stdio (`bin: wpm-mcp`), whose tool list is generated from the same contract file — see
21
+ "The second form" below.
22
+
18
23
  **The takeover tier defaults off, and that is structural.** The cursor is only ever moved because you
19
24
  opened `takeoverAllowed` **and** asked for it on the call (`takeover:true`), so an upgrade cannot
20
25
  start moving your cursor by itself. Keyboard injection lives inside that tier only, only when asked
@@ -368,6 +373,51 @@ failed`) rather than swallowed: a log that looks complete and is not is worse th
368
373
  is missing lines. This is the only artifact that survives a call, and it is the one thing that can
369
374
  answer "what did the agent do to this machine" after the fact.
370
375
 
376
+ ## The second form: MCP over stdio (0.8.0)
377
+
378
+ The same plugin is also an MCP server, and it is the same code rather than a re-implementation of it.
379
+ `lib/mcp-server.mjs` registers the tool by calling the very `apply()` the DSH host calls, and forwards
380
+ `tools/call` into the same `toRequest()` / gate order / `format()` path, so the eleven actions, the
381
+ seventeen refusal codes, the policy ceiling and the audit line are identical in both forms. That is why
382
+ the engine files were not touched to add it: a second implementation of a permission is a permission
383
+ that can be reached around by using the other copy.
384
+
385
+ **One tool, not eleven.** `tools/list` exposes `wpm` with an `action` discriminator, generated from
386
+ `src/schema/tools.json` — one `oneOf` branch per action, whose `properties`, `required` and
387
+ `additionalProperties` are that action's declaration copied field for field. Nothing in the server
388
+ spells out an action name, a parameter name or a code, and `scripts/check-mcp-schema.mjs` is the reason
389
+ that stays true: it starts the real server, reads what a client would read, and compares it to the file.
390
+ Its self-test mutates both sides on purpose — four edits to the generator must turn the gate red, and two
391
+ edits to the *contract* (rename a parameter, flip `additionalProperties`) must stay green AND move,
392
+ because an arm that only breaks the generator cannot tell a generated schema from a transcribed one that
393
+ happens to agree today.
394
+
395
+ **Settings come from the environment, never from the call.** `WPM_POLICY`, `WPM_TAKEOVER_ALLOWED`,
396
+ `WPM_APP_LAUNCH_ALLOWED`, `WPM_APP_LAUNCH_ALLOW` and the rest of the `WPM_*` set are read at start-up
397
+ and only if present — the defaults stay in `lib/index.js`, because a second copy of a default is a
398
+ default that drifts. A client that could raise its own ceiling or add itself to the launch whitelist
399
+ would make the authorization model decorative, which is the same reason the DSH form reads settings
400
+ from the profile rather than from the prompt.
401
+
402
+ **A picture is attached as pixels, because a path is not portable.** The DSH form renders the screenshot
403
+ file it wrote; a caller on the other end of a pipe cannot open it, so `tools/call` returns the PNG as
404
+ base64 `image` content alongside the text. The text is never replaced by it — `screenRect`, `scale`,
405
+ `identity`, `frame` and `captureBackend` stay in the first block, and across the DSH bridge, where a
406
+ host that cannot accept image input projects the picture into a text diagnostic, those numbers still
407
+ arrive. `WPM_MCP_NO_IMAGE=1` opts out.
408
+
409
+ **Refusals survive the trip.** A refused call comes back with `isError` and the code as the first token
410
+ of the text, unsoftened. Over the DSH bridge the refusal is re-raised as an error whose message is that
411
+ text, so `policy_denied` still reads as `policy_denied` at the far end — asserted, not assumed, in
412
+ `test/mcp-bridge.mjs`, which drives the SDK and the bridge code the host actually ships.
413
+
414
+ **The transport is the only new attack surface, and it is a pipe.** JSON-RPC 2.0 over stdin/stdout with
415
+ Node built-ins and zero dependencies: one JSON object per line, replies keyed by `id` because the worker
416
+ is asynchronous, notifications answered with nothing, a non-JSON line answered with `-32700` and a null
417
+ `id` without killing the loop, an unknown method answered `-32601` without killing the loop, and stdin
418
+ closing meaning "dispose the sidecar and exit 0". Everything that is not a protocol line goes to stderr
419
+ — `console.log` in the plugin half would otherwise print into the JSON stream and corrupt it.
420
+
371
421
  ## What it does not do
372
422
 
373
423
  - **No mouse injection.** `MOUSEEVENTF_*`, `mouse_event` and `keybd_event` are banned in every
@@ -381,6 +431,10 @@ answer "what did the agent do to this machine" after the fact.
381
431
  - **No OCR / Set-of-Marks / pixel fallback.** Not part of this claim, and already done well elsewhere.
382
432
  - **No watchdog.** The restore is one-shot and happens inline. A watchdog that keeps chasing the
383
433
  foreground would fight you.
434
+ - **No HTTP, no SSE, no OAuth, no TLS.** Two forms exist and neither has a network face: in-process for
435
+ DSH, stdio for MCP. "No network surface" is not a hardening claim, it is the absence of one — there is
436
+ nothing to authenticate against, nothing to listen on, and nothing that keeps running when the caller
437
+ goes away.
384
438
  - **Terminals are still refused** (`terminal_no_door`), and now for a measured reason. The 0.2.0 plan
385
439
  was to drive one by typing into it; two probes say otherwise on this host: 242 `KEYEVENTF_UNICODE`
386
440
  events with the terminal in the foreground and Enter sent produced nothing, and a scan-code arm
@@ -401,6 +455,22 @@ call, not at plugin load.
401
455
  `engines.dsh` is an explicit two-sided range. There is no runtime version probing and no silent
402
456
  degradation.
403
457
 
458
+ Since 0.8.0 the same package is also an MCP server, and nothing about the install above changes — the
459
+ two forms are parallel entries, not a migration:
460
+
461
+ ```bash
462
+ # stdio, configured by the environment of whoever starts it
463
+ WPM_POLICY=balanced npx dsh-windows-parallel-mcp # via bin: wpm-mcp
464
+ # or, from a checkout
465
+ node lib/mcp-server.mjs
466
+ ```
467
+
468
+ Point any MCP client at that command; `server.json` (shipped in the tarball) is the MCP Registry
469
+ manifest for it, with the namespace `io.github.drscrewdriver/dsh-windows-parallel-mcp` and the npm
470
+ package as its ownership proof. A DSH profile can bridge it instead of loading the plugin directly
471
+ (`@deepseek-ai/dsh-mcp-client`, stdio transport), which registers the tool as `mcp__<serverName>__wpm`;
472
+ `test/mcp-bridge.mjs` drives that bridge with the host's own client SDK and tool-definition code.
473
+
404
474
  ## Typed surface
405
475
 
406
476
  `types/index.d.ts` is written by hand, not emitted from an implementation. It covers the whole
@@ -561,6 +631,33 @@ unmeasured end-to-end and is stated as such in [docs/refusals.md](docs/refusals.
561
631
  unchanged whitelist file list: adding `launch`/`window` did not open a door to `MOUSEEVENTF_*`,
562
632
  `mouse_event` or `keybd_event`.
563
633
 
634
+ ### 0.8.0's measurements
635
+
636
+ - **A hand-written JSON-RPC loop over stdio is enough** (the 0.8.0 prerequisite probe): `initialize`,
637
+ `tools/list` and `tools/call` all answer, an unknown method returns `-32601` and the process survives
638
+ it, a notification produces no reply line, two requests in flight are matchable by id, a non-JSON line
639
+ does not kill the transport, and closing stdin exits 0. Fifteen assertions, zero dependencies —
640
+ `@modelcontextprotocol/sdk` is not needed and is not used.
641
+ - **The host's SDK is the stricter judge than our own harness.** `test/mcp-bridge.mjs` connects
642
+ `@modelcontextprotocol/client` 2.2.0 (the version the DSH install ships) to our server and validates
643
+ the shapes we emit. Its negotiation throws when the server answers with a protocol revision the
644
+ client does not list, which is why `PROTOCOL_VERSIONS` in `lib/mcp-server.mjs` is checked against that
645
+ SDK's constants (latest `2025-11-25`) rather than guessed from a document.
646
+ - **A picture the host cannot display still delivers its numbers.** Across the bridge with no attachment
647
+ store mounted, a `screenshot` call does not throw: the bridge projects the image block into an
648
+ `[image unavailable: …]` text diagnostic and the `screenRect` / `scale` / `identity` / `frame` /
649
+ `captureBackend` line arrives regardless. Attaching pixels by default is safe because of that
650
+ measurement, not in spite of it.
651
+ - **`tools/list` follows the contract file, in both directions.** Renaming `caretPosition` in
652
+ `src/schema/tools.json` changes what the running server reports, and flipping one
653
+ `additionalProperties` changes it too — both are gate arms (`scripts/check-mcp-schema.mjs --self-test`),
654
+ so the claim "generated, not copied" is exercised rather than asserted in prose.
655
+ - **The install artifact is what was tested.** The 0.7.0 release was smoked from the unpacked tarball
656
+ (`npm pack` → unpack → drive the policy ceiling, both launch gates, the clipboard length-not-payload
657
+ rule and the audit rows: 17 assertions) and that run found two things the working tree could not show:
658
+ the `clipboard` headline does not name which op ran, and the launch gate is only observable once the
659
+ ceiling lets the call reach it. Both are recorded rather than papered over.
660
+
564
661
  ## Verifying the copy you actually installed
565
662
 
566
663
  Every test above imports the repository checkout, so a package that installs to the wrong place or ships
@@ -569,6 +666,12 @@ drives the **installed** copy: it lists a real window, runs a takeover click, as
569
666
  `takeover=on cursorRestored=true abortChord=…`, and checks that the HUD is torn down afterwards. Run once
570
667
  against the desktop profile after installing, as the last step of a release.
571
668
 
669
+ The stdio form has the same discipline: unpack the tarball and start `lib/mcp-server.mjs` from the
670
+ unpacked directory (not from the checkout). `scripts/check-mcp-schema.mjs` and `test/mcp-bridge.mjs` both
671
+ spawn the server by path, so pointing them at the unpacked copy is the whole procedure. The 0.7.0 tag
672
+ was pushed after that run; a release that skips it is asserting that the shipped bytes work by
673
+ showing that the source does.
674
+
572
675
  ## License
573
676
 
574
677
  MIT
package/dsh.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-windows-parallel-mcp",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "main": "./lib/index.js",
5
5
  "description": "One tool, eleven actions: drive a Windows window quietly by default, read the target as a numbered element frame, and since 0.7.0 start a whitelisted program, touch the clipboard, and change one named window. Prefers window messages (zero foreground change); falls back to UI Automation with a bounded, self-reversing focus flash (measured net return 15-95 ms); offers an opt-in takeover tier (policy:'full' AND takeoverAllowed) where the cursor moves to the action point and is always restored, with a mandatory three-phase HUD and three interruption paths; adds snapshot/screenshot/preview, where labels address the UIA element itself and image coordinates are converted by the engine; reads a write back (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 a BitBlt capture path named as captureBackend; and gates everything through one ceiling (policy) plus a per-program launch whitelist, an idle check that refuses instead of interrupting, and an append-only JSONL audit log.",
6
6
  "engines": {
@@ -10,7 +10,7 @@
10
10
  "tools": [
11
11
  {
12
12
  "name": "wpm",
13
- "description": "Drive a Windows window quietly by default (actions: windows, status, click, type, focus, snapshot, screenshot, preview), with an opt-in takeover tier that is visible, interruptible and always restores the cursor, and a read surface whose numbered labels address the element itself."
13
+ "description": "Drive a Windows window quietly by default through eleven actions (windows, status, click, type, focus, snapshot, screenshot, preview, launch, clipboard, window), with an opt-in takeover tier that is visible, interruptible and always restores the cursor, a read surface whose numbered labels address the element itself, and a read-back that only grants effect=readback-verified when the field's own value agrees. Everything sits under one policy ceiling and every call, allowed or refused, leaves one audit row. The same engine is also reachable as an MCP stdio server (bin: wpm-mcp)."
14
14
  }
15
15
  ],
16
16
  "skills": []
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-windows-parallel-mcp",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest",
@@ -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",