markdown-pdf-export 2.1.1 → 2.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.
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @fileoverview Setup helpers behind the MCP tools `install_browser_markdown_pdf`
3
+ * and `open_studio_markdown_pdf`, so an assistant can finish the setup without
4
+ * the user opening a terminal (or having Node installed: the editor's own
5
+ * Node runs the server).
6
+ */
7
+ import { spawn } from "node:child_process";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import process from "node:process";
11
+
12
+ import { PROJECT_SETTINGS_FILENAME, userSettingsPath } from "./settings-loader.mjs";
13
+
14
+ /**
15
+ * Wrap a long browser download so one tool call never blocks for minutes.
16
+ * The download keeps running in the server after `run()` returns
17
+ * "installing"; later calls join the same download.
18
+ *
19
+ * @param {() => Promise<void>} install
20
+ * @param {{ waitMs?: number }} [opts]
21
+ */
22
+ export function createBrowserInstaller(install, { waitMs = 50_000 } = {}) {
23
+ /** @type {Promise<"installed"> | null} */
24
+ let running = null;
25
+ /** @type {string | null} */
26
+ let lastError = null;
27
+
28
+ return {
29
+ /** @returns {"idle"|"installing"|"failed"} */
30
+ status: () => (running ? "installing" : lastError ? "failed" : "idle"),
31
+ lastError: () => lastError,
32
+
33
+ /** @returns {Promise<"installed"|"installing">} rejects if the install fails in time */
34
+ async run() {
35
+ if (!running) {
36
+ lastError = null;
37
+ running = install().then(
38
+ () => {
39
+ running = null;
40
+ return /** @type {const} */ ("installed");
41
+ },
42
+ (error) => {
43
+ running = null;
44
+ lastError = error instanceof Error ? error.message : String(error);
45
+ throw error;
46
+ },
47
+ );
48
+ // A failure after the caller stopped waiting must not crash the server.
49
+ running.catch(() => {});
50
+ }
51
+ let timer;
52
+ const timeout = new Promise((resolve) => {
53
+ timer = setTimeout(() => resolve(/** @type {const} */ ("installing")), waitMs);
54
+ });
55
+ try {
56
+ return await Promise.race([running, timeout]);
57
+ } finally {
58
+ clearTimeout(timer);
59
+ }
60
+ },
61
+ };
62
+ }
63
+
64
+ const STUDIO_URL = /^http:\/\/127\.0\.0\.1:\d+\/#[0-9a-f]+$/;
65
+
66
+ /**
67
+ * Start `cli.mjs studio` in its own process and resolve with its private URL.
68
+ *
69
+ * Studio swaps the exporter's settings while it renders previews, so it must
70
+ * not share a process with the MCP server. The child is detached: it outlives
71
+ * a server restart and stops by itself a few minutes after its page is closed.
72
+ *
73
+ * @param {object} opts
74
+ * @param {string} opts.cliPath path to cli.mjs
75
+ * @param {string} [opts.file] Markdown file to preview
76
+ * @param {string} [opts.projectFolder] edit <folder>/.markdown-pdf.json instead of the user file
77
+ * @param {boolean} [opts.openBrowser] default true
78
+ * @param {number} [opts.timeoutMs] default 15 s
79
+ * @returns {Promise<{ url: string, settingsPath: string, pid: number }>}
80
+ */
81
+ export function launchStudio({
82
+ cliPath,
83
+ file,
84
+ projectFolder,
85
+ openBrowser = true,
86
+ timeoutMs = 15_000,
87
+ }) {
88
+ const args = [cliPath, "studio"];
89
+ if (projectFolder) args.push("--project");
90
+ if (file) args.push("--file", path.resolve(file));
91
+ if (!openBrowser) args.push("--no-open");
92
+ // Same rule as startStudio(); the child inherits this process's environment.
93
+ const settingsPath = projectFolder
94
+ ? path.join(path.resolve(projectFolder), PROJECT_SETTINGS_FILENAME)
95
+ : userSettingsPath();
96
+
97
+ return new Promise((resolve, reject) => {
98
+ const child = spawn(process.execPath, args, {
99
+ cwd: projectFolder ? path.resolve(projectFolder) : os.homedir(),
100
+ stdio: ["ignore", "pipe", "pipe"],
101
+ detached: true,
102
+ windowsHide: true,
103
+ });
104
+
105
+ let stdout = "";
106
+ let stderr = "";
107
+ let settled = false;
108
+ const finish = (fn) => {
109
+ if (settled) return;
110
+ settled = true;
111
+ clearTimeout(timer);
112
+ fn();
113
+ };
114
+
115
+ const timer = setTimeout(
116
+ () =>
117
+ finish(() => {
118
+ child.kill();
119
+ reject(new Error(`Studio did not start within ${timeoutMs / 1000} s.\n${stderr.trim()}`));
120
+ }),
121
+ timeoutMs,
122
+ );
123
+
124
+ child.stderr.on("data", (chunk) => {
125
+ stderr += chunk.toString();
126
+ });
127
+ child.stdout.on("data", (chunk) => {
128
+ stdout += chunk.toString();
129
+ const url = stdout.split(/\r?\n/).map((line) => line.trim()).find((line) => STUDIO_URL.test(line));
130
+ if (!url) return;
131
+ finish(() => {
132
+ // Keep draining the pipes so the child never blocks on a full buffer,
133
+ // but let the server exit without waiting for Studio.
134
+ child.stdout.unref?.();
135
+ child.stderr.unref?.();
136
+ child.unref();
137
+ resolve({ url, settingsPath, pid: child.pid });
138
+ });
139
+ });
140
+ child.on("error", (error) =>
141
+ finish(() => reject(new Error(`Could not start Studio: ${error.message}`))),
142
+ );
143
+ child.on("exit", (code) =>
144
+ finish(() =>
145
+ reject(new Error(`Studio stopped before it was ready (exit ${code}).\n${stderr.trim()}`)),
146
+ ),
147
+ );
148
+ });
149
+ }
package/mcp.mjs CHANGED
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * Markdown PDF MCP server (stdio).
3
3
  *
