bookstack-mcp 3.5.0 → 5.1.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/dist/index.js CHANGED
@@ -10,6 +10,8 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
10
10
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
11
11
  import { z } from "zod";
12
12
  import { BookStackClient } from "./bookstack-client.js";
13
+ import { registerPrompts } from "./prompts.js";
14
+ import { loadOAuthConfig, initOAuthStore, handleOAuthRoutes, validateBearer, sendUnauthorized } from "./oauth/entra-proxy.js";
13
15
  const PKG_VERSION = (() => {
14
16
  try {
15
17
  const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
@@ -45,6 +47,7 @@ function buildServer(config) {
45
47
  });
46
48
  registerTools(server, client, config);
47
49
  registerResources(server, client);
50
+ registerPrompts(server);
48
51
  return server;
49
52
  }
50
53
  function registerResources(server, client) {
@@ -56,7 +59,7 @@ function registerResources(server, client) {
56
59
  resources: (books.data ?? []).map((b) => ({
57
60
  uri: `bookstack://book/${b.id}`,
58
61
  name: b.name,
59
- description: b.summary ?? b.description ?? undefined,
62
+ description: b.description ?? undefined,
60
63
  mimeType: "application/json"
61
64
  }))
62
65
  };
@@ -70,7 +73,6 @@ function registerResources(server, client) {
70
73
  }
71
74
  }
72
75
  }), {
73
- title: "BookStack Book",
74
76
  description: "A BookStack book exposed as an MCP resource",
75
77
  mimeType: "application/json"
76
78
  }, async (uri, variables) => {
@@ -83,7 +85,7 @@ function registerResources(server, client) {
83
85
  contents: [{
84
86
  uri: uri.href,
85
87
  mimeType: "application/json",
86
- text: JSON.stringify(book, null, 2)
88
+ text: JSON.stringify(book)
87
89
  }]
88
90
  };
89
91
  });
@@ -95,7 +97,7 @@ function registerResources(server, client) {
95
97
  resources: (pages.data ?? []).map((p) => ({
96
98
  uri: `bookstack://page/${p.id}`,
97
99
  name: p.name,
98
- description: p.content_preview ?? p.location ?? undefined,
100
+ description: p.content_preview ?? undefined,
99
101
  mimeType: "text/markdown"
100
102
  }))
101
103
  };
@@ -109,7 +111,6 @@ function registerResources(server, client) {
109
111
  }
110
112
  }
111
113
  }), {
112
- title: "BookStack Page",
113
114
  description: "A BookStack page exposed as an MCP resource (markdown content)",
114
115
  mimeType: "text/markdown"
115
116
  }, async (uri, variables) => {
@@ -133,10 +134,10 @@ function registerResources(server, client) {
133
134
  chapter_id: page.chapter_id,
134
135
  url: page.url,
135
136
  word_count: page.word_count,
136
- last_updated_friendly: page.last_updated_friendly,
137
+ updated_at: page.updated_at,
137
138
  content_truncated: page.content_truncated,
138
139
  content_total_chars: page.content_total_chars
139
- }, null, 2)
140
+ })
140
141
  }]
141
142
  };
142
143
  });
@@ -147,35 +148,16 @@ function registerTools(server, client, config) {
147
148
  // to the SDK's generic overloads at the call sites.
148
149
  const readTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...READ_ONLY_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, handler));
149
150
  const writeTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...WRITE_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, handler));
