bookstack-mcp 2.1.1 → 3.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.
package/README.md CHANGED
@@ -1,14 +1,31 @@
1
1
  # BookStack MCP Server
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/bookstack-mcp)](https://www.npmjs.com/package/bookstack-mcp)
4
+ [![npm downloads](https://img.shields.io/npm/dm/bookstack-mcp)](https://www.npmjs.com/package/bookstack-mcp)
5
+ [![CI](https://github.com/ttpears/bookstack-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/ttpears/bookstack-mcp/actions/workflows/ci.yml)
6
+ [![Node.js](https://img.shields.io/node/v/bookstack-mcp)](https://nodejs.org)
7
+ [![MCP](https://img.shields.io/badge/MCP-compatible-7DC9D6)](https://modelcontextprotocol.io)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
+
10
+ <img src="assets/logo.svg" width="96" align="right" alt="bookstack-mcp"/>
11
+
3
12
  A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server that gives AI assistants full access to your [BookStack](https://www.bookstackapp.com) documentation — search, read, create, and manage content.
4
13
 
14
+ ```bash
15
+ npx bookstack-mcp
16
+ ```
17
+
5
18
  ## Features
6
19
 
7
- - 17 read-only tools + 8 write tools for complete BookStack API coverage
20
+ - 20 read-only tools + 18 write tools for complete BookStack API coverage
21
+ - Books, chapters, pages, shelves, attachments, and comments — full CRUD
22
+ - Recycle bin support — restore or permanently delete soft-deleted content
8
23
  - Type-safe input validation with Zod (auto-coerces string/number params for broad client compatibility)
9
24
  - Embedded URLs and content previews in all responses
25
+ - Markdown export fallback for HTML-authored pages, so AI clients always get usable content
10
26
  - Write operations disabled by default for safety
11
- - Works with Claude Desktop, LibreChat, and any MCP-compatible client
27
+ - Works with Claude Desktop, Claude Code, LibreChat, and any MCP-compatible client
28
+ - Stdio and Streamable HTTP transports
12
29
 
13
30
  ## Quick Start
14
31
 
@@ -58,7 +75,7 @@ Add to your Claude Desktop config:
58
75
  }
59
76
  ```
60
77
 
61
- ### LibreChat
78
+ ### LibreChat (stdio, single-user)
62
79
 
63
80
  Add to your `librechat.yaml`:
64
81
 
@@ -75,8 +92,68 @@ mcpServers:
75
92
  BOOKSTACK_TOKEN_SECRET: "your-token-secret"
76
93
  ```
77
94
 
95
+ ### LibreChat (Streamable HTTP, recommended for production / Docker)
96
+
97
+ Run the server as a long-lived HTTP service and point LibreChat at the URL. This is the right setup for multi-user or containerized deployments.
98
+
99
+ Start the server in HTTP mode:
100
+
101
+ ```bash
102
+ MCP_TRANSPORT=http \
103
+ MCP_HTTP_PORT=8080 \
104
+ BOOKSTACK_BASE_URL=https://your-bookstack.com \
105
+ BOOKSTACK_TOKEN_ID=your-token-id \
106
+ BOOKSTACK_TOKEN_SECRET=your-token-secret \
107
+ npx bookstack-mcp
108
+ ```
109
+
110
+ Then configure LibreChat:
111
+
112
+ ```yaml
113
+ mcpServers:
114
+ bookstack:
115
+ type: streamable-http
116
+ url: http://bookstack-mcp:8080/mcp
117
+ ```
118
+
119
+ > **3.0.0 breaking change:** the deprecated HTTP+SSE transport (`GET /sse` + `POST /messages`) has been removed. Streamable HTTP at `/mcp` already speaks SSE for streaming responses, and is the only HTTP transport in current MCP clients. If you're on an older client that needs the legacy endpoints, pin to `bookstack-mcp@2.x`.
120
+
121
+ #### HTTP transport environment variables
122
+
123
+ | Variable | Default | Description |
124
+ |----------|---------|-------------|
125
+ | `MCP_TRANSPORT` | `stdio` | Set to `http` to enable the HTTP server |
126
+ | `MCP_HTTP_PORT` | `8080` | Port to listen on |
127
+ | `MCP_HTTP_HOST` | `127.0.0.1` | Bind address. Loopback by default for safety |
128
+ | `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 |
129
+ | `MCP_HTTP_PATH` | `/mcp` | Streamable HTTP endpoint |
130
+
131
+ 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`.
132
+
78
133
  Restart LibreChat after config changes.
79
134
 
135
+ ### Claude Code (plugin marketplace)
136
+
137
+ This repo ships a Claude Code plugin manifest (`.claude-plugin/plugin.json`). Add the marketplace and install:
138
+
139
+ ```
140
+ /plugin marketplace add ttpears/claude-plugins
141
+ /plugin install bookstack-mcp@ttpears-plugins
142
+ ```
143
+
144
+ Then set the `BOOKSTACK_*` environment variables in your shell so the plugin's MCP server can authenticate.
145
+
146
+ ## MCP Resources
147
+
148
+ Books and pages are also exposed as MCP resources, so clients that browse resources (Claude Desktop, MCP Inspector, etc.) can `@`-mention them directly:
149
+
150
+ | URI template | Description |
151
+ |--------------|-------------|
152
+ | `bookstack://book/{id}` | A book, returned as JSON metadata |
153
+ | `bookstack://page/{id}` | A page, returned as markdown plus a JSON metadata blob |
154
+
155
+ Both templates support `id` autocompletion: as you type, the server searches BookStack and returns matching IDs so you don't have to remember numeric IDs by hand.
156
+
80
157
  ## Available Tools
81
158
 
82
159
  ### Read Operations (always available)
@@ -91,6 +168,8 @@ Restart LibreChat after config changes.
91
168
  | `get_chapters` / `get_chapter` | List or get chapter details |
92
169
  | `get_shelves` / `get_shelf` | List or get shelf details |
93
170
  | `get_attachments` / `get_attachment` | List or get attachment details |
171
+ | `get_comments` / `get_comment` | List or get page comments (BookStack v25.11+) |
172
+ | `get_recycle_bin` | List items in the recycle bin |
94
173
  | `export_page` | Export page as HTML, PDF, Markdown, plaintext, or ZIP |
95
174
  | `export_book` | Export entire book |
96
175
  | `export_chapter` | Export chapter |
@@ -100,9 +179,15 @@ Restart LibreChat after config changes.
100
179
 
101
180
  | Tool | Description |
102
181
  |------|-------------|
103
- | `create_page` / `update_page` | Create or update pages |
182
+ | `create_book` / `delete_book` | Create or delete a book |
183
+ | `create_chapter` / `delete_chapter` | Create or delete a chapter |
184
+ | `create_page` | Create a new page (HTML or Markdown) |
185
+ | `update_page` | Update content, rename, or move to a different book/chapter |
186
+ | `delete_page` | Delete a page (recoverable from recycle bin) |
104
187
  | `create_shelf` / `update_shelf` / `delete_shelf` | Manage shelves |
105
188
  | `create_attachment` / `update_attachment` / `delete_attachment` | Manage attachments |
189
+ | `create_comment` / `update_comment` / `delete_comment` | Manage page comments (v25.11+) |
190
+ | `restore_deleted` / `permanently_delete` | Restore or permanently destroy items in the recycle bin |
106
191
 
107
192
  ## BookStack API Setup
108
193
 
@@ -15,6 +15,15 @@ export class BookStackClient {
15
15
  }
16
16
  });
17
17
  }
18
+ applyFilters(params, filter) {
19
+ if (!filter)
20
+ return;
21
+ for (const [key, value] of Object.entries(filter)) {
22
+ if (value === undefined || value === null)
23
+ continue;
24
+ params[`filter[${key}]`] = value;
25
+ }
26
+ }
18
27
  async getBookSlug(bookId) {
19
28
  // Check cache first
20
29
  if (this.bookSlugCache.has(bookId)) {
@@ -64,21 +73,42 @@ export class BookStackClient {
64
73
  content_info: `Book created ${created}, last updated ${lastUpdated}`
65
74
  };
66
75
  }
67
- async enhancePageResponse(page) {
76
+ async enhancePageResponse(page, options) {
68
77
  const lastUpdated = this.formatDate(page.updated_at);
69
78
  const created = this.formatDate(page.created_at);
70
- const contentPreview = page.text ? `${page.text.substring(0, 200)}${page.text.length > 200 ? '...' : ''}` : 'No content preview available';
71
79
  const url = await this.generatePageUrl(page);
80
+ // Pick a single content format to return to avoid 3x duplication (html + markdown + text)
81
+ const format = options?.format ?? 'markdown';
82
+ const fullContent = (format === 'html' ? page.html : format === 'text' ? page.text : page.markdown) || '';
83
+ // Character-range slicing so very large pages can be paginated
84
+ const DEFAULT_LIMIT = 50000;
85
+ const offset = Math.max(0, options?.offset ?? 0);
86
+ const limit = Math.max(1, options?.limit ?? DEFAULT_LIMIT);
87
+ const totalChars = fullContent.length;
88
+ const slice = fullContent.substring(offset, offset + limit);
89
+ const nextOffset = offset + slice.length;
90
+ const truncated = nextOffset < totalChars;
91
+ // Strip duplicate large fields from the base page object
92
+ const { html: _h, markdown: _m, text: _t, ...pageMeta } = page;
72
93
  return {
73
- ...page,
94
+ ...pageMeta,
74
95
  url,
75
96
  direct_link: `[${page.name}](${url})`,
76
97
  last_updated_friendly: lastUpdated,
77
98
  created_friendly: created,
78
- content_preview: contentPreview,
79
99
  content_info: `Page created ${created}, last updated ${lastUpdated}`,
80
100
  word_count: page.text ? page.text.split(' ').length : 0,
81
- location: `Book ID ${page.book_id}${page.chapter_id ? `, Chapter ID ${page.chapter_id}` : ''}`
101
+ location: `Book ID ${page.book_id}${page.chapter_id ? `, Chapter ID ${page.chapter_id}` : ''}`,
102
+ content_format: format,
103
+ content_total_chars: totalChars,
104
+ content_offset: offset,
105
+ content_returned_chars: slice.length,
106
+ content_truncated: truncated,
107
+ content_next_offset: truncated ? nextOffset : null,
108
+ pagination_hint: truncated
109
+ ? `Only ${nextOffset}/${totalChars} characters returned. Call get_page again with offset=${nextOffset} to continue, or pass a larger limit.`
110
+ : undefined,
111
+ content: slice
82
112
  };
83
113
  }
84
114
  async enhanceChapterResponse(chapter) {
@@ -192,8 +222,7 @@ export class BookStackClient {
192
222
  };
193
223
  if (options?.sort)
194
224
  params.sort = options.sort;
195
- if (options?.filter)
196
- params.filter = JSON.stringify(options.filter);
225
+ this.applyFilters(params, options?.filter);
197
226
  const response = await this.client.get('/books', { params });
198
227
  const data = response.data;
199
228
  return {
@@ -210,32 +239,67 @@ export class BookStackClient {
210
239
  offset: options?.offset || 0,
211
240
  count: Math.min(options?.count || 50, 500)
212
241
  };
213
- // Build filter object
214
242
  const filter = { ...options?.filter };
215
243
  if (options?.bookId)
216
244
  filter.book_id = options.bookId;
217
245
  if (options?.chapterId)
218
246
  filter.chapter_id = options.chapterId;
219
- if (Object.keys(filter).length > 0) {
220
- params.filter = JSON.stringify(filter);
221
- }
247
+ this.applyFilters(params, filter);
222
248
  if (options?.sort)
223
249
  params.sort = options.sort;
224
250
  const response = await this.client.get('/pages', { params });
225
251
  const data = response.data;
226
252
  return {
227
253
  ...data,
228
- data: await Promise.all(data.data.map((page) => this.enhancePageResponse(page)))
254
+ data: await Promise.all(data.data.map((page) => this.enhancePageListItem(page)))
229
255
  };
230
256
  }
231
- async getPage(id) {
257
+ async enhancePageListItem(page) {
258
+ const lastUpdated = this.formatDate(page.updated_at);
259
+ const created = this.formatDate(page.created_at);
260
+ const url = await this.generatePageUrl(page);
261
+ const preview = page.text
262
+ ? `${page.text.substring(0, 200)}${page.text.length > 200 ? '...' : ''}`
263
+ : 'No content preview available';
264
+ // List responses from BookStack don't include html/markdown/text, but strip defensively
265
+ // and never embed full content here — use get_page for that.
266
+ const { html: _h, markdown: _m, text: _t, ...pageMeta } = page;
267
+ return {
268
+ ...pageMeta,
269
+ url,
270
+ direct_link: `[${page.name}](${url})`,
271
+ last_updated_friendly: lastUpdated,
272
+ created_friendly: created,
273
+ content_preview: preview,
274
+ content_info: `Page created ${created}, last updated ${lastUpdated}`,
275
+ location: `Book ID ${page.book_id}${page.chapter_id ? `, Chapter ID ${page.chapter_id}` : ''}`
276
+ };
277
+ }
278
+ async getPage(id, options) {
232
279
  const response = await this.client.get(`/pages/${id}`);
233
- return await this.enhancePageResponse(response.data);
280
+ const pageData = response.data;
281
+ // BookStack stores either markdown or html depending on the editor used to
282
+ // author the page. If markdown was requested but the page was authored in
283
+ // the WYSIWYG editor, page.markdown comes back empty. Fall back to the
284
+ // server-side HTML→markdown export so the caller still gets usable content.
285
+ const requestedFormat = options?.format ?? 'markdown';
286
+ if (requestedFormat === 'markdown' && !pageData.markdown) {
287
+ try {
288
+ const exportResponse = await this.client.get(`/pages/${id}/export/markdown`);
289
+ if (exportResponse.data) {
290
+ pageData.markdown = exportResponse.data;
291
+ }
292
+ }
293
+ catch (error) {
294
+ console.error(`Markdown export fallback failed for page ${id}:`, error);
295
+ }
296
+ }
297
+ return await this.enhancePageResponse(pageData, options);
234
298
  }
235
299
  async getChapters(bookId, offset = 0, count = 50) {
236
300
  const params = { offset, count };
237
301
  if (bookId)
238
- params.filter = JSON.stringify({ book_id: bookId });
302
+ params['filter[book_id]'] = bookId;
239
303
  const response = await this.client.get('/chapters', { params });
240
304
  const data = response.data;
241
305
  return {
@@ -247,6 +311,20 @@ export class BookStackClient {
247
311
  const response = await this.client.get(`/chapters/${id}`);
248
312
  return await this.enhanceChapterResponse(response.data);
249
313
  }
314
+ async createBook(data) {
315
+ if (!this.enableWrite) {
316
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
317
+ }
318
+ const response = await this.client.post('/books', data);
319
+ return this.enhanceBookResponse(response.data);
320
+ }
321
+ async createChapter(data) {
322
+ if (!this.enableWrite) {
323
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
324
+ }
325
+ const response = await this.client.post('/chapters', data);
326
+ return await this.enhanceChapterResponse(response.data);
327
+ }
250
328
  async createPage(data) {
251
329
  if (!this.enableWrite) {
252
330
  throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
@@ -254,6 +332,27 @@ export class BookStackClient {
254
332
  const response = await this.client.post('/pages', data);
255
333
  return await this.enhancePageResponse(response.data);
256
334
  }
335
+ async deleteBook(id) {
336
+ if (!this.enableWrite) {
337
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
338
+ }
339
+ const response = await this.client.delete(`/books/${id}`);
340
+ return response.data;
341
+ }
342
+ async deleteChapter(id) {
343
+ if (!this.enableWrite) {
344
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
345
+ }
346
+ const response = await this.client.delete(`/chapters/${id}`);
347
+ return response.data;
348
+ }
349
+ async deletePage(id) {
350
+ if (!this.enableWrite) {
351
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
352
+ }
353
+ const response = await this.client.delete(`/pages/${id}`);
354
+ return response.data;
355
+ }
257
356
  async updatePage(id, data) {
258
357
  if (!this.enableWrite) {
259
358
  throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
@@ -453,8 +552,7 @@ export class BookStackClient {
453
552
  };
454
553
  if (options?.sort)
455
554
  params.sort = options.sort;
456
- if (options?.filter)
457
- params.filter = JSON.stringify(options.filter);
555
+ this.applyFilters(params, options?.filter);
458
556
  const response = await this.client.get('/shelves', { params });
459
557
  const data = response.data;
460
558
  return {
@@ -495,8 +593,7 @@ export class BookStackClient {
495
593
  };
496
594
  if (options?.sort)
497
595
  params.sort = options.sort;
498
- if (options?.filter)
499
- params.filter = JSON.stringify(options.filter);
596
+ this.applyFilters(params, options?.filter);
500
597
  const response = await this.client.get('/attachments', { params });
501
598
  const data = response.data;
502
599
  return {
@@ -549,4 +646,67 @@ export class BookStackClient {
549
646
  const response = await this.client.delete(`/attachments/${id}`);
550
647
  return response.data;
551
648
  }
649
+ // Comments (BookStack v25.11+)
650
+ async getComments(options) {
651
+ const params = {
652
+ offset: options?.offset || 0,
653
+ count: Math.min(options?.count || 50, 500)
654
+ };
655
+ if (options?.pageId)
656
+ params['filter[commentable_id]'] = options.pageId;
657
+ if (options?.sort)
658
+ params.sort = options.sort;
659
+ const response = await this.client.get('/comments', { params });
660
+ return response.data;
661
+ }
662
+ async getComment(id) {
663
+ const response = await this.client.get(`/comments/${id}`);
664
+ return response.data;
665
+ }
666
+ async createComment(data) {
667
+ if (!this.enableWrite) {
668
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
669
+ }
670
+ const response = await this.client.post('/comments', data);
671
+ return response.data;
672
+ }
673
+ async updateComment(id, data) {
674
+ if (!this.enableWrite) {
675
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
676
+ }
677
+ const response = await this.client.put(`/comments/${id}`, data);
678
+ return response.data;
679
+ }
680
+ async deleteComment(id) {
681
+ if (!this.enableWrite) {
682
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
683
+ }
684
+ const response = await this.client.delete(`/comments/${id}`);
685
+ return response.data;
686
+ }
687
+ // Recycle Bin
688
+ async getRecycleBin(options) {
689
+ const params = {
690
+ offset: options?.offset || 0,
691
+ count: Math.min(options?.count || 50, 500)
692
+ };
693
+ if (options?.sort)
694
+ params.sort = options.sort;
695
+ const response = await this.client.get('/recycle-bin', { params });
696
+ return response.data;
697
+ }
698
+ async restoreFromRecycleBin(deletionId) {
699
+ if (!this.enableWrite) {
700
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
701
+ }
702
+ const response = await this.client.put(`/recycle-bin/${deletionId}`);
703
+ return response.data;
704
+ }
705
+ async destroyFromRecycleBin(deletionId) {
706
+ if (!this.enableWrite) {
707
+ throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
708
+ }
709
+ const response = await this.client.delete(`/recycle-bin/${deletionId}`);
710
+ return response.data;
711
+ }
552
712
  }
package/dist/index.js CHANGED
@@ -1,8 +1,34 @@
1
1
  #!/usr/bin/env node
2
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { createServer as createHttpServer } from "node:http";
3
+ import { randomUUID } from "node:crypto";
4
+ import { readFileSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+ import { dirname, join } from "node:path";
7
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
3
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
10
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
4
11
  import { z } from "zod";
5
12
  import { BookStackClient } from "./bookstack-client.js";
13
+ const PKG_VERSION = (() => {
14
+ try {
15
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
16
+ return JSON.parse(readFileSync(pkgPath, "utf8")).version;
17
+ }
18
+ catch {
19
+ return "0.0.0";
20
+ }
21
+ })();
22
+ const READ_ONLY_ANNOTATIONS = {
23
+ readOnlyHint: true,
24
+ openWorldHint: true
25
+ };
26
+ const WRITE_ANNOTATIONS = {
27
+ readOnlyHint: false,
28
+ destructiveHint: true,
29
+ idempotentHint: false,
30
+ openWorldHint: true
31
+ };
6
32
  function getRequiredEnvVar(name) {
7
33
  const value = process.env[name];
8
34
  if (!value) {
@@ -11,31 +37,125 @@ function getRequiredEnvVar(name) {
11
37
  }
12
38
  return value;
13
39
  }
14
- async function main() {
15
- // Load configuration from environment
16
- const config = {
17
- baseUrl: getRequiredEnvVar('BOOKSTACK_BASE_URL'),
18
- tokenId: getRequiredEnvVar('BOOKSTACK_TOKEN_ID'),
19
- tokenSecret: getRequiredEnvVar('BOOKSTACK_TOKEN_SECRET'),
20
- enableWrite: process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true'
21
- };
22
- console.error('Initializing BookStack MCP Server...');
23
- console.error(`BookStack URL: ${config.baseUrl}`);
24
- console.error(`Write operations: ${config.enableWrite ? 'ENABLED' : 'DISABLED'}`);
40
+ function buildServer(config) {
25
41
  const client = new BookStackClient(config);
26
42
  const server = new McpServer({
27
43
  name: "bookstack-mcp",
28
- version: "2.1.0"
44
+ version: PKG_VERSION
29
45
  });
46
+ registerTools(server, client, config);
47
+ registerResources(server, client);
48
+ return server;
49
+ }
50
+ function registerResources(server, client) {
51
+ // bookstack://book/{id} — every book as a discoverable, addressable resource
52
+ server.registerResource("book", new ResourceTemplate("bookstack://book/{id}", {
53
+ list: async () => {
54
+ const books = await client.getBooks({ count: 500 });
55
+ return {
56
+ resources: (books.data ?? []).map((b) => ({
57
+ uri: `bookstack://book/${b.id}`,
58
+ name: b.name,
59
+ description: b.summary ?? b.description ?? undefined,
60
+ mimeType: "application/json"
61
+ }))
62
+ };
63
+ },
64
+ complete: {
65
+ id: async (value) => {
66
+ if (!value)
67
+ return [];
68
+ const results = await client.searchContent(value, { type: "book", count: 20 });
69
+ return (results.results ?? []).map((r) => String(r.id));
70
+ }
71
+ }
72
+ }), {
73
+ title: "BookStack Book",
74
+ description: "A BookStack book exposed as an MCP resource",
75
+ mimeType: "application/json"
76
+ }, async (uri, variables) => {
77
+ const id = Number(variables.id);
78
+ if (!Number.isFinite(id) || id < 1) {
79
+ throw new Error(`Invalid book id: ${variables.id}`);
80
+ }
81
+ const book = await client.getBook(id);
82
+ return {
83
+ contents: [{
84
+ uri: uri.href,
85
+ mimeType: "application/json",
86
+ text: JSON.stringify(book, null, 2)
87
+ }]
88
+ };
89
+ });
90
+ // bookstack://page/{id} — pages as resources, content returned as markdown
91
+ server.registerResource("page", new ResourceTemplate("bookstack://page/{id}", {
92
+ list: async () => {
93
+ const pages = await client.getPages({ count: 500 });
94
+ return {
95
+ resources: (pages.data ?? []).map((p) => ({
96
+ uri: `bookstack://page/${p.id}`,
97
+ name: p.name,
98
+ description: p.content_preview ?? p.location ?? undefined,
99
+ mimeType: "text/markdown"
100
+ }))
101
+ };
102
+ },
103
+ complete: {
104
+ id: async (value) => {
105
+ if (!value)
106
+ return [];
107
+ const results = await client.searchContent(value, { type: "page", count: 20 });
108
+ return (results.results ?? []).map((r) => String(r.id));
109
+ }
110
+ }
111
+ }), {
112
+ title: "BookStack Page",
113
+ description: "A BookStack page exposed as an MCP resource (markdown content)",
114
+ mimeType: "text/markdown"
115
+ }, async (uri, variables) => {
116
+ const id = Number(variables.id);
117
+ if (!Number.isFinite(id) || id < 1) {
118
+ throw new Error(`Invalid page id: ${variables.id}`);
119
+ }
120
+ const page = await client.getPage(id, { format: "markdown" });
121
+ return {
122
+ contents: [{
123
+ uri: uri.href,
124
+ mimeType: "text/markdown",
125
+ text: page.content ?? ""
126
+ }, {
127
+ uri: `${uri.href}#metadata`,
128
+ mimeType: "application/json",
129
+ text: JSON.stringify({
130
+ id: page.id,
131
+ name: page.name,
132
+ book_id: page.book_id,
133
+ chapter_id: page.chapter_id,
134
+ url: page.url,
135
+ word_count: page.word_count,
136
+ last_updated_friendly: page.last_updated_friendly,
137
+ content_truncated: page.content_truncated,
138
+ content_total_chars: page.content_total_chars
139
+ }, null, 2)
140
+ }]
141
+ };
142
+ });
143
+ }
144
+ function registerTools(server, client, config) {
145
+ // Helpers wrap registerTool and inject MCP tool annotations so clients can
146
+ // distinguish read-only from destructive operations. Typed loosely to defer
147
+ // to the SDK's generic overloads at the call sites.
148
+ const readTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...READ_ONLY_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, handler));
149
+ const writeTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...WRITE_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, handler));
30
150
  // Register read-only tools
31
- server.registerTool("get_capabilities", {
151
+ readTool("get_capabilities", {
32
152
  title: "Get BookStack Capabilities",
33
153
  description: "Get information about available BookStack MCP capabilities and current configuration",
34
154
  inputSchema: {}
35
155
  }, async () => {
36
156
  const capabilities = {
37
157
  server_name: "BookStack MCP Server",
38
- version: "2.1.0",
158
+ version: PKG_VERSION,
39
159
  write_operations_enabled: config.enableWrite,
40
160
  available_tools: config.enableWrite ? "All tools enabled" : "Read-only tools only",
41
161
  security_note: config.enableWrite
@@ -46,7 +166,7 @@ async function main() {
46
166
  content: [{ type: "text", text: JSON.stringify(capabilities, null, 2) }]
47
167
  };
48
168
  });
49
- server.registerTool("search_content", {
169
+ readTool("search_content", {
50
170
  title: "Search BookStack Content",
51
171
  description: "Search across BookStack content with contextual previews and location info",
52
172
  inputSchema: {
@@ -65,7 +185,7 @@ async function main() {
65
185
  content: [{ type: "text", text: JSON.stringify(results, null, 2) }]
66
186
  };
67
187
  });
68
- server.registerTool("search_pages", {
188
+ readTool("search_pages", {
69
189
  title: "Search Pages",
70
190
  description: "Search specifically for pages with optional book filtering",
71
191
  inputSchema: {
@@ -84,7 +204,7 @@ async function main() {
84
204
  content: [{ type: "text", text: JSON.stringify(results, null, 2) }]
85
205
  };
86
206
  });
87
- server.registerTool("get_books", {
207
+ readTool("get_books", {
88
208
  title: "List Books",
89
209
  description: "List available books with advanced filtering and sorting",
90
210
  inputSchema: {
@@ -104,7 +224,7 @@ async function main() {
104
224
  content: [{ type: "text", text: JSON.stringify(books, null, 2) }]
105
225
  };
106
226
  });
107
- server.registerTool("get_book", {
227
+ readTool("get_book", {
108
228
  title: "Get Book Details",
109
229
  description: "Get detailed information about a specific book",
110
230
  inputSchema: {
@@ -116,7 +236,7 @@ async function main() {
116
236
  content: [{ type: "text", text: JSON.stringify(book, null, 2) }]
117
237
  };
118
238
  });
119
- server.registerTool("get_pages", {
239
+ readTool("get_pages", {
120
240
  title: "List Pages",
121
241
  description: "List pages with content previews, word counts, and contextual information",
122
242
  inputSchema: {
@@ -140,19 +260,26 @@ async function main() {
140
260
  content: [{ type: "text", text: JSON.stringify(pages, null, 2) }]
141
261
  };
142
262
  });
143
- server.registerTool("get_page", {
263
+ readTool("get_page", {
144
264
  title: "Get Page Content",
145
- description: "Get full content of a specific page",
265
+ 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.",
146
266
  inputSchema: {
147
- id: z.coerce.number().min(1).describe("Page ID")
267
+ id: z.coerce.number().min(1).describe("Page ID"),
268
+ format: z.enum(["markdown", "html", "text"]).optional().describe("Which content format to return. Defaults to markdown."),
269
+ offset: z.coerce.number().min(0).optional().describe("Character offset into the content to start from (default 0)"),
270
+ limit: z.coerce.number().min(1).max(200000).optional().describe("Max characters of content to return (default 50000)")
148
271
  }
149
272
  }, async (args) => {
150
- const page = await client.getPage(args.id);
273
+ const page = await client.getPage(args.id, {
274
+ format: args.format,
275
+ offset: args.offset,
276
+ limit: args.limit
277
+ });
151
278
  return {
152
279
  content: [{ type: "text", text: JSON.stringify(page, null, 2) }]
153
280
  };
154
281
  });
155
- server.registerTool("get_chapters", {
282
+ readTool("get_chapters", {
156
283
  title: "List Chapters",
157
284
  description: "List chapters, optionally filtered by book",
158
285
  inputSchema: {
@@ -166,7 +293,7 @@ async function main() {
166
293
  content: [{ type: "text", text: JSON.stringify(chapters, null, 2) }]
167
294
  };
168
295
  });
169
- server.registerTool("get_chapter", {
296
+ readTool("get_chapter", {
170
297
  title: "Get Chapter Details",
171
298
  description: "Get details of a specific chapter",
172
299
  inputSchema: {
@@ -178,7 +305,7 @@ async function main() {
178
305
  content: [{ type: "text", text: JSON.stringify(chapter, null, 2) }]
179
306
  };
180
307
  });
181
- server.registerTool("export_page", {
308
+ readTool("export_page", {
182
309
  title: "Export Page",
183
310
  description: "Export a page in various formats (PDF/ZIP provide direct BookStack download URLs)",
184
311
  inputSchema: {
@@ -208,7 +335,7 @@ async function main() {
208
335
  content: [{ type: "text", text }]
209
336
  };
210
337
  });
211
- server.registerTool("export_book", {
338
+ readTool("export_book", {
212
339
  title: "Export Book",
213
340
  description: "Export an entire book in various formats",
214
341
  inputSchema: {
@@ -235,7 +362,7 @@ async function main() {
235
362
  content: [{ type: "text", text }]
236
363
  };
237
364
  });
238
- server.registerTool("export_chapter", {
365
+ readTool("export_chapter", {
239
366
  title: "Export Chapter",
240
367
  description: "Export a chapter in various formats",
241
368
  inputSchema: {
@@ -263,7 +390,7 @@ async function main() {
263
390
  content: [{ type: "text", text }]
264
391
  };
265
392
  });
266
- server.registerTool("get_recent_changes", {
393
+ readTool("get_recent_changes", {
267
394
  title: "Get Recent Changes",
268
395
  description: "Get recently updated content with contextual previews and change descriptions",
269
396
  inputSchema: {
@@ -281,7 +408,7 @@ async function main() {
281
408
  content: [{ type: "text", text: JSON.stringify(changes, null, 2) }]
282
409
  };
283
410
  });
284
- server.registerTool("get_shelves", {
411
+ readTool("get_shelves", {
285
412
  title: "List Shelves",
286
413
  description: "List available book shelves (collections) with filtering and sorting",
287
414
  inputSchema: {
@@ -301,7 +428,7 @@ async function main() {
301
428
  content: [{ type: "text", text: JSON.stringify(shelves, null, 2) }]
302
429
  };
303
430
  });
304
- server.registerTool("get_shelf", {
431
+ readTool("get_shelf", {
305
432
  title: "Get Shelf Details",
306
433
  description: "Get details of a specific book shelf including all books",
307
434
  inputSchema: {
@@ -313,7 +440,7 @@ async function main() {
313
440
  content: [{ type: "text", text: JSON.stringify(shelf, null, 2) }]
314
441
  };
315
442
  });
316
- server.registerTool("get_attachments", {
443
+ readTool("get_attachments", {
317
444
  title: "List Attachments",
318
445
  description: "List attachments (files and links) with filtering and sorting",
319
446
  inputSchema: {
@@ -333,7 +460,7 @@ async function main() {
333
460
  content: [{ type: "text", text: JSON.stringify(attachments, null, 2) }]
334
461
  };
335
462
  });
336
- server.registerTool("get_attachment", {
463
+ readTool("get_attachment", {
337
464
  title: "Get Attachment Details",
338
465
  description: "Get details of a specific attachment including download links",
339
466
  inputSchema: {
@@ -345,9 +472,103 @@ async function main() {
345
472
  content: [{ type: "text", text: JSON.stringify(attachment, null, 2) }]
346
473
  };
347
474
  });
475
+ readTool("get_comments", {
476
+ title: "List Comments",
477
+ description: "List comments, optionally filtered to a single page. Requires BookStack v25.11+.",
478
+ inputSchema: {
479
+ page_id: z.coerce.number().optional().describe("Filter to comments on this page"),
480
+ offset: z.coerce.number().default(0).describe("Pagination offset"),
481
+ count: z.coerce.number().max(500).default(50).describe("Number of results to return"),
482
+ sort: z.string().optional().describe("Sort field")
483
+ }
484
+ }, async (args) => {
485
+ const comments = await client.getComments({
486
+ pageId: args.page_id,
487
+ offset: args.offset,
488
+ count: args.count,
489
+ sort: args.sort
490
+ });
491
+ return {
492
+ content: [{ type: "text", text: JSON.stringify(comments, null, 2) }]
493
+ };
494
+ });
495
+ readTool("get_comment", {
496
+ title: "Get Comment",
497
+ description: "Get a single comment by ID. Requires BookStack v25.11+.",
498
+ inputSchema: {
499
+ id: z.coerce.number().min(1).describe("Comment ID")
500
+ }
501
+ }, async (args) => {
502
+ const comment = await client.getComment(args.id);
503
+ return {
504
+ content: [{ type: "text", text: JSON.stringify(comment, null, 2) }]
505
+ };
506
+ });
507
+ readTool("get_recycle_bin", {
508
+ title: "List Recycle Bin",
509
+ description: "List items in the recycle bin (deleted books, chapters, pages, shelves). Requires admin permissions on the API token.",
510
+ inputSchema: {
511
+ offset: z.coerce.number().default(0).describe("Pagination offset"),
512
+ count: z.coerce.number().max(500).default(50).describe("Number of results to return"),
513
+ sort: z.string().optional().describe("Sort field")
514
+ }
515
+ }, async (args) => {
516
+ const items = await client.getRecycleBin({
517
+ offset: args.offset,
518
+ count: args.count,
519
+ sort: args.sort
520
+ });
521
+ return {
522
+ content: [{ type: "text", text: JSON.stringify(items, null, 2) }]
523
+ };
524
+ });
348
525
  // Register write tools if enabled
349
526
  if (config.enableWrite) {
350
- server.registerTool("create_page", {
527
+ writeTool("create_book", {
528
+ title: "Create Book",
529
+ description: "Create a new book in BookStack",
530
+ inputSchema: {
531
+ name: z.string().describe("Book name"),
532
+ description: z.string().optional().describe("Optional: Book description"),
533
+ tags: z.array(z.object({
534
+ name: z.string(),
535
+ value: z.string()
536
+ }).strict()).optional().describe("Tags for the book")
537
+ }
538
+ }, async (args) => {
539
+ const book = await client.createBook({
540
+ name: args.name,
541
+ description: args.description,
542
+ tags: args.tags
543
+ });
544
+ return {
545
+ content: [{ type: "text", text: JSON.stringify(book, null, 2) }]
546
+ };
547
+ });
548
+ writeTool("create_chapter", {
549
+ title: "Create Chapter",
550
+ description: "Create a new chapter within a book",
551
+ inputSchema: {
552
+ book_id: z.coerce.number().min(1).describe("Book ID where the chapter will be created"),
553
+ name: z.string().describe("Chapter name"),
554
+ description: z.string().optional().describe("Optional: Chapter description"),
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.createChapter({
562
+ book_id: args.book_id,
563
+ name: args.name,
564
+ description: args.description,
565
+ tags: args.tags
566
+ });
567
+ return {
568
+ content: [{ type: "text", text: JSON.stringify(chapter, null, 2) }]
569
+ };
570
+ });
571
+ writeTool("create_page", {
351
572
  title: "Create Page",
352
573
  description: "Create a new page in BookStack",
353
574
  inputSchema: {
@@ -369,26 +590,30 @@ async function main() {
369
590
  content: [{ type: "text", text: JSON.stringify(page, null, 2) }]
370
591
  };
371
592
  });
372
- server.registerTool("update_page", {
593
+ writeTool("update_page", {
373
594
  title: "Update Page",
374
- description: "Update an existing page",
595
+ description: "Update an existing page. Pass book_id (and optionally chapter_id) to move the page to a different location.",
375
596
  inputSchema: {
376
597
  id: z.coerce.number().min(1).describe("Page ID"),
377
598
  name: z.string().optional().describe("Optional: New page name"),
378
599
  html: z.string().optional().describe("Optional: New HTML content"),
379
- markdown: z.string().optional().describe("Optional: New Markdown content")
600
+ markdown: z.string().optional().describe("Optional: New Markdown content"),
601
+ book_id: z.coerce.number().min(1).optional().describe("Optional: Move page to this book"),
602
+ 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)")
380
603
  }
381
604
  }, async (args) => {
382
605
  const page = await client.updatePage(args.id, {
383
606
  name: args.name,
384
607
  html: args.html,
385
- markdown: args.markdown
608
+ markdown: args.markdown,
609
+ book_id: args.book_id,
610
+ chapter_id: args.chapter_id
386
611
  });
387
612
  return {
388
613
  content: [{ type: "text", text: JSON.stringify(page, null, 2) }]
389
614
  };
390
615
  });
391
- server.registerTool("create_shelf", {
616
+ writeTool("create_shelf", {
392
617
  title: "Create Shelf",
393
618
  description: "Create a new book shelf (collection)",
394
619
  inputSchema: {
@@ -411,7 +636,7 @@ async function main() {
411
636
  content: [{ type: "text", text: JSON.stringify(shelf, null, 2) }]
412
637
  };
413
638
  });
414
- server.registerTool("update_shelf", {
639
+ writeTool("update_shelf", {
415
640
  title: "Update Shelf",
416
641
  description: "Update an existing book shelf",
417
642
  inputSchema: {
@@ -435,7 +660,7 @@ async function main() {
435
660
  content: [{ type: "text", text: JSON.stringify(shelf, null, 2) }]
436
661
  };
437
662
  });
438
- server.registerTool("delete_shelf", {
663
+ writeTool("delete_shelf", {
439
664
  title: "Delete Shelf",
440
665
  description: "Delete a book shelf (collection)",
441
666
  inputSchema: {
@@ -447,7 +672,7 @@ async function main() {
447
672
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
448
673
  };
449
674
  });
450
- server.registerTool("create_attachment", {
675
+ writeTool("create_attachment", {
451
676
  title: "Create Attachment",
452
677
  description: "Create a new link attachment to a page",
453
678
  inputSchema: {
@@ -465,7 +690,7 @@ async function main() {
465
690
  content: [{ type: "text", text: JSON.stringify(attachment, null, 2) }]
466
691
  };
467
692
  });
468
- server.registerTool("update_attachment", {
693
+ writeTool("update_attachment", {
469
694
  title: "Update Attachment",
470
695
  description: "Update an existing attachment",
471
696
  inputSchema: {
@@ -484,7 +709,7 @@ async function main() {
484
709
  content: [{ type: "text", text: JSON.stringify(attachment, null, 2) }]
485
710
  };
486
711
  });
487
- server.registerTool("delete_attachment", {
712
+ writeTool("delete_attachment", {
488
713
  title: "Delete Attachment",
489
714
  description: "Delete an attachment",
490
715
  inputSchema: {
@@ -496,10 +721,273 @@ async function main() {
496
721
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
497
722
  };
498
723
  });
724
+ writeTool("delete_book", {
725
+ title: "Delete Book",
726
+ description: "Delete a book. Goes to the recycle bin and can be restored from there.",
727
+ inputSchema: {
728
+ id: z.coerce.number().min(1).describe("Book ID")
729
+ }
730
+ }, async (args) => {
731
+ const result = await client.deleteBook(args.id);
732
+ return {
733
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
734
+ };
735
+ });
736
+ writeTool("delete_chapter", {
737
+ title: "Delete Chapter",
738
+ description: "Delete a chapter. Goes to the recycle bin and can be restored from there.",
739
+ inputSchema: {
740
+ id: z.coerce.number().min(1).describe("Chapter ID")
741
+ }
742
+ }, async (args) => {
743
+ const result = await client.deleteChapter(args.id);
744
+ return {
745
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
746
+ };
747
+ });
748
+ writeTool("delete_page", {
749
+ title: "Delete Page",
750
+ description: "Delete a page. Goes to the recycle bin and can be restored from there.",
751
+ inputSchema: {
752
+ id: z.coerce.number().min(1).describe("Page ID")
753
+ }
754
+ }, async (args) => {
755
+ const result = await client.deletePage(args.id);
756
+ return {
757
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
758
+ };
759
+ });
760
+ writeTool("create_comment", {
761
+ title: "Create Comment",
762
+ description: "Add a comment to a page. Pass parent_id to reply to an existing comment. Requires BookStack v25.11+.",
763
+ inputSchema: {
764
+ page_id: z.coerce.number().min(1).describe("Page ID to comment on"),
765
+ html: z.string().describe("Comment HTML body"),
766
+ parent_id: z.coerce.number().optional().describe("Optional: parent comment ID for threaded replies"),
767
+ content_ref: z.string().optional().describe("Optional: anchor/selection reference within the page")
768
+ }
769
+ }, async (args) => {
770
+ const comment = await client.createComment({
771
+ page_id: args.page_id,
772
+ html: args.html,
773
+ parent_id: args.parent_id,
774
+ content_ref: args.content_ref
775
+ });
776
+ return {
777
+ content: [{ type: "text", text: JSON.stringify(comment, null, 2) }]
778
+ };
779
+ });
780
+ writeTool("update_comment", {
781
+ title: "Update Comment",
782
+ description: "Edit a comment's body or archive/unarchive it. Requires BookStack v25.11+.",
783
+ inputSchema: {
784
+ id: z.coerce.number().min(1).describe("Comment ID"),
785
+ html: z.string().optional().describe("Optional: new HTML body"),
786
+ archived: z.boolean().optional().describe("Optional: archive (true) or unarchive (false) the comment")
787
+ }
788
+ }, async (args) => {
789
+ const comment = await client.updateComment(args.id, {
790
+ html: args.html,
791
+ archived: args.archived
792
+ });
793
+ return {
794
+ content: [{ type: "text", text: JSON.stringify(comment, null, 2) }]
795
+ };
796
+ });
797
+ writeTool("delete_comment", {
798
+ title: "Delete Comment",
799
+ description: "Delete a comment. Requires BookStack v25.11+.",
800
+ inputSchema: {
801
+ id: z.coerce.number().min(1).describe("Comment ID")
802
+ }
803
+ }, async (args) => {
804
+ const result = await client.deleteComment(args.id);
805
+ return {
806
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
807
+ };
808
+ });
809
+ writeTool("restore_deleted", {
810
+ title: "Restore from Recycle Bin",
811
+ 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.",
812
+ inputSchema: {
813
+ deletion_id: z.coerce.number().min(1).describe("Deletion ID (from get_recycle_bin)")
814
+ }
815
+ }, async (args) => {
816
+ const result = await client.restoreFromRecycleBin(args.deletion_id);
817
+ return {
818
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
819
+ };
820
+ });
821
+ writeTool("permanently_delete", {
822
+ title: "Permanently Delete from Recycle Bin",
823
+ description: "PERMANENTLY destroys a deleted item — this cannot be undone. Use the deletion ID from get_recycle_bin. Requires admin permissions.",
824
+ inputSchema: {
825
+ deletion_id: z.coerce.number().min(1).describe("Deletion ID (from get_recycle_bin)")
826
+ }
827
+ }, async (args) => {
828
+ const result = await client.destroyFromRecycleBin(args.deletion_id);
829
+ return {
830
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
831
+ };
832
+ });
499
833
  }
500
- // Connect via stdio transport
834
+ }
835
+ async function startStdio(config) {
836
+ const server = buildServer(config);
501
837
  const transport = new StdioServerTransport();
502
838
  await server.connect(transport);
503
839
  console.error("BookStack MCP server running on stdio");
504
840
  }
505
- main().catch(console.error);
841
+ async function startHttp(config) {
842
+ const port = parseInt(process.env.MCP_HTTP_PORT ?? "8080", 10);
843
+ const host = process.env.MCP_HTTP_HOST ?? "127.0.0.1";
844
+ const mcpPath = process.env.MCP_HTTP_PATH ?? "/mcp";
845
+ // DNS rebinding protection: validate the Host header against an allowlist.
846
+ // Loopback binds default to localhost-only; other binds require an explicit
847
+ // MCP_HTTP_ALLOWED_HOSTS allowlist (comma-separated hostnames, no port).
848
+ const isLoopback = host === "127.0.0.1" || host === "localhost" || host === "::1";
849
+ const allowedHostsEnv = process.env.MCP_HTTP_ALLOWED_HOSTS;
850
+ const allowedHosts = allowedHostsEnv
851
+ ? allowedHostsEnv.split(",").map((h) => h.trim().toLowerCase()).filter(Boolean)
852
+ : isLoopback
853
+ ? ["localhost", "127.0.0.1", "[::1]"]
854
+ : null;
855
+ const validateHost = (req) => {
856
+ if (!allowedHosts)
857
+ return null; // user opted out by binding non-loopback without allowlist
858
+ const hostHeader = (req.headers.host ?? "").toLowerCase();
859
+ if (!hostHeader)
860
+ return "Missing Host header";
861
+ const hostname = hostHeader.startsWith("[")
862
+ ? hostHeader.slice(0, hostHeader.indexOf("]") + 1)
863
+ : hostHeader.split(":")[0];
864
+ return allowedHosts.includes(hostname) ? null : `Host '${hostname}' not allowed`;
865
+ };
866
+ const transports = {};
867
+ const readJsonBody = (req) => new Promise((resolve, reject) => {
868
+ const chunks = [];
869
+ req.on("data", (c) => chunks.push(c));
870
+ req.on("end", () => {
871
+ const raw = Buffer.concat(chunks).toString("utf8");
872
+ if (!raw)
873
+ return resolve(undefined);
874
+ try {
875
+ resolve(JSON.parse(raw));
876
+ }
877
+ catch (e) {
878
+ reject(e);
879
+ }
880
+ });
881
+ req.on("error", reject);
882
+ });
883
+ const sendJson = (res, status, body) => {
884
+ res.writeHead(status, { "Content-Type": "application/json" });
885
+ res.end(JSON.stringify(body));
886
+ };
887
+ const httpServer = createHttpServer(async (req, res) => {
888
+ try {
889
+ const hostError = validateHost(req);
890
+ if (hostError) {
891
+ sendJson(res, 421, { error: "Misdirected Request", message: hostError });
892
+ return;
893
+ }
894
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
895
+ const pathname = url.pathname;
896
+ // Streamable HTTP endpoint (recommended)
897
+ if (pathname === mcpPath) {
898
+ const sessionId = req.headers["mcp-session-id"];
899
+ let transport;
900
+ let parsedBody;
901
+ if (req.method === "POST") {
902
+ parsedBody = await readJsonBody(req);
903
+ }
904
+ if (sessionId && transports[sessionId]) {
905
+ transport = transports[sessionId];
906
+ }
907
+ else if (!sessionId && req.method === "POST" && isInitializeRequest(parsedBody)) {
908
+ transport = new StreamableHTTPServerTransport({
909
+ sessionIdGenerator: () => randomUUID(),
910
+ onsessioninitialized: (sid) => {
911
+ transports[sid] = transport;
912
+ }
913
+ });
914
+ transport.onclose = () => {
915
+ const sid = transport.sessionId;
916
+ if (sid && transports[sid])
917
+ delete transports[sid];
918
+ };
919
+ const server = buildServer(config);
920
+ await server.connect(transport);
921
+ }
922
+ else {
923
+ sendJson(res, 400, {
924
+ jsonrpc: "2.0",
925
+ error: { code: -32000, message: "Bad Request: No valid session ID provided" },
926
+ id: null
927
+ });
928
+ return;
929
+ }
930
+ await transport.handleRequest(req, res, parsedBody);
931
+ return;
932
+ }
933
+ // Health check
934
+ if (pathname === "/health" || pathname === "/") {
935
+ sendJson(res, 200, { status: "ok", server: "bookstack-mcp", transport: "http" });
936
+ return;
937
+ }
938
+ sendJson(res, 404, { error: "Not Found" });
939
+ }
940
+ catch (err) {
941
+ console.error("HTTP handler error:", err);
942
+ if (!res.headersSent) {
943
+ sendJson(res, 500, {
944
+ jsonrpc: "2.0",
945
+ error: { code: -32603, message: "Internal server error" },
946
+ id: null
947
+ });
948
+ }
949
+ }
950
+ });
951
+ httpServer.listen(port, host, () => {
952
+ console.error(`BookStack MCP server listening on http://${host}:${port}`);
953
+ console.error(` Streamable HTTP: ${mcpPath}`);
954
+ console.error(allowedHosts
955
+ ? ` Allowed Host headers: ${allowedHosts.join(", ")}`
956
+ : ` Host header validation: DISABLED (set MCP_HTTP_ALLOWED_HOSTS to enable)`);
957
+ });
958
+ const shutdown = async () => {
959
+ console.error("Shutting down HTTP server...");
960
+ for (const sid of Object.keys(transports)) {
961
+ try {
962
+ await transports[sid].close();
963
+ }
964
+ catch { }
965
+ delete transports[sid];
966
+ }
967
+ httpServer.close(() => process.exit(0));
968
+ };
969
+ process.on("SIGINT", shutdown);
970
+ process.on("SIGTERM", shutdown);
971
+ }
972
+ async function main() {
973
+ const config = {
974
+ baseUrl: getRequiredEnvVar('BOOKSTACK_BASE_URL'),
975
+ tokenId: getRequiredEnvVar('BOOKSTACK_TOKEN_ID'),
976
+ tokenSecret: getRequiredEnvVar('BOOKSTACK_TOKEN_SECRET'),
977
+ enableWrite: process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true'
978
+ };
979
+ console.error('Initializing BookStack MCP Server...');
980
+ console.error(`BookStack URL: ${config.baseUrl}`);
981
+ console.error(`Write operations: ${config.enableWrite ? 'ENABLED' : 'DISABLED'}`);
982
+ const transportMode = (process.env.MCP_TRANSPORT ?? "stdio").toLowerCase();
983
+ if (transportMode === "http" || transportMode === "sse") {
984
+ await startHttp(config);
985
+ }
986
+ else {
987
+ await startStdio(config);
988
+ }
989
+ }
990
+ main().catch((err) => {
991
+ console.error(err);
992
+ process.exit(1);
993
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bookstack-mcp",
3
- "version": "2.1.1",
3
+ "version": "3.2.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": {