4
- * Thin transport around export.mjs: framing, JSON-RPC dispatch, two tools.
4
+ * Thin transport around export.mjs: framing, JSON-RPC dispatch, four tools
5
+ * (export, doctor, and two setup helpers from lib/mcp-setup.mjs).
5
6
  * Settings: user file (~/.config/markdown-pdf-export/settings.json) or the
6
7
  * MARKDOWN_PDF_SETTINGS env var, plus the nearest .markdown-pdf.json — see
7
8
  * lib/settings-loader.mjs.
8
9
  */
10
+ import path from "node:path";
9
11
  import process from "node:process";
10
12
  import { fileURLToPath } from "node:url";
11
13
 
@@ -15,9 +17,20 @@ import {
15
17
  debugLog,
16
18
  exportMarkdownPdf,
17
19
  doctorMarkdownPdf,
20
+ installBrowser,
21
+ launchBrowser,
22
+ reloadSettings,
18
23
  } from "./export.mjs";
24
+ import { createBrowserInstaller, launchStudio } from "./lib/mcp-setup.mjs";
19
25
  import { TOOLS } from "./tool-schemas.mjs";
20
26
 
27
+ const CLI_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), "cli.mjs");
28
+ const NO_BROWSER = "No usable Chrome/Chromium browser found";
29
+ const MCP_BROWSER_HINT =
30
+ "No Chrome or Edge found. Ask the user, then call install_browser_markdown_pdf " +
31
+ "to download Chromium (about 200 MB).";
32
+ const browserInstaller = createBrowserInstaller(() => installBrowser());
33
+
21
34
  debugLog(`server starting — pid=${process.pid} node=${process.execPath}`);
22
35
  debugLog(`argv=${JSON.stringify(process.argv)}`);
23
36
  debugLog(`cwd=${process.cwd()}`);
@@ -232,21 +245,94 @@ async function callTool(name, args) {
232
245
  try {
233
246
  switch (name) {
234
247
  case "export_markdown_pdf":
248
+ // Pick up edits made in Studio (or by hand) since the server started.
249
+ reloadSettings();
235
250
  return toolResult(await exportMarkdownPdf(args));
236
251
 
237
252
  case "doctor_markdown_pdf":
238
- return toolResult(await doctorMarkdownPdf(args));
253
+ reloadSettings();
254
+ return toolResult(await doctor(args));
255
+
256
+ case "install_browser_markdown_pdf":
257
+ return toolResult(await installBrowserTool(args));
258
+
259
+ case "open_studio_markdown_pdf":
260
+ return toolResult(await openStudioTool(args));
239
261
 
240
262
  default:
241
263
  throw new Error(`Unknown tool: ${name}`);
242
264
  }
243
265
  } catch (error) {
244
- const message = error instanceof Error ? error.message : String(error);
266
+ let message = error instanceof Error ? error.message : String(error);
267
+ if (message.includes(NO_BROWSER)) message += `\n\n${MCP_BROWSER_HINT}`;
245
268
  debugLog(`callTool(${name}) error: ${message}`);
246
269
  return toolError(message);
247
270
  }
248
271
  }
249
272
 
