bookstack-mcp 5.3.0 → 5.4.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.md CHANGED
@@ -17,7 +17,7 @@ npx bookstack-mcp
17
17
 
18
18
  ## Features
19
19
 
20
- - 20 read-only tools + 18 write tools for complete BookStack API coverage
20
+ - 20 read-only tools + 20 write tools for complete BookStack API coverage
21
21
  - Books, chapters, pages, shelves, attachments, and comments — full CRUD
22
22
  - Recycle bin support — restore or permanently delete soft-deleted content
23
23
  - Type-safe input validation with Zod (auto-coerces string/number params for broad client compatibility)
@@ -242,7 +242,7 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
242
242
  | `get_shelves` / `get_shelf` | List or get shelf details |
243
243
  | `get_attachments` / `get_attachment` | List or get attachment details |
244
244
  | `get_comments` / `get_comment` | List or get page comments (BookStack v25.11+) |
245
- | `find_users` | Look up BookStack users by name, email, or slug to resolve numeric user IDs for search filters |
245
+ | `find_users` | Look up BookStack users by name, email, or slug to resolve user slugs for `{created_by:X}`-style search filters |
246
246
  | `get_recycle_bin` | List items in the recycle bin |
247
247
  | `export_page` | Export page as HTML, PDF, Markdown, plaintext, or ZIP |
248
248
  | `export_book` | Export entire book |
@@ -253,8 +253,8 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
253
253
 
254
254
  | Tool | Description |
255
255
  |------|-------------|
256
- | `create_book` / `delete_book` | Create or delete a book |
257
- | `create_chapter` / `delete_chapter` | Create or delete a chapter |
256
+ | `create_book` / `update_book` / `delete_book` | Create, update, or delete a book |
257
+ | `create_chapter` / `update_chapter` / `delete_chapter` | Create, update (including moving to a different book or reordering), or delete a chapter |
258
258
  | `create_page` | Create a new page (HTML or Markdown) |
259
259
  | `update_page` | Update content, rename, or move to a different book/chapter |
260
260
  | `delete_page` | Delete a page (recoverable from recycle bin) |
@@ -271,6 +271,12 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
271
271
  4. In the **API Tokens** section, create a new token
272
272
  5. Copy the Token ID and Token Secret
273
273
 
274
+ > **Also grant the role “Export Content”** if you read pages written in the
275
+ > WYSIWYG editor. BookStack returns an empty `markdown` body for those pages, and
276
+ > `get_page` recovers it from the server-side HTML→markdown export endpoint. Without
277
+ > the permission that fallback fails and the page reads as empty. The default Viewer
278
+ > role does not include it.
279
+
274
280
  ## Security
275
281
 
276
282
  - Write operations are **disabled by default**
@@ -1,6 +1,7 @@
1
1
  import axios from 'axios';
2
2
  import https from 'https';
3
3
  import { Semaphore } from './util/semaphore.js';
4
+ import { countWords } from './util/word-count.js';
4
5
  const MAX_RETRIES_429 = 5;
5
6
  function parseRetryAfter(value) {
6
7
  if (typeof value !== 'string' || !value)
@@ -13,16 +14,20 @@ function parseRetryAfter(value) {
13
14
  return Math.max(0, dateMs - Date.now());
14
15
  return null;
15
16
  }
16
- // BookStack's advanced search silently ignores {created_by:X}/{updated_by:X}/{owned_by:X}
17
- // when X isn't a numeric user ID — the query falls back to unfiltered results, which is
18
- // a confusing footgun. Reject the bad form up front and point the caller at find_users.
17
+ // BookStack resolves {created_by:X}/{updated_by:X}/{owned_by:X} by user SLUG, with 'me'
18
+ // as a shortcut for the token's own user, and silently SKIPS the filter when X matches no
19
+ // user's slug — the query falls back to unfiltered results, which is a confusing footgun
20
+ // (SearchRunner::filterCreatedBy et al. look users up by slug only). A numeric user ID is
21
+ // the classic way to hit it, so reject that form up front and point the caller at
22
+ // find_users for the slug.
19
23
  function validateUserIdFilters(query) {
20
- const re = /\{(created_by|updated_by|owned_by):([^}\s]+)\}/g;
24
+ const re = /\{(!?)(created_by|updated_by|owned_by):([^}\s]+)\}/g;
21
25
  for (const match of query.matchAll(re)) {
22
- const [, field, value] = match;
23
- if (!/^\d+$/.test(value)) {
24
- throw new Error(`Search filter {${field}:${value}} requires a numeric user ID, not "${value}". ` +
25
- `Use the find_users tool to look up a user's ID by name, email, or slug.`);
26
+ const [, neg, field, value] = match;
27
+ if (/^\d+$/.test(value)) {
28
+ throw new Error(`Search filter {${neg}${field}:${value}} takes a user slug or 'me', not a numeric user ID — ` +
29
+ `BookStack resolves these filters by slug and silently returns unfiltered results for ` +
30
+ `unmatched values. Use the find_users tool to look up a user's slug by name or email.`);
26
31
  }
27
32
  }
28
33
  }