150
- // Register read-only tools
151
- readTool("get_capabilities", {
152
- title: "Get BookStack Capabilities",
153
- description: "Get information about available BookStack MCP capabilities and current configuration",
154
- inputSchema: {}
155
- }, async () => {
156
- const capabilities = {
157
- server_name: "BookStack MCP Server",
158
- version: PKG_VERSION,
159
- write_operations_enabled: config.enableWrite,
160
- available_tools: config.enableWrite ? "All tools enabled" : "Read-only tools only",
161
- security_note: config.enableWrite
162
- ? "⚠️ Write operations are ENABLED - AI can create and modify BookStack content"
163
- : "🛡️ Read-only mode - Safe for production use"
164
- };
165
- return {
166
- content: [{ type: "text", text: JSON.stringify(capabilities, null, 2) }]
167
- };
168
- });
151
+ // Register read-only tools.
152
+ // Common params (offset/count/sort/filter/id) are self-describing and intentionally
153
+ // bare so tool definitions stay compact in the MCP tools/list payload.
169
154
  readTool("search_content", {
170
- title: "Search BookStack Content",
171
- description: "Search across BookStack content with contextual previews and location info. Supports BookStack's advanced search syntax — see the query parameter for caveats.",
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.",
172
156
  inputSchema: {
173
- query: z.string().describe("Search query. Supports BookStack advanced search syntax like {type:page} or {book_id:5}. " +
174
- "Caveat: {created_by:X}, {updated_by:X}, and {owned_by:X} require a numeric user ID — pass a name and BookStack silently ignores the filter, returning the unfiltered query. " +
175
- "Use the find_users tool to resolve names to IDs."),
176
- type: z.enum(["book", "page", "chapter", "bookshelf"]).optional().describe("Filter by content type"),
177
- count: z.coerce.number().max(500).optional().describe("Number of results to return (max 500)"),
178
- offset: z.coerce.number().optional().describe("Number of results to skip for pagination")
157
+ query: z.string(),
158
+ type: z.enum(["book", "page", "chapter", "bookshelf"]).optional(),
159
+ count: z.coerce.number().max(500).optional(),
160
+ offset: z.coerce.number().optional()
179
161
  }
180
162
  }, async (args) => {
181
163
  const results = await client.searchContent(args.query, {
@@ -183,20 +165,15 @@ function registerTools(server, client, config) {
183
165
  count: args.count,
184
166
  offset: args.offset
185
167
  });
186
- return {
187
- content: [{ type: "text", text: JSON.stringify(results, null, 2) }]
188
- };
168
+ return { content: [{ type: "text", text: JSON.stringify(results) }] };
189
169
  });
190
170
  readTool("search_pages", {
191
- title: "Search Pages",
192
- description: "Search specifically for pages with optional book filtering. Same advanced-search caveats as search_content — see the query parameter.",
171
+ description: "Search BookStack pages, optionally within a book. Same user-ID caveat as search_content.",
193
172
  inputSchema: {
194
- query: z.string().describe("Search query for pages. Supports BookStack advanced search syntax. " +
195
- "Caveat: {created_by:X}, {updated_by:X}, and {owned_by:X} require a numeric user ID — pass a name and BookStack silently ignores the filter. " +
196
- "Use the find_users tool to resolve names to IDs."),
197
- book_id: z.coerce.number().optional().describe("Filter results to pages within a specific book"),
198
- count: z.coerce.number().max(500).optional().describe("Number of results to return"),
199
- offset: z.coerce.number().optional().describe("Pagination offset")
173
+ query: z.string(),
174
+ book_id: z.coerce.number().optional(),
175
+ count: z.coerce.number().max(500).optional(),
176
+ offset: z.coerce.number().optional()
200
177
  }
201
178
  }, async (args) => {
202
179
  const results = await client.searchPages(args.query, {
@@ -204,18 +181,15 @@ function registerTools(server, client, config) {
204
181
  count: args.count,
205
182
  offset: args.offset
206
183
  });
207
- return {
208
- content: [{ type: "text", text: JSON.stringify(results, null, 2) }]
209
- };
184
+ return { content: [{ type: "text", text: JSON.stringify(results) }] };
210
185
  });
211
186
  readTool("get_books", {
212
- title: "List Books",
213
- description: "List available books with advanced filtering and sorting",
187
+ description: "List books with optional filter/sort.",
214
188
  inputSchema: {
215
- offset: z.coerce.number().default(0).describe("Pagination offset"),
216
- count: z.coerce.number().max(500).default(50).describe("Number of results to return"),
217
- sort: z.string().optional().describe("Sort field (e.g., 'name', '-created_at', 'updated_at')"),
218
- filter: z.record(z.any()).optional().describe("Filter criteria")
189
+ offset: z.coerce.number().default(0),
190
+ count: z.coerce.number().max(500).default(50),
191
+ sort: z.string().optional(),
192
+ filter: z.record(z.any()).optional()
219
193
  }
220
194
  }, async (args) => {
221
195
  const books = await client.getBooks({
@@ -225,31 +199,29 @@ function registerTools(server, client, config) {
225
199
  filter: args.filter
226
200
  });
227
201
  return {
228
- content: [{ type: "text", text: JSON.stringify(books, null, 2) }]
202
+ content: [{ type: "text", text: JSON.stringify(books) }]
229
203
  };
230
204
  });
231
205
  readTool("get_book", {
232
- title: "Get Book Details",
233
- description: "Get detailed information about a specific book",
206
+ description: "Get a book.",
234
207
  inputSchema: {
235
- id: z.coerce.number().min(1).describe("Book ID")
208
+ id: z.coerce.number().min(1)
236
209
  }
237
210
  }, async (args) => {
238
211
  const book = await client.getBook(args.id);
239
212
  return {
240
- content: [{ type: "text", text: JSON.stringify(book, null, 2) }]
213
+ content: [{ type: "text", text: JSON.stringify(book) }]
241
214
  };
242
215
  });
243
216
  readTool("get_pages", {
244
- title: "List Pages",
245
- description: "List pages with content previews, word counts, and contextual information",
217
+ description: "List pages with previews.",
246
218
  inputSchema: {
247
- book_id: z.coerce.number().optional().describe("Filter by book ID"),
248
- chapter_id: z.coerce.number().optional().describe("Filter by chapter ID"),
249
- offset: z.coerce.number().default(0).describe("Pagination offset"),
250
- count: z.coerce.number().max(500).default(50).describe("Number of results to return"),
251
- sort: z.string().optional().describe("Sort field"),
252
- filter: z.record(z.any()).optional().describe("Additional filter criteria")
219
+ book_id: z.coerce.number().optional(),
220
+ chapter_id: z.coerce.number().optional(),
221
+ offset: z.coerce.number().default(0),
222
+ count: z.coerce.number().max(500).default(50),
223
+ sort: z.string().optional(),
224
+ filter: z.record(z.any()).optional()
253
225
  }
254
226
  }, async (args) => {
255
227
  const pages = await client.getPages({
@@ -261,14 +233,13 @@ function registerTools(server, client, config) {
261
233
  filter: args.filter
262
234
  });
263
235
  return {
264
- content: [{ type: "text", text: JSON.stringify(pages, null, 2) }]
236
+ content: [{ type: "text", text: JSON.stringify(pages) }]
265
237
  };
266
238
  });
267
239
  readTool("get_page", {
268
- title: "Get Page Content",
269
- description: "Get content of a specific page. Returns one content format (default markdown) and supports character-range pagination so large pages don't blow the context window. Use offset/limit or the returned content_next_offset to page through long content.",
240
+ description: "Get a page. Returns one format (default markdown); use offset/limit + content_next_offset to paginate large pages.",
270
241
  inputSchema: {
271
- id: z.coerce.number().min(1).describe("Page ID"),
242
+ id: z.coerce.number().min(1),
272
243
  format: z.enum(["markdown", "html", "text"]).optional().describe("Which content format to return. Defaults to markdown."),
273
244
  offset: z.coerce.number().min(0).optional().describe("Character offset into the content to start from (default 0)"),
274
245
  limit: z.coerce.number().min(1).max(200000).optional().describe("Max characters of content to return (default 50000)")
@@ -280,127 +251,87 @@ function registerTools(server, client, config) {
280
251
  limit: args.limit
281
252
  });
282
253
  return {
283
- content: [{ type: "text", text: JSON.stringify(page, null, 2) }]
254
+ content: [{ type: "text", text: JSON.stringify(page) }]
284
255
  };
285
256
  });
286
257
  readTool("get_chapters", {
287
- title: "List Chapters",
288
- description: "List chapters, optionally filtered by book",
258
+ description: "List chapters; optional book_id.",
289
259
  inputSchema: {
290
- book_id: z.coerce.number().optional().describe("Filter by book ID"),
291
- offset: z.coerce.number().default(0).describe("Pagination offset"),
292
- count: z.coerce.number().default(50).describe("Number of results to return")
260
+ book_id: z.coerce.number().optional(),
261
+ offset: z.coerce.number().default(0),
262
+ count: z.coerce.number().default(50)
293
263
  }
294
264
  }, async (args) => {
295
265
  const chapters = await client.getChapters(args.book_id, args.offset, args.count);
296
266
  return {
297
- content: [{ type: "text", text: JSON.stringify(chapters, null, 2) }]
267
+ content: [{ type: "text", text: JSON.stringify(chapters) }]
298
268
  };
299
269
  });
300
270
  readTool("get_chapter", {
301
- title: "Get Chapter Details",
302
- description: "Get details of a specific chapter",
271
+ description: "Get a chapter.",
303
272
  inputSchema: {
304
- id: z.coerce.number().min(1).describe("Chapter ID")
273
+ id: z.coerce.number().min(1)
305
274
  }
306
275
  }, async (args) => {
307
276
  const chapter = await client.getChapter(args.id);
308
277
  return {
309
- content: [{ type: "text", text: JSON.stringify(chapter, null, 2) }]
278
+ content: [{ type: "text", text: JSON.stringify(chapter) }]
310
279
  };
311
280
  });
312
281
  readTool("export_page", {
313
- title: "Export Page",
314
- description: "Export a page in various formats (PDF/ZIP provide direct BookStack download URLs)",
282
+ description: "Export a page (PDF/ZIP return download URL).",
315
283
  inputSchema: {
316
- id: z.coerce.number().min(1).describe("Page ID"),
317
- format: z.enum(["html", "pdf", "markdown", "plaintext", "zip"]).describe("Export format")
284
+ id: z.coerce.number().min(1),
285
+ format: z.enum(["html", "pdf", "markdown", "plaintext", "zip"])
318
286
  }
319
287
  }, async (args) => {
320
288
  const content = await client.exportPage(args.id, args.format);
321
- // Handle binary formats with direct URLs
322
- if (typeof content === 'object' && content.download_url && content.direct_download) {
323
- const format = args.format.toUpperCase();
324
- return {
325
- content: [{
326
- type: "text",
327
- text: `✅ **${format} Export Ready**\n\n` +
328
- `📄 **Page:** ${content.page_name}\n` +
329
- `📚 **Book:** ${content.book_name}\n` +
330
- `📁 **File:** ${content.filename}\n\n` +
331
- `🚀 **Direct Download Link:**\n${content.download_url}\n\n` +
332
- `ℹ️ **Note:** ${content.note}`
333
- }]
334
- };
289
+ if (typeof content === 'object' && content.download_url) {
290
+ return { content: [{ type: "text", text: JSON.stringify(content) }] };
335
291
  }
336
- // Handle text formats
337
- const text = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
292
+ const text = typeof content === 'string' ? content : JSON.stringify(content);
338
293
  return {
339
294
  content: [{ type: "text", text }]
340
295
  };
341
296
  });
342
297
  readTool("export_book", {
343
- title: "Export Book",
344
- description: "Export an entire book in various formats",
298
+ description: "Export a book.",
345
299
  inputSchema: {
346
- id: z.coerce.number().min(1).describe("Book ID"),
347
- format: z.enum(["html", "pdf", "markdown", "plaintext", "zip"]).describe("Export format")
300
+ id: z.coerce.number().min(1),
301
+ format: z.enum(["html", "pdf", "markdown", "plaintext", "zip"])
348
302
  }
349
303
  }, async (args) => {
350
304
  const content = await client.exportBook(args.id, args.format);
351
305
  if (typeof content === 'object' && content.download_url) {
352
- const format = args.format.toUpperCase();
353
- return {
354
- content: [{
355
- type: "text",
356
- text: `✅ **${format} Book Export Ready**\n\n` +
357
- `📚 **Book:** ${content.book_name}\n` +
358
- `📁 **File:** ${content.filename}\n\n` +
359
- `🚀 **Direct Download Link:**\n${content.download_url}\n\n` +
360
- `ℹ️ **Note:** ${content.note}`
361
- }]
362
- };
306
+ return { content: [{ type: "text", text: JSON.stringify(content) }] };
363
307
  }
364
- const text = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
308
+ const text = typeof content === 'string' ? content : JSON.stringify(content);
365
309
  return {
366
310
  content: [{ type: "text", text }]
367
311
  };
368
312
  });
369
313
  readTool("export_chapter", {
370
- title: "Export Chapter",
371
- description: "Export a chapter in various formats",
314
+ description: "Export a chapter.",
372
315
  inputSchema: {
373
- id: z.coerce.number().min(1).describe("Chapter ID"),
374
- format: z.enum(["html", "pdf", "markdown", "plaintext", "zip"]).describe("Export format")
316
+ id: z.coerce.number().min(1),
317
+ format: z.enum(["html", "pdf", "markdown", "plaintext", "zip"])
375
318
  }
376
319
  }, async (args) => {
377
320
  const content = await client.exportChapter(args.id, args.format);
378
321
  if (typeof content === 'object' && content.download_url) {
379
- const format = args.format.toUpperCase();
380
- return {
381
- content: [{
382
- type: "text",
383
- text: `✅ **${format} Chapter Export Ready**\n\n` +
384
- `📖 **Chapter:** ${content.chapter_name}\n` +
385
- `📚 **Book:** ${content.book_name}\n` +
386
- `📁 **File:** ${content.filename}\n\n` +
387
- `🚀 **Direct Download Link:**\n${content.download_url}\n\n` +
388
- `ℹ️ **Note:** ${content.note}`
389
- }]
390
- };
322
+ return { content: [{ type: "text", text: JSON.stringify(content) }] };
391
323
  }
392
- const text = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
324
+ const text = typeof content === 'string' ? content : JSON.stringify(content);
393
325
  return {
394
326
  content: [{ type: "text", text }]
395
327
  };
396
328
  });
397
329
  readTool("get_recent_changes", {
398
- title: "Get Recent Changes",
399
- description: "Get recently updated content with contextual previews and change descriptions",
330
+ description: "List content updated in the last N days.",
400
331
  inputSchema: {
401
- type: z.enum(["all", "page", "book", "chapter"]).default("all").describe("Filter by content type"),
402
- limit: z.coerce.number().max(100).default(20).describe("Number of recent items to return"),
403
- days: z.coerce.number().default(30).describe("Number of days back to look for changes")
332
+ type: z.enum(["all", "page", "book", "chapter"]).default("all"),
333
+ limit: z.coerce.number().max(100).default(20),
334
+ days: z.coerce.number().default(30)
404
335
  }
405
336
  }, async (args) => {
406
337
  const changes = await client.getRecentChanges({
@@ -409,17 +340,16 @@ function registerTools(server, client, config) {
409
340
  days: args.days
410
341
  });
411
342
  return {
412
- content: [{ type: "text", text: JSON.stringify(changes, null, 2) }]
343
+ content: [{ type: "text", text: JSON.stringify(changes) }]
413
344
  };
414
345
  });
415
346
  readTool("get_shelves", {
416
- title: "List Shelves",
417
- description: "List available book shelves (collections) with filtering and sorting",
347
+ description: "List shelves (book collections).",
418
348
  inputSchema: {
419
- offset: z.coerce.number().default(0).describe("Pagination offset"),
420
- count: z.coerce.number().max(500).default(50).describe("Number of results to return"),
421
- sort: z.string().optional().describe("Sort field"),
422
- filter: z.record(z.any()).optional().describe("Filter criteria")
349
+ offset: z.coerce.number().default(0),
350
+ count: z.coerce.number().max(500).default(50),
351
+ sort: z.string().optional(),
352
+ filter: z.record(z.any()).optional()
423
353
  }
424
354
  }, async (args) => {
425
355
  const shelves = await client.getShelves({
@@ -429,29 +359,27 @@ function registerTools(server, client, config) {
429
359
  filter: args.filter
430
360
  });
431
361
  return {
432
- content: [{ type: "text", text: JSON.stringify(shelves, null, 2) }]
362
+ content: [{ type: "text", text: JSON.stringify(shelves) }]
433
363
  };
434
364
  });
435
365
  readTool("get_shelf", {
436
- title: "Get Shelf Details",
437
- description: "Get details of a specific book shelf including all books",
366
+ description: "Get a shelf including its books.",
438
367
  inputSchema: {
439
- id: z.coerce.number().min(1).describe("Shelf ID")
368
+ id: z.coerce.number().min(1)
440
369
  }
441
370
  }, async (args) => {
442
371
  const shelf = await client.getShelf(args.id);
443
372
  return {
444
- content: [{ type: "text", text: JSON.stringify(shelf, null, 2) }]
373
+ content: [{ type: "text", text: JSON.stringify(shelf) }]
445
374
  };
446
375
  });
447
376
  readTool("get_attachments", {
448
- title: "List Attachments",
449
- description: "List attachments (files and links) with filtering and sorting",
377
+ description: "List attachments (files and links).",
450
378
  inputSchema: {
451
- offset: z.coerce.number().default(0).describe("Pagination offset"),
452
- count: z.coerce.number().max(500).default(50).describe("Number of results to return"),
453
- sort: z.string().optional().describe("Sort field"),
454
- filter: z.record(z.any()).optional().describe("Filter criteria")
379
+ offset: z.coerce.number().default(0),
380
+ count: z.coerce.number().max(500).default(50),
381
+ sort: z.string().optional(),
382
+ filter: z.record(z.any()).optional()
455
383
  }
456
384
  }, async (args) => {
457
385
  const attachments = await client.getAttachments({
@@ -461,29 +389,27 @@ function registerTools(server, client, config) {
461
389
  filter: args.filter
462
390
  });
463
391
  return {
464
- content: [{ type: "text", text: JSON.stringify(attachments, null, 2) }]
392
+ content: [{ type: "text", text: JSON.stringify(attachments) }]
465
393
  };
466
394
  });
467
395
  readTool("get_attachment", {
468
- title: "Get Attachment Details",
469
- description: "Get details of a specific attachment including download links",
396
+ description: "Get an attachment with download_url.",
470
397
  inputSchema: {
471
- id: z.coerce.number().min(1).describe("Attachment ID")
398
+ id: z.coerce.number().min(1)
472
399
  }
473
400
  }, async (args) => {
474
401
  const attachment = await client.getAttachment(args.id);
475
402
  return {
476
- content: [{ type: "text", text: JSON.stringify(attachment, null, 2) }]
403
+ content: [{ type: "text", text: JSON.stringify(attachment) }]
477
404
  };
478
405
  });
479
406
  readTool("get_comments", {
480
- title: "List Comments",
481
- description: "List comments, optionally filtered to a single page. Requires BookStack v25.11+.",
407
+ description: "List comments (optional page_id). BookStack v25.11+.",
482
408
  inputSchema: {
483
- page_id: z.coerce.number().optional().describe("Filter to comments on this page"),
484
- offset: z.coerce.number().default(0).describe("Pagination offset"),
485
- count: z.coerce.number().max(500).default(50).describe("Number of results to return"),
486
- sort: z.string().optional().describe("Sort field")
409
+ page_id: z.coerce.number().optional(),
410
+ offset: z.coerce.number().default(0),
411
+ count: z.coerce.number().max(500).default(50),
412
+ sort: z.string().optional()
487
413
  }
488
414
  }, async (args) => {
489
415
  const comments = await client.getComments({
@@ -493,31 +419,29 @@ function registerTools(server, client, config) {
493
419
  sort: args.sort
494
420
  });
495
421
  return {
496
- content: [{ type: "text", text: JSON.stringify(comments, null, 2) }]
422
+ content: [{ type: "text", text: JSON.stringify(comments) }]
497
423
  };
498
424
  });
499
425
  readTool("get_comment", {
500
- title: "Get Comment",
501
- description: "Get a single comment by ID. Requires BookStack v25.11+.",
426
+ description: "Get a comment. BookStack v25.11+.",
502
427
  inputSchema: {
503
- id: z.coerce.number().min(1).describe("Comment ID")
428
+ id: z.coerce.number().min(1)
504
429
  }
505
430
  }, async (args) => {
506
431
  const comment = await client.getComment(args.id);
507
432
  return {
508
- content: [{ type: "text", text: JSON.stringify(comment, null, 2) }]
433
+ content: [{ type: "text", text: JSON.stringify(comment) }]
509
434
  };
510
435
  });
511
436
  readTool("find_users", {
512
- title: "Find Users",
513
- description: "List BookStack users with optional filtering by name, email, or slug. Use this to resolve a person's name into the numeric user ID needed for {created_by:X}/{updated_by:X}/{owned_by:X} search filters and for the filter parameter on get_pages, get_books, etc. Requires admin permissions on the API token.",
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.",
514
438
  inputSchema: {
515
- name: z.string().optional().describe("Filter by user display name (partial match)"),
516
- email: z.string().optional().describe("Filter by email address (partial match)"),
517
- slug: z.string().optional().describe("Filter by URL slug (e.g. \"jane-doe\")"),
518
- offset: z.coerce.number().default(0).describe("Pagination offset"),
519
- count: z.coerce.number().max(500).default(50).describe("Number of results to return"),
520
- sort: z.string().optional().describe("Sort field (e.g. 'name', '-created_at')")
439
+ name: z.string().optional(),
440
+ email: z.string().optional(),
441
+ slug: z.string().optional(),
442
+ offset: z.coerce.number().default(0),
443
+ count: z.coerce.number().max(500).default(50),
444
+ sort: z.string().optional()
521
445
  }
522
446
  }, async (args) => {
523
447
  const filter = {};
@@ -534,16 +458,15 @@ function registerTools(server, client, config) {
534
458
  filter: Object.keys(filter).length ? filter : undefined
535
459
  });
536
460
  return {
537
- content: [{ type: "text", text: JSON.stringify(users, null, 2) }]
461
+ content: [{ type: "text", text: JSON.stringify(users) }]
538
462
  };
539
463
  });
540
464
  readTool("get_recycle_bin", {
541
- title: "List Recycle Bin",
542
- description: "List items in the recycle bin (deleted books, chapters, pages, shelves). Requires admin permissions on the API token.",
465
+ description: "List recycle-bin items. Admin token required.",
543
466
  inputSchema: {
544
- offset: z.coerce.number().default(0).describe("Pagination offset"),
545
- count: z.coerce.number().max(500).default(50).describe("Number of results to return"),
546
- sort: z.string().optional().describe("Sort field")
467
+ offset: z.coerce.number().default(0),
468
+ count: z.coerce.number().max(500).default(50),
469
+ sort: z.string().optional()
547
470
  }
548
471
  }, async (args) => {
549
472
  const items = await client.getRecycleBin({
@@ -552,13 +475,12 @@ function registerTools(server, client, config) {
552
475
  sort: args.sort
553
476
  });
554
477
  return {
555
- content: [{ type: "text", text: JSON.stringify(items, null, 2) }]
478
+ content: [{ type: "text", text: JSON.stringify(items) }]
556
479
  };
557
480
  });
558
481
  // Register write tools if enabled
559
482
  if (config.enableWrite) {
560
483
  writeTool("create_book", {
561
- title: "Create Book",
562
484
  description: "Create a new book in BookStack",
563
485
  inputSchema: {
564
486
  name: z.string().describe("Book name"),
@@ -575,11 +497,10 @@ function registerTools(server, client, config) {
575
497
  tags: args.tags
576
498
  });
577
499
  return {
578
- content: [{ type: "text", text: JSON.stringify(book, null, 2) }]
500
+ content: [{ type: "text", text: JSON.stringify(book) }]
579
501
  };
580
502
  });
581
503
  writeTool("create_chapter", {
582
- title: "Create Chapter",
583
504
  description: "Create a new chapter within a book",
584
505
  inputSchema: {
585
506
  book_id: z.coerce.number().min(1).describe("Book ID where the chapter will be created"),
@@ -598,11 +519,10 @@ function registerTools(server, client, config) {
598
519
  tags: args.tags
599
520
  });
600
521
  return {
601
- content: [{ type: "text", text: JSON.stringify(chapter, null, 2) }]
522
+ content: [{ type: "text", text: JSON.stringify(chapter) }]
602
523
  };
603
524
  });
604
525
  writeTool("create_page", {
605
- title: "Create Page",
606
526
  description: "Create a new page in BookStack",
607
527
  inputSchema: {
608
528
  name: z.string().describe("Page name"),
@@ -620,14 +540,13 @@ function registerTools(server, client, config) {
620
540
  markdown: args.markdown
621
541
  });
622
542
  return {
623
- content: [{ type: "text", text: JSON.stringify(page, null, 2) }]
543
+ content: [{ type: "text", text: JSON.stringify(page) }]
624
544
  };
625
545
  });
626
546
  writeTool("update_page", {
627
- title: "Update Page",
628
547
  description: "Update an existing page. Pass book_id (and optionally chapter_id) to move the page to a different location.",
629
548
  inputSchema: {
630
- id: z.coerce.number().min(1).describe("Page ID"),
549
+ id: z.coerce.number().min(1),
631
550
  name: z.string().optional().describe("Optional: New page name"),
632
551
  html: z.string().optional().describe("Optional: New HTML content"),
633
552
  markdown: z.string().optional().describe("Optional: New Markdown content"),
@@ -643,11 +562,10 @@ function registerTools(server, client, config) {
643
562
  chapter_id: args.chapter_id
644
563
  });
645
564
  return {
646
- content: [{ type: "text", text: JSON.stringify(page, null, 2) }]
565
+ content: [{ type: "text", text: JSON.stringify(page) }]
647
566
  };
648
567
  });
649
568
  writeTool("create_shelf", {
650
- title: "Create Shelf",
651
569
  description: "Create a new book shelf (collection)",
652
570
  inputSchema: {
653
571
  name: z.string().describe("Shelf name"),
@@ -666,14 +584,13 @@ function registerTools(server, client, config) {
666
584
  tags: args.tags
667
585
  });
668
586
  return {
669
- content: [{ type: "text", text: JSON.stringify(shelf, null, 2) }]
587
+ content: [{ type: "text", text: JSON.stringify(shelf) }]
670
588
  };
671
589
  });
672
590
  writeTool("update_shelf", {
673
- title: "Update Shelf",
674
591
  description: "Update an existing book shelf",
675
592
  inputSchema: {
676
- id: z.coerce.number().min(1).describe("Shelf ID"),
593
+ id: z.coerce.number().min(1),
677
594
  name: z.string().optional().describe("New shelf name"),
678
595
  description: z.string().optional().describe("New shelf description"),
679
596
  books: z.array(z.coerce.number()).optional().describe("Array of book IDs"),
@@ -690,23 +607,21 @@ function registerTools(server, client, config) {
690
607
  tags: args.tags
691
608
  });
692
609
  return {
693
- content: [{ type: "text", text: JSON.stringify(shelf, null, 2) }]
610
+ content: [{ type: "text", text: JSON.stringify(shelf) }]
694
611
  };
695
612
  });
696
613
  writeTool("delete_shelf", {
697
- title: "Delete Shelf",
698
614
  description: "Delete a book shelf (collection)",
699
615
  inputSchema: {
700
- id: z.coerce.number().min(1).describe("Shelf ID")
616
+ id: z.coerce.number().min(1)
701
617
  }
702
618
  }, async (args) => {
703
619
  const result = await client.deleteShelf(args.id);
704
620
  return {
705
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
621
+ content: [{ type: "text", text: JSON.stringify(result) }]
706
622
  };
707
623
  });
708
624
  writeTool("create_attachment", {
709
- title: "Create Attachment",
710
625
  description: "Create a new link attachment to a page",
711
626
  inputSchema: {
712
627
  name: z.string().describe("Attachment name"),
@@ -720,14 +635,13 @@ function registerTools(server, client, config) {
720
635
  link: args.link
721
636
  });
722
637
  return {
723
- content: [{ type: "text", text: JSON.stringify(attachment, null, 2) }]
638
+ content: [{ type: "text", text: JSON.stringify(attachment) }]
724
639
  };
725
640
  });
726
641
  writeTool("update_attachment", {
727
- title: "Update Attachment",
728
642
  description: "Update an existing attachment",
729
643
  inputSchema: {
730
- id: z.coerce.number().min(1).describe("Attachment ID"),
644
+ id: z.coerce.number().min(1),
731
645
  name: z.string().optional().describe("New attachment name"),
732
646
  link: z.string().optional().describe("New URL for link attachment"),
733
647
  uploaded_to: z.coerce.number().optional().describe("Move attachment to different page")
@@ -739,59 +653,54 @@ function registerTools(server, client, config) {
739
653
  uploaded_to: args.uploaded_to
740
654
  });
741
655
  return {
742
- content: [{ type: "text", text: JSON.stringify(attachment, null, 2) }]
656
+ content: [{ type: "text", text: JSON.stringify(attachment) }]
743
657
  };
744
658
  });
745
659
  writeTool("delete_attachment", {
746
- title: "Delete Attachment",
747
660
  description: "Delete an attachment",
748
661
  inputSchema: {
749
- id: z.coerce.number().min(1).describe("Attachment ID")
662
+ id: z.coerce.number().min(1)
750
663
  }
751
664
  }, async (args) => {
752
665
  const result = await client.deleteAttachment(args.id);
753
666
  return {
754
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
667
+ content: [{ type: "text", text: JSON.stringify(result) }]
755
668
  };
756
669
  });
757
670
  writeTool("delete_book", {
758
- title: "Delete Book",
759
671
  description: "Delete a book. Goes to the recycle bin and can be restored from there.",
760
672
  inputSchema: {
761
- id: z.coerce.number().min(1).describe("Book ID")
673
+ id: z.coerce.number().min(1)
762
674
  }
763
675
  }, async (args) => {
764
676
  const result = await client.deleteBook(args.id);
765
677
  return {
766
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
678
+ content: [{ type: "text", text: JSON.stringify(result) }]
767
679
  };
768
680
  });
769
681
  writeTool("delete_chapter", {
770
- title: "Delete Chapter",
771
682
  description: "Delete a chapter. Goes to the recycle bin and can be restored from there.",
772
683
  inputSchema: {
773
- id: z.coerce.number().min(1).describe("Chapter ID")
684
+ id: z.coerce.number().min(1)
774
685
  }
775
686
  }, async (args) => {
776
687
  const result = await client.deleteChapter(args.id);
777
688
  return {
778
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
689
+ content: [{ type: "text", text: JSON.stringify(result) }]
779
690
  };
780
691
  });
781
692
  writeTool("delete_page", {
782
- title: "Delete Page",
783
693
  description: "Delete a page. Goes to the recycle bin and can be restored from there.",
784
694
  inputSchema: {
785
- id: z.coerce.number().min(1).describe("Page ID")
695
+ id: z.coerce.number().min(1)
786
696
  }
787
697
  }, async (args) => {
788
698
  const result = await client.deletePage(args.id);
789
699
  return {
790
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
700
+ content: [{ type: "text", text: JSON.stringify(result) }]
791
701
  };
792
702
  });
793
703
  writeTool("create_comment", {
794
- title: "Create Comment",
795
704
  description: "Add a comment to a page. Pass parent_id to reply to an existing comment. Requires BookStack v25.11+.",
796
705
  inputSchema: {
797
706
  page_id: z.coerce.number().min(1).describe("Page ID to comment on"),
@@ -807,14 +716,13 @@ function registerTools(server, client, config) {
807
716
  content_ref: args.content_ref
808
717
  });
809
718
  return {
810
- content: [{ type: "text", text: JSON.stringify(comment, null, 2) }]
719
+ content: [{ type: "text", text: JSON.stringify(comment) }]
811
720
  };
812
721
  });
813
722
  writeTool("update_comment", {
814
- title: "Update Comment",
815
723
  description: "Edit a comment's body or archive/unarchive it. Requires BookStack v25.11+.",
816
724
  inputSchema: {
817
- id: z.coerce.number().min(1).describe("Comment ID"),
725
+ id: z.coerce.number().min(1),
818
726
  html: z.string().optional().describe("Optional: new HTML body"),
819
727
  archived: z.boolean().optional().describe("Optional: archive (true) or unarchive (false) the comment")
820
728
  }
@@ -824,49 +732,46 @@ function registerTools(server, client, config) {
824
732
  archived: args.archived
825
733
  });
826
734
  return {
827
- content: [{ type: "text", text: JSON.stringify(comment, null, 2) }]
735
+ content: [{ type: "text", text: JSON.stringify(comment) }]
828
736
  };
829
737
  });
830
738
  writeTool("delete_comment", {
831
- title: "Delete Comment",
832
739
  description: "Delete a comment. Requires BookStack v25.11+.",
833
740
  inputSchema: {
834
- id: z.coerce.number().min(1).describe("Comment ID")
741
+ id: z.coerce.number().min(1)
835
742
  }
836
743
  }, async (args) => {
837
744
  const result = await client.deleteComment(args.id);
838
745
  return {
839
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
746
+ content: [{ type: "text", text: JSON.stringify(result) }]
840
747
  };
841
748
  });
842
749
  writeTool("restore_deleted", {
843
- title: "Restore from Recycle Bin",
844
750
  description: "Restore a deleted item from the recycle bin. Use the deletion ID from get_recycle_bin (not the original entity ID). Requires admin permissions.",
845
751
  inputSchema: {
846
- deletion_id: z.coerce.number().min(1).describe("Deletion ID (from get_recycle_bin)")
752
+ deletion_id: z.coerce.number().min(1)
847
753
  }
848
754
  }, async (args) => {
849
755
  const result = await client.restoreFromRecycleBin(args.deletion_id);
850
756
  return {
851
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
757
+ content: [{ type: "text", text: JSON.stringify(result) }]
852
758
  };
853
759
  });
854
760
  writeTool("permanently_delete", {
855
- title: "Permanently Delete from Recycle Bin",
856
761
  description: "PERMANENTLY destroys a deleted item — this cannot be undone. Use the deletion ID from get_recycle_bin. Requires admin permissions.",
857
762
  inputSchema: {
858
- deletion_id: z.coerce.number().min(1).describe("Deletion ID (from get_recycle_bin)")
763
+ deletion_id: z.coerce.number().min(1)
859
764
  }
860
765
  }, async (args) => {
861
766
  const result = await client.destroyFromRecycleBin(args.deletion_id);
862
767
  return {
863
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
768
+ content: [{ type: "text", text: JSON.stringify(result) }]
864
769
  };
865
770
  });
866
771
  }
867
772
  }
868
773
  async function startStdio(config) {
869
- const server = buildServer(config);
774
+ const server = buildServer(config.read);
870
775
  const transport = new StdioServerTransport();
871
776
  await server.connect(transport);
872
777
  console.error("BookStack MCP server running on stdio");
@@ -897,6 +802,8 @@ async function startHttp(config) {
897
802
  return allowedHosts.includes(hostname) ? null : `Host '${hostname}' not allowed`;
898
803
  };
899
804
  const transports = {};
805
+ // Per-session auth binding (OAuth mode only): subject + resolved write status, fixed at init.
806
+ const sessionAuth = {};
900
807
  const readJsonBody = (req) => new Promise((resolve, reject) => {
901
808
  const chunks = [];
902
809
  req.on("data", (c) => chunks.push(c));
@@ -924,10 +831,24 @@ async function startHttp(config) {
924
831
  sendJson(res, 421, { error: "Misdirected Request", message: hostError });
925
832
  return;
926
833
  }
834
+ // OAuth proxy surface (discovery metadata, DCR, authorize/callback/token).
835
+ if (config.oauth && (await handleOAuthRoutes(req, res, config.oauth))) {
836
+ return;
837
+ }
927
838
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
928
839
  const pathname = url.pathname;
929
840
  // Streamable HTTP endpoint (recommended)
930
841
  if (pathname === mcpPath) {
842
+ // Enforce the bearer and resolve the caller's authorization when OAuth is enabled.
843
+ let auth = null;
844
+ if (config.oauth) {
845
+ const result = await validateBearer(req, config.oauth);
846
+ if (!result.ok) {
847
+ sendUnauthorized(res, config.oauth);
848
+ return;
849
+ }
850
+ auth = { sub: result.sub, isWriter: !!result.isWriter };
851
+ }
931
852
  const sessionId = req.headers["mcp-session-id"];
932
853
  let transport;
933
854
  let parsedBody;
@@ -935,21 +856,38 @@ async function startHttp(config) {
935
856
  parsedBody = await readJsonBody(req);
936
857
  }
937
858
  if (sessionId && transports[sessionId]) {
859
+ // 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) {
861
+ sendJson(res, 403, {
862
+ jsonrpc: "2.0",
863
+ error: { code: -32003, message: "Forbidden: token does not match session" },
864
+ id: null
865
+ });
866
+ return;
867
+ }
938
868
  transport = transports[sessionId];
939
869
  }
940
870
  else if (!sessionId && req.method === "POST" && isInitializeRequest(parsedBody)) {
871
+ // Choose the per-session credential: writers (with a write token configured) get the
872
+ // write token and write tools; everyone else gets the read-only token.
873
+ const useWrite = !!(auth?.isWriter && config.write);
874
+ const sessionConfig = useWrite ? config.write : config.read;
941
875
  transport = new StreamableHTTPServerTransport({
942
876
  sessionIdGenerator: () => randomUUID(),
943
877
  onsessioninitialized: (sid) => {
944
878
  transports[sid] = transport;
879
+ if (config.oauth && auth)
880
+ sessionAuth[sid] = auth;
945
881
  }
946
882
  });
947
883
  transport.onclose = () => {
948
884
  const sid = transport.sessionId;
949
885
  if (sid && transports[sid])
950
886
  delete transports[sid];
887
+ if (sid && sessionAuth[sid])
888
+ delete sessionAuth[sid];
951
889
  };
952
- const server = buildServer(config);
890
+ const server = buildServer(sessionConfig);
953
891
  await server.connect(transport);
954
892
  }
955
893
  else {
@@ -1003,17 +941,47 @@ async function startHttp(config) {
1003
941
  process.on("SIGTERM", shutdown);
1004
942
  }
1005
943
  async function main() {
1006
- const config = {
1007
- baseUrl: getRequiredEnvVar('BOOKSTACK_BASE_URL'),
944
+ const baseUrl = getRequiredEnvVar('BOOKSTACK_BASE_URL');
945
+ const insecureSkipTlsVerify = process.env.BOOKSTACK_INSECURE_SKIP_TLS_VERIFY?.toLowerCase() === 'true';
946
+ const envEnableWrite = process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true';
947
+ const oauth = loadOAuthConfig(process.env);
948
+ // Initialize the OAuth broker-state store (Redis when REDIS_URL is set) before
949
+ // the server handles any request, so DCR clients / pending flows / codes persist.
950
+ if (oauth) {
951
+ await initOAuthStore(process.env, oauth.serverUrl);
952
+ }
953
+ // The read-only credential is required. In OAuth mode it always runs read-only (write is
954
+ // reserved for role-bearing sessions on the separate write token); otherwise the legacy
955
+ // BOOKSTACK_ENABLE_WRITE flag governs it.
956
+ const read = {
957
+ baseUrl,
1008
958
  tokenId: getRequiredEnvVar('BOOKSTACK_TOKEN_ID'),
1009
959
  tokenSecret: getRequiredEnvVar('BOOKSTACK_TOKEN_SECRET'),
1010
- enableWrite: process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true',
1011
- insecureSkipTlsVerify: process.env.BOOKSTACK_INSECURE_SKIP_TLS_VERIFY?.toLowerCase() === 'true'
960
+ enableWrite: oauth ? false : envEnableWrite,
961
+ insecureSkipTlsVerify
1012
962
  };
963
+ // The write credential is optional and only used by the OAuth proxy for sessions whose
964
+ // token carries the configured app role.
965
+ const writeTokenId = process.env.BOOKSTACK_WRITE_TOKEN_ID;
966
+ const writeTokenSecret = process.env.BOOKSTACK_WRITE_TOKEN_SECRET;
967
+ const write = (writeTokenId && writeTokenSecret)
968
+ ? { baseUrl, tokenId: writeTokenId, tokenSecret: writeTokenSecret, enableWrite: true, insecureSkipTlsVerify }
969
+ : null;
970
+ const config = { read, write, oauth };
1013
971
  console.error('Initializing BookStack MCP Server...');
1014
- console.error(`BookStack URL: ${config.baseUrl}`);
1015
- console.error(`Write operations: ${config.enableWrite ? 'ENABLED' : 'DISABLED'}`);
1016
- if (config.insecureSkipTlsVerify) {
972
+ console.error(`BookStack URL: ${baseUrl}`);
973
+ if (oauth) {
974
+ console.error(`Auth: Entra OAuth proxy ENABLED (tenant ${oauth.tenantId})`);
975
+ console.error(` Public URL: ${oauth.serverUrl}`);
976
+ console.error(` Write role: ${oauth.writeRole}`);
977
+ if (!write) {
978
+ console.error(' WARNING: no BOOKSTACK_WRITE_TOKEN_ID/SECRET set — all sessions are read-only regardless of role.');
979
+ }
980
+ }
981
+ else {
982
+ console.error(`Auth: none (token-only mode); Write operations: ${read.enableWrite ? 'ENABLED' : 'DISABLED'}`);
983
+ }
984
+ if (insecureSkipTlsVerify) {
1017
985
  console.error('WARNING: TLS certificate verification is DISABLED (BOOKSTACK_INSECURE_SKIP_TLS_VERIFY=true). Connections to BookStack are vulnerable to MITM attacks. Use only with trusted self-signed certs on a trusted network.');
1018
986
  }
1019
987
  const transportMode = (process.env.MCP_TRANSPORT ?? "stdio").toLowerCase();