273
+ async function doctor(args) {
274
+ const report = await doctorMarkdownPdf(args);
275
+ if (report.browser && !report.browser.available) {
276
+ report.browser.hint =
277
+ browserInstaller.status() === "installing"
278
+ ? "Chromium is downloading. Check again in a minute."
279
+ : MCP_BROWSER_HINT;
280
+ if (browserInstaller.status() === "failed") {
281
+ report.browser.last_install_error = browserInstaller.lastError();
282
+ }
283
+ }
284
+ return report;
285
+ }
286
+
287
+ async function installBrowserTool(args) {
288
+ if (!args.force && browserInstaller.status() !== "installing") {
289
+ try {
290
+ const browser = await launchBrowser();
291
+ const version = browser.version();
292
+ await browser.close();
293
+ return {
294
+ status: "already_available",
295
+ browser: version,
296
+ message: "A browser already works; nothing was downloaded. Pass force: true to download Chromium anyway.",
297
+ };
298
+ } catch {
299
+ // none found → download below
300
+ }
301
+ }
302
+ const status = await browserInstaller.run();
303
+ return status === "installed"
304
+ ? { status, message: "Chromium is installed. PDFs can be exported now." }
305
+ : {
306
+ status,
307
+ message: "The download is still running (about 200 MB). Call doctor_markdown_pdf in a minute to check.",
308
+ };
309
+ }
310
+
311
+ async function openStudioTool(args) {
312
+ const studio = await launchStudio({
313
+ cliPath: CLI_PATH,
314
+ file: args.file,
315
+ projectFolder: args.project_folder,
316
+ openBrowser: args.open_browser !== false,
317
+ });
318
+ const result = {
319
+ url: studio.url,
320
+ settings_file: studio.settingsPath,
321
+ message:
322
+ (args.open_browser === false
323
+ ? "Studio is running. Give the user this private link."
324
+ : "Studio is open in the browser. If no page appeared, give the user this private link.") +
325
+ " Choices saved in Studio apply to the next export. Studio stops by itself a few minutes after its page is closed.",
326
+ };
327
+ const env = (process.env.MARKDOWN_PDF_SETTINGS ?? "").trim();
328
+ if (env && env !== "{}" && !args.project_folder) {
329
+ result.warning =
330
+ "This server reads its settings from MARKDOWN_PDF_SETTINGS, not from the file Studio edits, " +
331
+ "so Studio changes will not apply to exports until that variable is removed.";
332
+ }
333
+ return result;
334
+ }
335
+
250
336
  function toolResult(data) {
251
337
  return {
252
338
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markdown-pdf-export",
3
- "version": "2.1.1",
3
+ "version": "2.2.0",
4
4
  "description": "Markdown to PDF with your header, footer, page numbers and logo. Design pages in Studio, export from VS Code, Zed, Cursor, Claude or any MCP client, or the command line.",
5
5
  "type": "module",
6
6
  "mcpName": "io.github.matinfo-tech/markdown-pdf-export",
package/tool-schemas.mjs CHANGED
@@ -203,6 +203,40 @@ export const DOCTOR_INPUT_SCHEMA = {
203
203
  },
204
204
  };
205
205
 
206
+ export const INSTALL_BROWSER_INPUT_SCHEMA = {
207
+ type: "object",
208
+ additionalProperties: false,
209
+ properties: {
210
+ force: {
211
+ type: "boolean",
212
+ description:
213
+ "Download even when a working browser is already found. Default: false.",
214
+ },
215
+ },
216
+ };
217
+
218
+ export const OPEN_STUDIO_INPUT_SCHEMA = {
219
+ type: "object",
220
+ additionalProperties: false,
221
+ properties: {
222
+ file: {
223
+ type: "string",
224
+ description:
225
+ "Markdown file to preview instead of the built-in sample. Use an absolute path.",
226
+ },
227
+ project_folder: {
228
+ type: "string",
229
+ description:
230
+ "Edit the settings of this folder only (its .markdown-pdf.json) instead of the user settings used by every document. Use an absolute path.",
231
+ },
232
+ open_browser: {
233
+ type: "boolean",
234
+ description:
235
+ "Open Studio in the default browser. Default: true. The private link is returned either way.",
236
+ },
237
+ },
238
+ };
239
+
206
240
  export const TOOLS = [
207
241
  {
208
242
  name: "export_markdown_pdf",
@@ -218,4 +252,24 @@ export const TOOLS = [
218
252
  "Inspect browser setup and current settings.",
219
253
  inputSchema: DOCTOR_INPUT_SCHEMA,
220
254
  },
255
+ {
256
+ name: "install_browser_markdown_pdf",
257
+ title: "Install browser for Markdown PDF",
258
+ description:
259
+ "Download Playwright's Chromium (about 200 MB), the browser that draws the PDF. " +
260
+ "Only needed when doctor_markdown_pdf reports no browser (no Chrome or Edge on this computer). " +
261
+ "Ask the user before calling it. Returns status \"installing\" if the download is still running; " +
262
+ "call doctor_markdown_pdf a minute later to check.",
263
+ inputSchema: INSTALL_BROWSER_INPUT_SCHEMA,
264
+ },
265
+ {
266
+ name: "open_studio_markdown_pdf",
267
+ title: "Open Markdown PDF Studio",
268
+ description:
269
+ "Open Studio, a local page with a live PDF preview, to choose the page style, font, " +
270
+ "header, footer and logo. Saved choices apply to every later export. " +
271
+ "Use when the user wants to change how their PDFs look in general; for a one-off change, " +
272
+ "pass arguments to export_markdown_pdf instead.",
273
+ inputSchema: OPEN_STUDIO_INPUT_SCHEMA,
274
+ },
221
275
  ];