bookstack-mcp 5.6.1 → 5.7.1

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
@@ -79,6 +79,24 @@ use these tools to order pages and chapters within a book.
79
79
  (1–180 characters), saved as the revision summary in the page's history. It
80
80
  needs BookStack v26.09 or newer; older versions silently ignore it.
81
81
 
82
+ `create_page`, `update_page`, `create_book`, and `update_book` accept `tags`
83
+ as an array of `{ "name": "Environment", "value": "Production" }` objects.
84
+ Use `"value": ""` for a tag with no value. Chapter and shelf create/update
85
+ tools also support tags.
86
+
87
+ On updates, `tags` replaces the entire tag list: omit it to leave tags unchanged,
88
+ or pass `[]` to remove all tags. To add, edit, or remove individual tags, first
89
+ read the entity with `get_page` or `get_book`, then send the revised list,
90
+ including every tag you want to keep. For example:
91
+
92
+ ```json
93
+ {"id": 42, "tags": [{"name": "Environment", "value": "Production"}, {"name": "Reviewed", "value": ""}]}
94
+ ```
95
+
96
+ Pass this to `update_page` or `update_book`. A tag-only update needs no page
97
+ content and preserves the editor source. Tag writes require
98
+ `BOOKSTACK_ENABLE_WRITE=true` and the corresponding BookStack edit permission.
99
+
82
100
  `get_page` accepts `format: "raw"` to return the page's stored editor HTML
