A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: resolve qmd MCP failure on Windows via Node wrapper (#58)
Brenno Ferraric1a25a32ac2b
diff --git a/.claude/scripts/qmd-mcp.d.mts b/.claude/scripts/qmd-mcp.d.mtsnew file mode 100644index 0000000..c1c0723--- /dev/null+++ b/.claude/scripts/qmd-mcp.d.mts@@ -0,0 +1,23 @@+/**+ * Type declarations for qmd-mcp.mjs so TypeScript tests can import it.+ * The runtime file is plain ESM JS (.mjs) to avoid a build step; this file+ * mirrors its public exports for `tsc --noEmit`.+ */++/**+ * Locate @tobilu/qmd's real JS entrypoint. Returns an absolute path when+ * resolvable, null when not.+ */+export function resolveQmdEntry(): string | null;++/**+ * Build the (command, args, shell) tuple the spawn layer should invoke.+ */+export function buildLaunchCommand(+ entry: string | null,+ extraArgs?: readonly string[],+): {+ readonly cmd: string;+ readonly args: readonly string[];+ readonly shell: boolean;+};diff --git a/.claude/scripts/qmd-mcp.mjs b/.claude/scripts/qmd-mcp.mjsnew file mode 100644index 0000000..bc62087--- /dev/null+++ b/.claude/scripts/qmd-mcp.mjs@@ -0,0 +1,122 @@+#!/usr/bin/env node+/**+ * qmd-mcp.mjs — cross-platform MCP launcher for QMD.+ *+ * Claude Code spawns MCP servers without a shell, so on Windows the npm-installed+ * `qmd` shim (a .cmd/.ps1 file) can't be located from `child_process.spawn`. Even+ * with shell: true, the shim itself delegates to /bin/sh via %_prog%, which fails+ * on stock Windows without Git Bash's sh.exe on PATH.+ *+ * This wrapper bypasses the shim by resolving @tobilu/qmd's real JS entrypoint+ * and spawning it with the current Node binary. Works identically on Windows,+ * macOS, and Linux — no shell, no /bin/sh dependency.+ *+ * Fallback: if @tobilu/qmd isn't resolvable from this location (e.g., the user+ * has qmd installed via a non-npm channel), fall through to the `qmd` command+ * with shell: true so the global shim is still attempted.+ */++import { spawn, spawnSync } from "node:child_process";+import { existsSync } from "node:fs";+import { isAbsolute, join } from "node:path";+import { createRequire } from "node:module";+import { pathToFileURL } from "node:url";++const require = createRequire(import.meta.url);++/**+ * Locate @tobilu/qmd's real JS entrypoint. Returns an absolute path when+ * resolvable, null when not. Exported so the cross-platform test matrix can+ * verify resolution works on Windows, macOS, and Linux without having to+ * spawn the wrapper itself.+ */+export function resolveQmdEntry() {+ try {+ return require.resolve("@tobilu/qmd/dist/cli/qmd.js");+ } catch {}++ // Fallback for global npm installs that aren't on this package's resolution+ // path — ask npm directly where global packages live. Bounded timeout so a+ // hung npm process can't block MCP server startup indefinitely.+ const npmRoot = spawnSync("npm", ["root", "-g"], {+ shell: true,+ encoding: "utf8",+ timeout: 3000,+ });+ if (+ npmRoot.error ||+ npmRoot.signal !== null ||+ npmRoot.status !== 0+ ) {+ return null;+ }++ // Guard against success-with-empty-stdout or a relative path — either would+ // make join() produce a path anchored at cwd, and existsSync could then+ // match a local folder by accident.+ const root = npmRoot.stdout.trim();+ if (root === "" || !isAbsolute(root)) {+ return null;+ }++ const entry = join(root, "@tobilu", "qmd", "dist", "cli", "qmd.js");+ return existsSync(entry) ? entry : null;+}++/**+ * Build the (command, args) tuple the spawn layer should invoke. Split out+ * so tests can lock both branches (resolved entrypoint vs. PATH fallback)+ * without running a real child.+ */+export function buildLaunchCommand(entry, extraArgs = []) {+ const qmdArgs = ["mcp", ...extraArgs];+ return entry+ ? { cmd: process.execPath, args: [entry, ...qmdArgs], shell: false }+ : { cmd: "qmd", args: qmdArgs, shell: true };+}++function runAsMcp() {+ const entry = resolveQmdEntry();+ const { cmd, args, shell } = buildLaunchCommand(+ entry,+ process.argv.slice(2),+ );++ const child = spawn(cmd, args, { stdio: "inherit", shell });++ // spawn() emits 'error' when the command can't be invoked at all (e.g., qmd+ // not on PATH in the fallback branch). Without a handler Node would crash+ // with a stack trace — write a concise message and exit cleanly instead.+ child.on("error", (err) => {+ process.stderr.write(+ `qmd-mcp: failed to start qmd: ${err.message}\n`,+ );+ process.exit(1);+ });++ child.on("exit", (code, signal) => {+ if (signal !== null) {+ // Re-raise the signal against ourselves so the parent sees the same+ // termination cause. Some POSIX signals (SIGKILL, SIGSTOP) or names+ // unknown on this platform will cause process.kill to throw — in+ // that case fall back to a conventional non-zero exit.+ try {+ process.kill(process.pid, signal);+ } catch {+ process.exit(1);+ }+ return;+ }+ process.exit(code ?? 0);+ });+}++// Only spawn a child when this file is the actual entry point. Importing it+// from tests (to exercise resolveQmdEntry / buildLaunchCommand in isolation)+// must not trigger a spawn.+const entryUrl = process.argv[1]+ ? pathToFileURL(process.argv[1]).href+ : null;+if (entryUrl === import.meta.url) {+ runAsMcp();+}diff --git a/.claude/scripts/tests/qmd-mcp.test.ts b/.claude/scripts/tests/qmd-mcp.test.tsnew file mode 100644index 0000000..f63b52c--- /dev/null+++ b/.claude/scripts/tests/qmd-mcp.test.ts@@ -0,0 +1,87 @@+/**+ * Cross-platform tests for the QMD MCP wrapper.+ *+ * The real value of these tests is the CI matrix: they run on+ * ubuntu-latest, macos-latest, and windows-latest × Node 22/24.+ * CI installs @tobilu/qmd globally before the suite, so the happy-path+ * resolution assertion proves `require.resolve` + `npm root -g` find qmd+ * on every platform the template supports — exactly the guarantee this+ * wrapper exists to deliver.+ *+ * Pure-function tests for `buildLaunchCommand` lock both branches (resolved+ * entrypoint vs PATH fallback) without spawning anything.+ *+ * End-to-end spawn behaviour (JSON-RPC stream passthrough) is out of scope+ * here — that belongs in an MCP integration suite.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { existsSync } from "node:fs";+import { isAbsolute } from "node:path";++import {+ resolveQmdEntry,+ buildLaunchCommand,+} from "../qmd-mcp.mjs";++describe("resolveQmdEntry", () => {+ test("returns an absolute path to an existing qmd entrypoint when qmd is installed", () => {+ const entry = resolveQmdEntry();++ // When qmd isn't on this machine, skip — the assertion is meaningful+ // only against a real install. CI installs qmd globally, so this+ // branch should execute on every matrix leg.+ if (entry === null) {+ // Surface a skip-style signal in test output rather than silently passing.+ assert.ok(+ true,+ "qmd not installed in this environment — resolver correctly returned null",+ );+ return;+ }++ assert.equal(typeof entry, "string");+ assert.equal(isAbsolute(entry), true, `resolved path must be absolute, got: ${entry}`);+ assert.equal(existsSync(entry), true, `resolved path must exist on disk, got: ${entry}`);+ assert.match(+ entry,+ /@tobilu[\\/]qmd[\\/]dist[\\/]cli[\\/]qmd\.js$/,+ `resolved path should point at @tobilu/qmd's CLI entry, got: ${entry}`,+ );+ });+});++describe("buildLaunchCommand", () => {+ test("routes through process.execPath when an entrypoint is resolved", () => {+ const { cmd, args, shell } = buildLaunchCommand(+ "/fake/@tobilu/qmd/dist/cli/qmd.js",+ [],+ );+ assert.equal(cmd, process.execPath);+ assert.deepEqual(args, ["/fake/@tobilu/qmd/dist/cli/qmd.js", "mcp"]);+ assert.equal(shell, false);+ });++ test("forwards extra argv to the qmd mcp subcommand", () => {+ const { args } = buildLaunchCommand("/fake/qmd.js", ["--verbose", "--port=4000"]);+ assert.deepEqual(args, [+ "/fake/qmd.js",+ "mcp",+ "--verbose",+ "--port=4000",+ ]);+ });++ test("falls back to bare `qmd` with shell: true when resolution returns null", () => {+ const { cmd, args, shell } = buildLaunchCommand(null, []);+ assert.equal(cmd, "qmd");+ assert.deepEqual(args, ["mcp"]);+ assert.equal(shell, true);+ });++ test("fallback path still forwards extra argv", () => {+ const { args } = buildLaunchCommand(null, ["--debug"]);+ assert.deepEqual(args, ["mcp", "--debug"]);+ });+});diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 2ffe946..4772303 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -27,6 +27,9 @@ jobs:- name: Install typecheck deps (CI-only, not shipped)shell: bashrun: npm install --no-save --silent --prefix .claude/scripts [email protected] @types/[email protected]+ - name: Install qmd globally (proves MCP wrapper resolution on this OS)+ shell: bash+ run: npm install -g @tobilu/[email protected]- name: Typecheckshell: bashworking-directory: .claude/scriptsdiff --git a/.mcp.json b/.mcp.jsonindex cdaca1c..b2aef33 100644--- a/.mcp.json+++ b/.mcp.json@@ -1,8 +1,8 @@{"mcpServers": {"qmd": {- "command": "qmd",- "args": ["mcp"]+ "command": "node",+ "args": [".claude/scripts/qmd-mcp.mjs"]}}}