@@ -240,7 +245,7 @@ export class BookStackClient {
240
245
  return {
241
246
  ...pageMeta,
242
247
  url,
243
- word_count: page.text ? page.text.split(' ').length : 0,
248
+ word_count: countWords(page),
244
249
  content_format: format,
245
250
  content_total_chars: totalChars,
246
251
  content_offset: offset,
@@ -442,6 +447,20 @@ export class BookStackClient {
442
447
  const response = await this.client.post('/chapters', data);
443
448
  return await this.enhanceChapterResponse(response.data);
444
449
  }
450
+ async updateBook(id, data) {
451
+ if (!this.enableWrite) {
452
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
453
+ }
454
+ const response = await this.client.put(`/books/${id}`, data);
455
+ return this.enhanceBookResponse(response.data);
456
+ }
457
+ async updateChapter(id, data) {
458
+ if (!this.enableWrite) {
459
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
460
+ }
461
+ const response = await this.client.put(`/chapters/${id}`, data);
462
+ return await this.enhanceChapterResponse(response.data);
463
+ }
445
464
  async createPage(data) {
446
465
  if (!this.enableWrite) {
447
466
  throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ import { z } from "zod";
12
12
  import { BookStackClient } from "./bookstack-client.js";
13
13
  import { registerPrompts } from "./prompts.js";
14
14
  import { loadOAuthConfig, initOAuthStore, handleOAuthRoutes, validateBearer, sendUnauthorized } from "./oauth/entra-proxy.js";
15
+ import { SessionRegistry } from "./session-registry.js";
15
16
  const PKG_VERSION = (() => {
16
17
  try {
17
18
  const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
@@ -152,7 +153,7 @@ function registerTools(server, client, config) {
152
153
  // Common params (offset/count/sort/filter/id) are self-describing and intentionally
153
154
  // bare so tool definitions stay compact in the MCP tools/list payload.
154
155
  readTool("search_content", {
155
- description: "Search BookStack content. Supports advanced syntax like {type:page} or {book_id:5}. {created_by:X}/{updated_by:X}/{owned_by:X} need a numeric user ID — use find_users to resolve names.",
156
+ description: "Search BookStack content. Supports advanced syntax like {type:page} or {book_id:5}. {created_by:X}/{updated_by:X}/{owned_by:X} take a user slug or 'me' — use find_users to resolve names to slugs.",
156
157
  inputSchema: {
157
158
  query: z.string(),
158
159
  type: z.enum(["book", "page", "chapter", "bookshelf"]).optional(),
@@ -434,7 +435,7 @@ function registerTools(server, client, config) {
434
435
  };
435
436
  });
436
437
  readTool("find_users", {
437
- description: "List users; filter by name/email/slug (partial match). Resolves names to numeric user IDs for {created_by:X}/{updated_by:X}/{owned_by:X} search filters. Requires admin token.",
438
+ description: "List users; filter by name/email/slug (partial match). Resolves names to user slugs for {created_by:X}/{updated_by:X}/{owned_by:X} search filters. Requires admin token.",
438
439
  inputSchema: {
439
440
  name: z.string().optional(),
440
441
  email: z.string().optional(),
@@ -522,6 +523,52 @@ function registerTools(server, client, config) {
522
523
  content: [{ type: "text", text: JSON.stringify(chapter) }]
523
524
  };
524
525
  });
526
+ writeTool("update_book", {
527
+ description: "Update an existing book",
528
+ inputSchema: {
529
+ id: z.coerce.number().min(1),
530
+ name: z.string().optional().describe("New book name"),
531
+ description: z.string().optional().describe("New book description"),
532
+ tags: z.array(z.object({
533
+ name: z.string(),
534
+ value: z.string()
535
+ }).strict()).optional().describe("Tags for the book")
536
+ }
537
+ }, async (args) => {
538
+ const book = await client.updateBook(args.id, {
539
+ name: args.name,
540
+ description: args.description,
541
+ tags: args.tags
542
+ });
543
+ return {
544
+ content: [{ type: "text", text: JSON.stringify(book) }]
545
+ };
546
+ });
547
+ writeTool("update_chapter", {
548
+ description: "Update an existing chapter. Pass book_id to move the chapter to a different book, or priority to reorder it within its book.",
549
+ inputSchema: {
550
+ id: z.coerce.number().min(1),
551
+ name: z.string().optional().describe("New chapter name"),
552
+ description: z.string().optional().describe("New chapter description"),
553
+ book_id: z.coerce.number().min(1).optional().describe("Optional: Move chapter to this book"),
554
+ priority: z.coerce.number().int().min(0).optional().describe("Optional: Reorder chapter within its book (non-negative integer, lower sorts first)"),
555
+ tags: z.array(z.object({
556
+ name: z.string(),
557
+ value: z.string()
558
+ }).strict()).optional().describe("Tags for the chapter")
559
+ }
560
+ }, async (args) => {
561
+ const chapter = await client.updateChapter(args.id, {
562
+ name: args.name,
563
+ description: args.description,
564
+ book_id: args.book_id,
565
+ priority: args.priority,
566
+ tags: args.tags
567
+ });
568
+ return {
569
+ content: [{ type: "text", text: JSON.stringify(chapter) }]
570
+ };
571
+ });
525
572
  writeTool("create_page", {
526
573
  description: "Create a new page in BookStack",
527
574
  inputSchema: {
@@ -801,9 +848,13 @@ async function startHttp(config) {
801
848
  : hostHeader.split(":")[0];
802
849
  return allowedHosts.includes(hostname) ? null : `Host '${hostname}' not allowed`;
803
850
  };
804
- const transports = {};
805
- // Per-session auth binding (OAuth mode only): subject + resolved write status, fixed at init.
806
- const sessionAuth = {};
851
+ const idleTtlRaw = process.env.BOOKSTACK_SESSION_IDLE_TTL_MS;
852
+ const idleTtlParsed = idleTtlRaw ? parseInt(idleTtlRaw, 10) : NaN;
853
+ const idleTtlMs = Number.isFinite(idleTtlParsed) && idleTtlParsed > 0 ? idleTtlParsed : undefined;
854
+ const maxSessionsRaw = process.env.BOOKSTACK_MAX_SESSIONS;
855
+ const maxSessionsParsed = maxSessionsRaw ? parseInt(maxSessionsRaw, 10) : NaN;
856
+ const maxSessions = Number.isFinite(maxSessionsParsed) && maxSessionsParsed > 0 ? maxSessionsParsed : undefined;
857
+ const sessions = new SessionRegistry({ idleTtlMs, maxSessions });
807
858
  const readJsonBody = (req) => new Promise((resolve, reject) => {
808
859
  const chunks = [];
809
860
  req.on("data", (c) => chunks.push(c));
@@ -855,9 +906,10 @@ async function startHttp(config) {
855
906
  if (req.method === "POST") {
856
907
  parsedBody = await readJsonBody(req);
857
908
  }
858
- if (sessionId && transports[sessionId]) {
909
+ if (sessionId && sessions.has(sessionId)) {
859
910
  // Reject a valid token belonging to a different subject than the session was bound to.
860
- if (config.oauth && sessionAuth[sessionId] && auth?.sub !== sessionAuth[sessionId].sub) {
911
+ const boundAuth = sessions.getAuth(sessionId);
912
+ if (config.oauth && boundAuth && auth?.sub !== boundAuth.sub) {
861
913
  sendJson(res, 403, {
862
914
  jsonrpc: "2.0",
863
915
  error: { code: -32003, message: "Forbidden: token does not match session" },
@@ -865,9 +917,17 @@ async function startHttp(config) {
865
917
  });
866
918
  return;
867
919
  }
868
- transport = transports[sessionId];
920
+ transport = sessions.get(sessionId);
869
921
  }
870
922
  else if (!sessionId && req.method === "POST" && isInitializeRequest(parsedBody)) {
923
+ if (sessions.atCapacity()) {
924
+ sendJson(res, 503, {
925
+ jsonrpc: "2.0",
926
+ error: { code: -32000, message: "Server busy: maximum concurrent sessions reached" },
927
+ id: null
928
+ });
929
+ return;
930
+ }
871
931
  // Choose the per-session credential: writers (with a write token configured) get the
872
932
  // write token and write tools; everyone else gets the read-only token.
873
933
  const useWrite = !!(auth?.isWriter && config.write);
@@ -875,17 +935,13 @@ async function startHttp(config) {
875
935
  transport = new StreamableHTTPServerTransport({
876
936
  sessionIdGenerator: () => randomUUID(),
877
937
  onsessioninitialized: (sid) => {
878
- transports[sid] = transport;
879
- if (config.oauth && auth)
880
- sessionAuth[sid] = auth;
938
+ sessions.register(sid, transport, config.oauth && auth ? auth : undefined);
881
939
  }
882
940
  });
883
941
  transport.onclose = () => {
884
942
  const sid = transport.sessionId;
885
- if (sid && transports[sid])
886
- delete transports[sid];
887
- if (sid && sessionAuth[sid])
888
- delete sessionAuth[sid];
943
+ if (sid)
944
+ sessions.delete(sid);
889
945
  };
890
946
  const server = buildServer(sessionConfig);
891
947
  await server.connect(transport);
@@ -903,7 +959,13 @@ async function startHttp(config) {
903
959
  }
904
960
  // Health check
905
961
  if (pathname === "/health" || pathname === "/") {
906
- sendJson(res, 200, { status: "ok", server: "bookstack-mcp", transport: "http" });
962
+ sendJson(res, 200, {
963
+ status: "ok",
964
+ server: "bookstack-mcp",
965
+ transport: "http",
966
+ sessions: sessions.size(),
967
+ memoryRssBytes: process.memoryUsage().rss
968
+ });
907
969
  return;
908
970
  }
909
971
  sendJson(res, 404, { error: "Not Found" });
@@ -925,16 +987,18 @@ async function startHttp(config) {
925
987
  console.error(allowedHosts
926
988
  ? ` Allowed Host headers: ${allowedHosts.join(", ")}`
927
989
  : ` Host header validation: DISABLED (set MCP_HTTP_ALLOWED_HOSTS to enable)`);
990
+ console.error(` Session limits: idle TTL ${Math.round(sessions.idleTtlMs / 60000)}m, max concurrent ${sessions.maxSessions}`);
928
991
  });
929
992
  const shutdown = async () => {
930
993
  console.error("Shutting down HTTP server...");
931
- for (const sid of Object.keys(transports)) {
994
+ for (const sid of sessions.sessionIds()) {
932
995
  try {
933
- await transports[sid].close();
996
+ await sessions.get(sid)?.close();
934
997
  }
935
998
  catch { }
936
- delete transports[sid];
999
+ sessions.delete(sid);
937
1000
  }
1001
+ sessions.dispose();
938
1002
  httpServer.close(() => process.exit(0));
939
1003
  };
940
1004
  process.on("SIGINT", shutdown);
@@ -0,0 +1,95 @@
1
+ // Production traffic shows SSE streams recycling roughly every 5 minutes as normal,
2
+ // healthy behavior (reconnect/backoff churn). 30 minutes gives 6x that margin, so a
3
+ // normal reconnect cycle — even a slow or retried one — never gets mistaken for an
4
+ // abandoned session, while still bounding how long a truly abandoned session's
5
+ // transport (and the McpServer + tool closures it holds) can leak.
6
+ const DEFAULT_IDLE_TTL_MS = 30 * 60 * 1000;
7
+ // Sweep cadence mirrors oauth/kv-store.ts's InMemoryKvStore.
8
+ const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
9
+ // Hard cap as a second line of defense: bounds worst-case memory even if the TTL
10
+ // logic has a bug, or a burst of sessions arrives faster than a sweep tick.
11
+ const DEFAULT_MAX_SESSIONS = 1000;
12
+ /**
13
+ * Tracks live StreamableHTTPServerTransport sessions and their OAuth binding for the
14
+ * HTTP transport. Mirrors oauth/kv-store.ts's InMemoryKvStore: a periodic sweep
15
+ * (`setInterval`, `.unref()`'d) evicts sessions idle longer than `idleTtlMs`, with a
16
+ * lazy expiry check on access as a backstop between sweeps. `maxSessions` is a hard
17
+ * cap enforced independently of the TTL. `dispose()` stops the sweep timer.
18
+ */
19
+ export class SessionRegistry {
20
+ transports = {};
21
+ sessionAuth = {};
22
+ lastSeen = {};
23
+ idleTtlMs;
24
+ maxSessions;
25
+ sweep;
26
+ constructor(options = {}) {
27
+ this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
28
+ this.maxSessions = options.maxSessions ?? DEFAULT_MAX_SESSIONS;
29
+ const sweepIntervalMs = options.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
30
+ this.sweep = setInterval(() => this.sweepExpired(), sweepIntervalMs);
31
+ this.sweep.unref?.();
32
+ }
33
+ /** Closes the transport (best-effort) before dropping it from bookkeeping, mirroring shutdown(). */
34
+ evict(sessionId) {
35
+ this.transports[sessionId]?.close().catch(() => { });
36
+ this.delete(sessionId);
37
+ }
38
+ sweepExpired() {
39
+ const now = Date.now();
40
+ for (const sid of Object.keys(this.transports)) {
41
+ if (now - (this.lastSeen[sid] ?? 0) >= this.idleTtlMs)
42
+ this.evict(sid);
43
+ }
44
+ }
45
+ /** Evicts sessionId if idle-expired. Returns true if it was (or already is) absent. */
46
+ purgeIfExpired(sessionId) {
47
+ if (!(sessionId in this.transports))
48
+ return true;
49
+ const seen = this.lastSeen[sessionId];
50
+ if (seen === undefined || Date.now() - seen >= this.idleTtlMs) {
51
+ this.evict(sessionId);
52
+ return true;
53
+ }
54
+ return false;
55
+ }
56
+ has(sessionId) {
57
+ return !this.purgeIfExpired(sessionId);
58
+ }
59
+ /** Also refreshes the session's idle timer — every real request is a keep-alive. */
60
+ get(sessionId) {
61
+ if (this.purgeIfExpired(sessionId))
62
+ return undefined;
63
+ this.lastSeen[sessionId] = Date.now();
64
+ return this.transports[sessionId];
65
+ }
66
+ getAuth(sessionId) {
67
+ if (this.purgeIfExpired(sessionId))
68
+ return undefined;
69
+ return this.sessionAuth[sessionId];
70
+ }
71
+ atCapacity() {
72
+ return this.size() >= this.maxSessions;
73
+ }
74
+ register(sessionId, transport, auth) {
75
+ this.transports[sessionId] = transport;
76
+ this.lastSeen[sessionId] = Date.now();
77
+ if (auth)
78
+ this.sessionAuth[sessionId] = auth;
79
+ }
80
+ delete(sessionId) {
81
+ delete this.transports[sessionId];
82
+ delete this.sessionAuth[sessionId];
83
+ delete this.lastSeen[sessionId];
84
+ }
85
+ sessionIds() {
86
+ return Object.keys(this.transports);
87
+ }
88
+ size() {
89
+ return this.sessionIds().length;
90
+ }
91
+ dispose() {
92
+ if (this.sweep)
93
+ clearInterval(this.sweep);
94
+ }
95
+ }
@@ -0,0 +1,16 @@
1
+ // BookStack only populates page.text for markdown-authored pages. For pages
2
+ // written in the WYSIWYG editor it comes back empty, so a word count taken
3
+ // from page.text alone reports 0 for pages that plainly have content (#10).
4
+ // Fall back to whichever body the response actually carries.
5
+ function stripHtml(html) {
6
+ return html
7
+ .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
8
+ .replace(/<[^>]+>/g, ' ')
9
+ .replace(/&nbsp;/gi, ' ');
10
+ }
11
+ export function countWords(page) {
12
+ const source = page.text || page.markdown || (page.html ? stripHtml(page.html) : '');
13
+ // Split on any whitespace, not a single space: a page whose lines are
14
+ // newline-separated counts as one word under /' '/.
15
+ return source.split(/\s+/).filter(Boolean).length;
16
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bookstack-mcp",
3
- "version": "5.3.0",
3
+ "version": "5.4.0",
4
4
  "description": "MCP server for BookStack wiki — search, read, create, and manage documentation via AI assistants",
5
5
  "type": "module",
6
6
  "bin": {