83
101
  (BookStack's `raw_html`). The `html` format is the rendered view readers see:
84
102
  page includes are resolved and the content filter has run, so attributes such as
@@ -107,7 +125,10 @@ remain disabled unless `BOOKSTACK_ENABLE_WRITE=true` is set.
107
125
 
108
126
  The manifest supplies the project website, privacy policy, and terms of use for
109
127
  plugin directories, including HOL. The HOL Guard CI workflow scans this manifest
110
- alongside the Claude and Gemini manifests; it does not submit or publish listings.
128
+ alongside the Claude and Gemini manifests. After a passing scan on `main`, a
129
+ separate job sends an authenticated score summary to HOL so the registry can
130
+ show the result checked in CI. PR scans remain read-only. See
131
+ [HOL registry setup](docs/HOL.md) for ownership verification and reporting details.
111
132
 
112
133
  ### Claude Desktop
113
134
 
@@ -231,6 +252,16 @@ the BookStack authorization token. Deleting an image can break existing page ref
231
252
  | `MCP_HTTP_HOST` | `127.0.0.1` | Bind address. Loopback by default for safety |
232
253
  | `MCP_HTTP_ALLOWED_HOSTS` | *(loopback only)* | Comma-separated allowlist of `Host` header hostnames for DNS rebinding protection. Required when binding to a non-loopback address |
233
254
  | `MCP_HTTP_PATH` | `/mcp` | Streamable HTTP endpoint |
255
+ | `MCP_HTTP_MAX_BODY_BYTES` | `10485760` (10 MiB) | Maximum MCP JSON request size in bytes; positive integer |
256
+
257
+ OAuth registration and token request bodies are limited to 64 KiB. Body reads
258
+ must complete within 30 seconds. Oversized bodies return HTTP 413, slow bodies
259
+ return 408, and malformed MCP JSON returns 400 without echoing its contents.
260
+
261
+ OAuth sessions are bound to both the user's identity and current write role.
262
+ If that role changes, the server closes the old session and returns 404 so the
263
+ client reinitializes with the appropriate credential and tool set. OAuth pending
264
+ states and authorization codes are consumed atomically, including with Redis.
234
265
 
235
266
  When binding to `0.0.0.0` (e.g. inside a container reachable from other services), set `MCP_HTTP_ALLOWED_HOSTS` to the hostnames LibreChat will use to reach this server, e.g. `MCP_HTTP_ALLOWED_HOSTS=bookstack-mcp,bookstack-mcp.internal`.
236
267
 
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ import { loadOAuthConfig, initOAuthStore, handleOAuthRoutes, validateBearer, sen
14
14
  import { SessionRegistry } from "./session-registry.js";
15
15
  import { parseRequestCredentials, requestScopedClient, withRequestCredentials } from "./request-credentials.js";
16
16
  import { PublicError, logSafeError, safeError, safeUrlOrigin } from "./util/safe-errors.js";
17
+ import { HttpBodyError, readRequestBody } from "./util/http-body.js";
17
18
  const PKG_VERSION = (() => {
18
19
  try {
19
20
  const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
@@ -563,7 +564,7 @@ function registerTools(server, client, config) {
563
564
  tags: z.array(z.object({
564
565
  name: z.string(),
565
566
  value: z.string()
566
- }).strict()).optional().describe("Tags for the book")
567
+ }).strict()).optional().describe("Replace all book tags. Omit to preserve tags; [] removes all. Read get_book first and include any tags to keep. Use an empty value for a name-only tag.")
567
568
  }
568
569
  }, async (args) => {
569
570
  const book = await client.updateBook(args.id, {
@@ -608,6 +609,10 @@ function registerTools(server, client, config) {
608
609
  chapter_id: z.coerce.number().optional().describe("Optional: Chapter ID if page should be in a chapter"),
609
610
  html: z.string().optional().describe("Optional: HTML content"),
610
611
  markdown: z.string().optional().describe("Optional: Markdown content"),
612
+ tags: z.array(z.object({
613
+ name: z.string(),
614
+ value: z.string()
615
+ }).strict()).optional().describe("Tags for the new page; use an empty value for a name-only tag"),
611
616
  changelog: z.string().min(1).max(180).optional().describe("Optional: Revision changelog message shown in the page history (BookStack v26.09+; older servers ignore it)")
612
617
  }
613
618
  }, async (args) => {
@@ -617,7 +622,8 @@ function registerTools(server, client, config) {
617
622
  chapter_id: args.chapter_id,
618
623
  html: args.html,
619
624
  markdown: args.markdown,
620
- changelog: args.changelog
625
+ changelog: args.changelog,
626
+ tags: args.tags
621
627
  });
622
628
  return {
623
629
  content: [{ type: "text", text: JSON.stringify(page) }]
@@ -633,6 +639,10 @@ function registerTools(server, client, config) {
633
639
  book_id: z.coerce.number().min(1).optional().describe("Optional: Move page to this book"),
634
640
  chapter_id: z.coerce.number().optional().describe("Optional: Move page into this chapter (must belong to the target book; pass 0 to move out of any chapter)"),
635
641
  priority: z.coerce.number().int().min(0).optional().describe("Optional: Sort order (non-negative integer, lower sorts first)"),
642
+ tags: z.array(z.object({
643
+ name: z.string(),
644
+ value: z.string()
645
+ }).strict()).optional().describe("Replace all page tags. Omit to preserve tags; [] removes all. Read get_page first and include any tags to keep. Use an empty value for a name-only tag. Can be updated without sending page content."),
636
646
  changelog: z.string().min(1).max(180).optional().describe("Optional: Revision changelog message shown in the page history (BookStack v26.09+; older servers ignore it)")
637
647
  }
638
648
  }, async (args) => {
@@ -643,7 +653,8 @@ function registerTools(server, client, config) {
643
653
  book_id: args.book_id,
644
654
  chapter_id: args.chapter_id,
645
655
  priority: args.priority,
646
- changelog: args.changelog
656
+ changelog: args.changelog,
657
+ tags: args.tags
647
658
  });
648
659
  return {
649
660
  content: [{ type: "text", text: JSON.stringify(page) }]
@@ -893,22 +904,22 @@ async function startHttp(config) {
893
904
  const maxSessionsParsed = maxSessionsRaw ? parseInt(maxSessionsRaw, 10) : NaN;
894
905
  const maxSessions = Number.isFinite(maxSessionsParsed) && maxSessionsParsed > 0 ? maxSessionsParsed : undefined;
895
906
  const sessions = new SessionRegistry({ idleTtlMs, maxSessions });
896
- const readJsonBody = (req) => new Promise((resolve, reject) => {
897
- const chunks = [];
898
- req.on("data", (c) => chunks.push(c));
899
- req.on("end", () => {
900
- const raw = Buffer.concat(chunks).toString("utf8");
901
- if (!raw)
902
- return resolve(undefined);
903
- try {
904
- resolve(JSON.parse(raw));
905
- }
906
- catch (e) {
907
- reject(e);
908
- }
909
- });
910
- req.on("error", reject);
911
- });
907
+ const maxBodyRaw = process.env.MCP_HTTP_MAX_BODY_BYTES;
908
+ const maxBodyBytes = maxBodyRaw === undefined ? 10 * 1024 * 1024 : Number(maxBodyRaw);
909
+ if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) {
910
+ throw new PublicError('MCP_HTTP_MAX_BODY_BYTES must be a positive integer');
911
+ }
912
+ const readJsonBody = async (req) => {
913
+ const raw = await readRequestBody(req, { maxBytes: maxBodyBytes });
914
+ if (!raw)
915
+ return undefined;
916
+ try {
917
+ return JSON.parse(raw);
918
+ }
919
+ catch {
920
+ throw new HttpBodyError(400, 'Invalid JSON');
921
+ }
922
+ };
912
923
  const sendJson = (res, status, body) => {
913
924
  res.writeHead(status, { "Content-Type": "application/json" });
914
925
  res.end(JSON.stringify(body));
@@ -935,7 +946,7 @@ async function startHttp(config) {
935
946
  let auth = null;
936
947
  if (config.oauth) {
937
948
  const result = await validateBearer(req, config.oauth);
938
- if (!result.ok) {
949
+ if (!result.ok || !result.sub) {
939
950
  sendUnauthorized(res, config.oauth);
940
951
  return;
941
952
  }
@@ -956,12 +967,14 @@ async function startHttp(config) {
956
967
  parsedBody = await readJsonBody(req);
957
968
  }
958
969
  if (sessionId && sessions.has(sessionId)) {
959
- // Reject a valid token belonging to a different subject than the session was bound to.
960
- const boundAuth = sessions.getAuth(sessionId);
961
- if (config.oauth && boundAuth && auth?.sub !== boundAuth.sub) {
962
- sendJson(res, 403, {
970
+ const authorization = config.oauth ? sessions.validateAuth(sessionId, auth) : 'ok';
971
+ if (authorization !== 'ok') {
972
+ const changed = authorization === 'permissions_changed';
973
+ sendJson(res, changed ? 404 : 403, {
963
974
  jsonrpc: "2.0",
964
- error: { code: -32003, message: "Forbidden: token does not match session" },
975
+ error: { code: changed ? -32001 : -32003, message: changed
976
+ ? "Session permissions changed; reinitialize the session"
977
+ : "Forbidden: token does not match session" },
965
978
  id: null
966
979
  });
967
980
  return;
@@ -1038,6 +1051,16 @@ async function startHttp(config) {
1038
1051
  sendJson(res, 404, { error: "Not Found" });
1039
1052
  }
1040
1053
  catch (err) {
1054
+ if (err instanceof HttpBodyError) {
1055
+ if (req.aborted || res.headersSent)
1056
+ return;
1057
+ res.setHeader('Connection', 'close');
1058
+ sendJson(res, err.status, {
1059
+ jsonrpc: '2.0', id: null,
1060
+ error: { code: err.status === 400 ? -32700 : -32600, message: err.message }
1061
+ });
1062
+ return;
1063
+ }
1041
1064
  logSafeError("HTTP handler error", err);
1042
1065
  if (!res.headersSent) {
1043
1066
  sendJson(res, 500, {
@@ -13,6 +13,7 @@ import { randomUUID, createHash, randomBytes } from "node:crypto";
13
13
  import { createRemoteJWKSet, jwtVerify } from "jose";
14
14
  import { InMemoryKvStore, createStore } from "./kv-store.js";
15
15
  import { logSafeError, oauthErrorCode } from "../util/safe-errors.js";
16
+ import { HttpBodyError, readRequestBody } from "../util/http-body.js";
16
17
  // Load config from env. Returns null when OAuth proxy mode is disabled.
17
18
  export function loadOAuthConfig(env) {
18
19
  if (env.MCP_OAUTH_ENABLE?.toLowerCase() !== "true")
@@ -86,13 +87,19 @@ function sendJson(res, status, body) {
86
87
  });
87
88
  res.end(JSON.stringify(body));
88
89
  }
89
- function readBody(req) {
90
- return new Promise((resolve, reject) => {
91
- const chunks = [];
92
- req.on("data", (c) => chunks.push(c));
93
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
94
- req.on("error", reject);
95
- });
90
+ async function readBody(req, res) {
91
+ try {
92
+ return await readRequestBody(req, { maxBytes: 64 * 1024 });
93
+ }
94
+ catch (error) {
95
+ if (!(error instanceof HttpBodyError))
96
+ throw error;
97
+ if (!req.aborted) {
98
+ res.setHeader('Connection', 'close');
99
+ sendJson(res, error.status, { error: 'invalid_request', error_description: error.message });
100
+ }
101
+ return undefined;
102
+ }
96
103
  }
97
104
  function parseForm(raw) {
98
105
  const out = {};
@@ -195,9 +202,12 @@ export async function handleOAuthRoutes(req, res, cfg) {
195
202
  }
196
203
  // RFC 7591 — Dynamic Client Registration (handled locally)
197
204
  if (path === "/register" && req.method === "POST") {
205
+ const raw = await readBody(req, res);
206
+ if (raw === undefined)
207
+ return true;
198
208
  let meta = {};
199
209
  try {
200
- meta = JSON.parse((await readBody(req)) || "{}");
210
+ meta = JSON.parse(raw || "{}");
201
211
  }
202
212
  catch {
203
213
  sendJson(res, 400, { error: "invalid_client_metadata" });
@@ -269,12 +279,11 @@ export async function handleOAuthRoutes(req, res, cfg) {
269
279
  const upstreamState = q.get("state") ?? "";
270
280
  const code = q.get("code") ?? "";
271
281
  const err = q.get("error");
272
- const p = await store.get(`pending:${upstreamState}`);
282
+ const p = await store.take(`pending:${upstreamState}`);
273
283
  if (!p) {
274
284
  sendJson(res, 400, { error: "invalid_state" });
275
285
  return true;
276
286
  }
277
- await store.del(`pending:${upstreamState}`);
278
287
  if (err || !code) {
279
288
  const dest = new URL(p.clientRedirectUri);
280
289
  dest.searchParams.set("error", oauthErrorCode(err, 'invalid_request'));
@@ -333,16 +342,18 @@ export async function handleOAuthRoutes(req, res, cfg) {
333
342
  }
334
343
  // Token endpoint — code exchange (verify PKCE) and refresh pass-through.
335
344
  if (path === "/token" && req.method === "POST") {
336
- const form = parseForm(await readBody(req));
345
+ const raw = await readBody(req, res);
346
+ if (raw === undefined)
347
+ return true;
348
+ const form = parseForm(raw);
337
349
  const grant = form["grant_type"];
338
350
  if (grant === "authorization_code") {
339
- const issued = await store.get(`code:${form["code"] ?? ""}`);
351
+ const issued = await store.take(`code:${form["code"] ?? ""}`);
340
352
  if (!issued) {
341
353
  console.error("[oauth] /token authorization_code: invalid_grant (code not found/expired)");
342
354
  sendJson(res, 400, { error: "invalid_grant" });
343
355
  return true;
344
356
  }
345
- await store.del(`code:${form["code"]}`);
346
357
  const verifier = form["code_verifier"] ?? "";
347
358
  if (!verifier || s256(verifier) !== issued.codeChallenge) {
348
359
  console.error(`[oauth] /token authorization_code: PKCE FAILED (verifier=${verifier ? "present" : "missing"})`);
@@ -31,6 +31,12 @@ export class InMemoryKvStore {
31
31
  async set(key, value, ttlMs) {
32
32
  this.map.set(this.prefix + key, { value, expiresAt: Date.now() + ttlMs });
33
33
  }
34
+ async take(key) {
35
+ const entry = this.map.get(this.prefix + key);
36
+ // No await between lookup and deletion: concurrent consumers get one winner.
37
+ this.map.delete(this.prefix + key);
38
+ return entry && entry.expiresAt > Date.now() ? entry.value : undefined;
39
+ }
34
40
  async del(key) {
35
41
  this.map.delete(this.prefix + key);
36
42
  }
@@ -51,6 +57,11 @@ export class RedisKvStore {
51
57
  const raw = await this.client.get(this.prefix + key);
52
58
  return raw == null ? undefined : JSON.parse(raw);
53
59
  }
60
+ async take(key) {
61
+ // Atomic GET+DEL also works on Redis versions predating GETDEL (6.2).
62
+ const raw = await this.client.eval("local value = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return value", 1, this.prefix + key);
63
+ return raw == null ? undefined : JSON.parse(String(raw));
64
+ }
54
65
  async set(key, value, ttlMs) {
55
66
  await this.client.set(this.prefix + key, JSON.stringify(value), "PX", Math.max(1, Math.floor(ttlMs)));
56
67
  }
@@ -68,6 +68,17 @@ export class SessionRegistry {
68
68
  return undefined;
69
69
  return this.sessionAuth[sessionId];
70
70
  }
71
+ /** A session's tool set and upstream token must match every request's roles. */
72
+ validateAuth(sessionId, current) {
73
+ const bound = this.getAuth(sessionId);
74
+ if (!bound?.sub || !current?.sub || bound.sub !== current.sub)
75
+ return 'forbidden';
76
+ if (bound.isWriter !== current.isWriter) {
77
+ this.evict(sessionId);
78
+ return 'permissions_changed';
79
+ }
80
+ return 'ok';
81
+ }
71
82
  atCapacity() {
72
83
  return this.size() >= this.maxSessions;
73
84
  }
@@ -0,0 +1,55 @@
1
+ import { PublicError } from './safe-errors.js';
2
+ export class HttpBodyError extends PublicError {
3
+ status;
4
+ constructor(status, message) {
5
+ super(message);
6
+ this.status = status;
7
+ }
8
+ }
9
+ /** Bound buffering before JSON/form parsing, including chunked requests. */
10
+ export function readRequestBody(req, { maxBytes, timeoutMs = 30000 }) {
11
+ return new Promise((resolve, reject) => {
12
+ const chunks = [];
13
+ let size = 0;
14
+ const cleanup = () => {
15
+ clearTimeout(timer);
16
+ req.off('data', onData);
17
+ req.off('end', onEnd);
18
+ req.off('error', onError);
19
+ req.off('aborted', onAborted);
20
+ };
21
+ const fail = (error) => {
22
+ cleanup();
23
+ chunks.length = 0;
24
+ // A client can reset its socket after our early rejection.
25
+ req.once('error', () => { });
26
+ // Discard further bytes without buffering; the caller can still send 413.
27
+ req.resume();
28
+ reject(error);
29
+ };
30
+ const onData = (chunk) => {
31
+ size += chunk.length;
32
+ if (size > maxBytes)
33
+ return fail(new HttpBodyError(413, 'Request body too large'));
34
+ chunks.push(chunk);
35
+ };
36
+ const onEnd = () => {
37
+ cleanup();
38
+ resolve(Buffer.concat(chunks, size).toString('utf8'));
39
+ };
40
+ const onError = (error) => fail(error);
41
+ const onAborted = () => fail(new HttpBodyError(400, 'Request body interrupted'));
42
+ const timer = setTimeout(() => fail(new HttpBodyError(408, 'Request body timed out')), timeoutMs);
43
+ timer.unref?.();
44
+ if (req.aborted)
45
+ return onAborted();
46
+ const declared = req.headers['content-length'];
47
+ if (typeof declared === 'string' && Number(declared) > maxBytes) {
48
+ return fail(new HttpBodyError(413, 'Request body too large'));
49
+ }
50
+ req.on('data', onData);
51
+ req.on('end', onEnd);
52
+ req.on('error', onError);
53
+ req.on('aborted', onAborted);
54
+ });
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bookstack-mcp",
3
- "version": "5.6.1",
3
+ "version": "5.7.1",
4
4
  "description": "MCP server for BookStack wiki — search, read, create, and manage documentation via AI assistants",
5
5
  "type": "module",
6
6
  "bin": {
@@ -43,10 +43,10 @@
43
43
  "node": ">=18"
44
44
  },
45
45
  "dependencies": {
46
- "@modelcontextprotocol/sdk": "^1.25.3",
47
- "axios": "^1.6.0",
46
+ "@modelcontextprotocol/sdk": "^1.32.2",
47
+ "axios": "^1.21.0",
48
48
  "ioredis": "^5.11.1",
49
- "jose": "^6.2.3",
49
+ "jose": "^6.2.14",
50
50
  "zod": "^4.6.5"
51
51
  },
52
52
  "devDependencies": {