bookstack-mcp 2.1.0 → 3.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/README.md +83 -4
- package/dist/bookstack-client.js +95 -19
- package/dist/index.js +375 -48
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,14 +1,30 @@
|
|
|
1
1
|
# BookStack MCP Server
|
|
2
2
|
|
|
3
|
+
[](https://www.npmjs.com/package/bookstack-mcp)
|
|
4
|
+
[](https://www.npmjs.com/package/bookstack-mcp)
|
|
5
|
+
[](https://github.com/ttpears/bookstack-mcp/actions/workflows/ci.yml)
|
|
6
|
+
[](https://nodejs.org)
|
|
7
|
+
[](https://modelcontextprotocol.io)
|
|
8
|
+
[](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 +
|
|
20
|
+
- 17 read-only tools + 10 write tools for complete BookStack API coverage
|
|
21
|
+
- Books, chapters, pages, shelves, and attachments — full CRUD where it matters
|
|
8
22
|
- Type-safe input validation with Zod (auto-coerces string/number params for broad client compatibility)
|
|
9
23
|
- Embedded URLs and content previews in all responses
|
|
24
|
+
- Markdown export fallback for HTML-authored pages, so AI clients always get usable content
|
|
10
25
|
- Write operations disabled by default for safety
|
|
11
|
-
- Works with Claude Desktop, LibreChat, and any MCP-compatible client
|
|
26
|
+
- Works with Claude Desktop, Claude Code, LibreChat, and any MCP-compatible client
|
|
27
|
+
- Stdio and Streamable HTTP transports
|
|
12
28
|
|
|
13
29
|
## Quick Start
|
|
14
30
|
|
|
@@ -58,7 +74,7 @@ Add to your Claude Desktop config:
|
|
|
58
74
|
}
|
|
59
75
|
```
|
|
60
76
|
|
|
61
|
-
### LibreChat
|
|
77
|
+
### LibreChat (stdio, single-user)
|
|
62
78
|
|
|
63
79
|
Add to your `librechat.yaml`:
|
|
64
80
|
|
|
@@ -75,8 +91,68 @@ mcpServers:
|
|
|
75
91
|
BOOKSTACK_TOKEN_SECRET: "your-token-secret"
|
|
76
92
|
```
|
|
77
93
|
|
|
94
|
+
### LibreChat (Streamable HTTP, recommended for production / Docker)
|
|
95
|
+
|
|
96
|
+
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.
|
|
97
|
+
|
|
98
|
+
Start the server in HTTP mode:
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
MCP_TRANSPORT=http \
|
|
102
|
+
MCP_HTTP_PORT=8080 \
|
|
103
|
+
BOOKSTACK_BASE_URL=https://your-bookstack.com \
|
|
104
|
+
BOOKSTACK_TOKEN_ID=your-token-id \
|
|
105
|
+
BOOKSTACK_TOKEN_SECRET=your-token-secret \
|
|
106
|
+
npx bookstack-mcp
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Then configure LibreChat:
|
|
110
|
+
|
|
111
|
+
```yaml
|
|
112
|
+
mcpServers:
|
|
113
|
+
bookstack:
|
|
114
|
+
type: streamable-http
|
|
115
|
+
url: http://bookstack-mcp:8080/mcp
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
> **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`.
|
|
119
|
+
|
|
120
|
+
#### HTTP transport environment variables
|
|
121
|
+
|
|
122
|
+
| Variable | Default | Description |
|
|
123
|
+
|----------|---------|-------------|
|
|
124
|
+
| `MCP_TRANSPORT` | `stdio` | Set to `http` to enable the HTTP server |
|
|
125
|
+
| `MCP_HTTP_PORT` | `8080` | Port to listen on |
|
|
126
|
+
| `MCP_HTTP_HOST` | `127.0.0.1` | Bind address. Loopback by default for safety |
|
|
127
|
+
| `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 |
|
|
128
|
+
| `MCP_HTTP_PATH` | `/mcp` | Streamable HTTP endpoint |
|
|
129
|
+
|
|
130
|
+
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`.
|
|
131
|
+
|
|
78
132
|
Restart LibreChat after config changes.
|
|
79
133
|
|
|
134
|
+
### Claude Code (plugin marketplace)
|
|
135
|
+
|
|
136
|
+
This repo ships a Claude Code plugin manifest (`.claude-plugin/plugin.json`). Add the marketplace and install:
|
|
137
|
+
|
|
138
|
+
```
|
|
139
|
+
/plugin marketplace add ttpears/claude-plugins
|
|
140
|
+
/plugin install bookstack-mcp@ttpears-plugins
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Then set the `BOOKSTACK_*` environment variables in your shell so the plugin's MCP server can authenticate.
|
|
144
|
+
|
|
145
|
+
## MCP Resources
|
|
146
|
+
|
|
147
|
+
Books and pages are also exposed as MCP resources, so clients that browse resources (Claude Desktop, MCP Inspector, etc.) can `@`-mention them directly:
|
|
148
|
+
|
|
149
|
+
| URI template | Description |
|
|
150
|
+
|--------------|-------------|
|
|
151
|
+
| `bookstack://book/{id}` | A book, returned as JSON metadata |
|
|
152
|
+
| `bookstack://page/{id}` | A page, returned as markdown plus a JSON metadata blob |
|
|
153
|
+
|
|
154
|
+
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.
|
|
155
|
+
|
|
80
156
|
## Available Tools
|
|
81
157
|
|
|
82
158
|
### Read Operations (always available)
|
|
@@ -100,7 +176,10 @@ Restart LibreChat after config changes.
|
|
|
100
176
|
|
|
101
177
|
| Tool | Description |
|
|
102
178
|
|------|-------------|
|
|
103
|
-
| `
|
|
179
|
+
| `create_book` | Create a new book |
|
|
180
|
+
| `create_chapter` | Create a new chapter inside a book |
|
|
181
|
+
| `create_page` | Create a new page (HTML or Markdown) |
|
|
182
|
+
| `update_page` | Update page content, rename, or move it to a different book/chapter |
|
|
104
183
|
| `create_shelf` / `update_shelf` / `delete_shelf` | Manage shelves |
|
|
105
184
|
| `create_attachment` / `update_attachment` / `delete_attachment` | Manage attachments |
|
|
106
185
|
|
package/dist/bookstack-client.js
CHANGED
|
@@ -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
|
-
...
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
254
|
+
data: await Promise.all(data.data.map((page) => this.enhancePageListItem(page)))
|
|
229
255
|
};
|
|
230
256
|
}
|
|
231
|
-
async
|
|
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
|
-
|
|
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
|
|
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.');
|
|
@@ -453,8 +531,7 @@ export class BookStackClient {
|
|
|
453
531
|
};
|
|
454
532
|
if (options?.sort)
|
|
455
533
|
params.sort = options.sort;
|
|
456
|
-
|
|
457
|
-
params.filter = JSON.stringify(options.filter);
|
|
534
|
+
this.applyFilters(params, options?.filter);
|
|
458
535
|
const response = await this.client.get('/shelves', { params });
|
|
459
536
|
const data = response.data;
|
|
460
537
|
return {
|
|
@@ -495,8 +572,7 @@ export class BookStackClient {
|
|
|
495
572
|
};
|
|
496
573
|
if (options?.sort)
|
|
497
574
|
params.sort = options.sort;
|
|
498
|
-
|
|
499
|
-
params.filter = JSON.stringify(options.filter);
|
|
575
|
+
this.applyFilters(params, options?.filter);
|
|
500
576
|
const response = await this.client.get('/attachments', { params });
|
|
501
577
|
const data = response.data;
|
|
502
578
|
return {
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,34 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
263
|
+
readTool("get_page", {
|
|
144
264
|
title: "Get Page Content",
|
|
145
|
-
description: "Get
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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: {
|
|
@@ -347,7 +474,51 @@ async function main() {
|
|
|
347
474
|
});
|
|
348
475
|
// Register write tools if enabled
|
|
349
476
|
if (config.enableWrite) {
|
|
350
|
-
|
|
477
|
+
writeTool("create_book", {
|
|
478
|
+
title: "Create Book",
|
|
479
|
+
description: "Create a new book in BookStack",
|
|
480
|
+
inputSchema: {
|
|
481
|
+
name: z.string().describe("Book name"),
|
|
482
|
+
description: z.string().optional().describe("Optional: Book description"),
|
|
483
|
+
tags: z.array(z.object({
|
|
484
|
+
name: z.string(),
|
|
485
|
+
value: z.string()
|
|
486
|
+
}).strict()).optional().describe("Tags for the book")
|
|
487
|
+
}
|
|
488
|
+
}, async (args) => {
|
|
489
|
+
const book = await client.createBook({
|
|
490
|
+
name: args.name,
|
|
491
|
+
description: args.description,
|
|
492
|
+
tags: args.tags
|
|
493
|
+
});
|
|
494
|
+
return {
|
|
495
|
+
content: [{ type: "text", text: JSON.stringify(book, null, 2) }]
|
|
496
|
+
};
|
|
497
|
+
});
|
|
498
|
+
writeTool("create_chapter", {
|
|
499
|
+
title: "Create Chapter",
|
|
500
|
+
description: "Create a new chapter within a book",
|
|
501
|
+
inputSchema: {
|
|
502
|
+
book_id: z.coerce.number().min(1).describe("Book ID where the chapter will be created"),
|
|
503
|
+
name: z.string().describe("Chapter name"),
|
|
504
|
+
description: z.string().optional().describe("Optional: Chapter description"),
|
|
505
|
+
tags: z.array(z.object({
|
|
506
|
+
name: z.string(),
|
|
507
|
+
value: z.string()
|
|
508
|
+
}).strict()).optional().describe("Tags for the chapter")
|
|
509
|
+
}
|
|
510
|
+
}, async (args) => {
|
|
511
|
+
const chapter = await client.createChapter({
|
|
512
|
+
book_id: args.book_id,
|
|
513
|
+
name: args.name,
|
|
514
|
+
description: args.description,
|
|
515
|
+
tags: args.tags
|
|
516
|
+
});
|
|
517
|
+
return {
|
|
518
|
+
content: [{ type: "text", text: JSON.stringify(chapter, null, 2) }]
|
|
519
|
+
};
|
|
520
|
+
});
|
|
521
|
+
writeTool("create_page", {
|
|
351
522
|
title: "Create Page",
|
|
352
523
|
description: "Create a new page in BookStack",
|
|
353
524
|
inputSchema: {
|
|
@@ -369,26 +540,30 @@ async function main() {
|
|
|
369
540
|
content: [{ type: "text", text: JSON.stringify(page, null, 2) }]
|
|
370
541
|
};
|
|
371
542
|
});
|
|
372
|
-
|
|
543
|
+
writeTool("update_page", {
|
|
373
544
|
title: "Update Page",
|
|
374
|
-
description: "Update an existing page",
|
|
545
|
+
description: "Update an existing page. Pass book_id (and optionally chapter_id) to move the page to a different location.",
|
|
375
546
|
inputSchema: {
|
|
376
547
|
id: z.coerce.number().min(1).describe("Page ID"),
|
|
377
548
|
name: z.string().optional().describe("Optional: New page name"),
|
|
378
549
|
html: z.string().optional().describe("Optional: New HTML content"),
|
|
379
|
-
markdown: z.string().optional().describe("Optional: New Markdown content")
|
|
550
|
+
markdown: z.string().optional().describe("Optional: New Markdown content"),
|
|
551
|
+
book_id: z.coerce.number().min(1).optional().describe("Optional: Move page to this book"),
|
|
552
|
+
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
553
|
}
|
|
381
554
|
}, async (args) => {
|
|
382
555
|
const page = await client.updatePage(args.id, {
|
|
383
556
|
name: args.name,
|
|
384
557
|
html: args.html,
|
|
385
|
-
markdown: args.markdown
|
|
558
|
+
markdown: args.markdown,
|
|
559
|
+
book_id: args.book_id,
|
|
560
|
+
chapter_id: args.chapter_id
|
|
386
561
|
});
|
|
387
562
|
return {
|
|
388
563
|
content: [{ type: "text", text: JSON.stringify(page, null, 2) }]
|
|
389
564
|
};
|
|
390
565
|
});
|
|
391
|
-
|
|
566
|
+
writeTool("create_shelf", {
|
|
392
567
|
title: "Create Shelf",
|
|
393
568
|
description: "Create a new book shelf (collection)",
|
|
394
569
|
inputSchema: {
|
|
@@ -411,7 +586,7 @@ async function main() {
|
|
|
411
586
|
content: [{ type: "text", text: JSON.stringify(shelf, null, 2) }]
|
|
412
587
|
};
|
|
413
588
|
});
|
|
414
|
-
|
|
589
|
+
writeTool("update_shelf", {
|
|
415
590
|
title: "Update Shelf",
|
|
416
591
|
description: "Update an existing book shelf",
|
|
417
592
|
inputSchema: {
|
|
@@ -435,7 +610,7 @@ async function main() {
|
|
|
435
610
|
content: [{ type: "text", text: JSON.stringify(shelf, null, 2) }]
|
|
436
611
|
};
|
|
437
612
|
});
|
|
438
|
-
|
|
613
|
+
writeTool("delete_shelf", {
|
|
439
614
|
title: "Delete Shelf",
|
|
440
615
|
description: "Delete a book shelf (collection)",
|
|
441
616
|
inputSchema: {
|
|
@@ -447,7 +622,7 @@ async function main() {
|
|
|
447
622
|
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
448
623
|
};
|
|
449
624
|
});
|
|
450
|
-
|
|
625
|
+
writeTool("create_attachment", {
|
|
451
626
|
title: "Create Attachment",
|
|
452
627
|
description: "Create a new link attachment to a page",
|
|
453
628
|
inputSchema: {
|
|
@@ -465,7 +640,7 @@ async function main() {
|
|
|
465
640
|
content: [{ type: "text", text: JSON.stringify(attachment, null, 2) }]
|
|
466
641
|
};
|
|
467
642
|
});
|
|
468
|
-
|
|
643
|
+
writeTool("update_attachment", {
|
|
469
644
|
title: "Update Attachment",
|
|
470
645
|
description: "Update an existing attachment",
|
|
471
646
|
inputSchema: {
|
|
@@ -484,7 +659,7 @@ async function main() {
|
|
|
484
659
|
content: [{ type: "text", text: JSON.stringify(attachment, null, 2) }]
|
|
485
660
|
};
|
|
486
661
|
});
|
|
487
|
-
|
|
662
|
+
writeTool("delete_attachment", {
|
|
488
663
|
title: "Delete Attachment",
|
|
489
664
|
description: "Delete an attachment",
|
|
490
665
|
inputSchema: {
|
|
@@ -497,11 +672,163 @@ async function main() {
|
|
|
497
672
|
};
|
|
498
673
|
});
|
|
499
674
|
}
|
|
500
|
-
|
|
675
|
+
}
|
|
676
|
+
async function startStdio(config) {
|
|
677
|
+
const server = buildServer(config);
|
|
501
678
|
const transport = new StdioServerTransport();
|
|
502
679
|
await server.connect(transport);
|
|
503
680
|
console.error("BookStack MCP server running on stdio");
|
|
504
681
|
}
|
|
505
|
-
|
|
506
|
-
|
|
682
|
+
async function startHttp(config) {
|
|
683
|
+
const port = parseInt(process.env.MCP_HTTP_PORT ?? "8080", 10);
|
|
684
|
+
const host = process.env.MCP_HTTP_HOST ?? "127.0.0.1";
|
|
685
|
+
const mcpPath = process.env.MCP_HTTP_PATH ?? "/mcp";
|
|
686
|
+
// DNS rebinding protection: validate the Host header against an allowlist.
|
|
687
|
+
// Loopback binds default to localhost-only; other binds require an explicit
|
|
688
|
+
// MCP_HTTP_ALLOWED_HOSTS allowlist (comma-separated hostnames, no port).
|
|
689
|
+
const isLoopback = host === "127.0.0.1" || host === "localhost" || host === "::1";
|
|
690
|
+
const allowedHostsEnv = process.env.MCP_HTTP_ALLOWED_HOSTS;
|
|
691
|
+
const allowedHosts = allowedHostsEnv
|
|
692
|
+
? allowedHostsEnv.split(",").map((h) => h.trim().toLowerCase()).filter(Boolean)
|
|
693
|
+
: isLoopback
|
|
694
|
+
? ["localhost", "127.0.0.1", "[::1]"]
|
|
695
|
+
: null;
|
|
696
|
+
const validateHost = (req) => {
|
|
697
|
+
if (!allowedHosts)
|
|
698
|
+
return null; // user opted out by binding non-loopback without allowlist
|
|
699
|
+
const hostHeader = (req.headers.host ?? "").toLowerCase();
|
|
700
|
+
if (!hostHeader)
|
|
701
|
+
return "Missing Host header";
|
|
702
|
+
const hostname = hostHeader.startsWith("[")
|
|
703
|
+
? hostHeader.slice(0, hostHeader.indexOf("]") + 1)
|
|
704
|
+
: hostHeader.split(":")[0];
|
|
705
|
+
return allowedHosts.includes(hostname) ? null : `Host '${hostname}' not allowed`;
|
|
706
|
+
};
|
|
707
|
+
const transports = {};
|
|
708
|
+
const readJsonBody = (req) => new Promise((resolve, reject) => {
|
|
709
|
+
const chunks = [];
|
|
710
|
+
req.on("data", (c) => chunks.push(c));
|
|
711
|
+
req.on("end", () => {
|
|
712
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
713
|
+
if (!raw)
|
|
714
|
+
return resolve(undefined);
|
|
715
|
+
try {
|
|
716
|
+
resolve(JSON.parse(raw));
|
|
717
|
+
}
|
|
718
|
+
catch (e) {
|
|
719
|
+
reject(e);
|
|
720
|
+
}
|
|
721
|
+
});
|
|
722
|
+
req.on("error", reject);
|
|
723
|
+
});
|
|
724
|
+
const sendJson = (res, status, body) => {
|
|
725
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
726
|
+
res.end(JSON.stringify(body));
|
|
727
|
+
};
|
|
728
|
+
const httpServer = createHttpServer(async (req, res) => {
|
|
729
|
+
try {
|
|
730
|
+
const hostError = validateHost(req);
|
|
731
|
+
if (hostError) {
|
|
732
|
+
sendJson(res, 421, { error: "Misdirected Request", message: hostError });
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
736
|
+
const pathname = url.pathname;
|
|
737
|
+
// Streamable HTTP endpoint (recommended)
|
|
738
|
+
if (pathname === mcpPath) {
|
|
739
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
740
|
+
let transport;
|
|
741
|
+
let parsedBody;
|
|
742
|
+
if (req.method === "POST") {
|
|
743
|
+
parsedBody = await readJsonBody(req);
|
|
744
|
+
}
|
|
745
|
+
if (sessionId && transports[sessionId]) {
|
|
746
|
+
transport = transports[sessionId];
|
|
747
|
+
}
|
|
748
|
+
else if (!sessionId && req.method === "POST" && isInitializeRequest(parsedBody)) {
|
|
749
|
+
transport = new StreamableHTTPServerTransport({
|
|
750
|
+
sessionIdGenerator: () => randomUUID(),
|
|
751
|
+
onsessioninitialized: (sid) => {
|
|
752
|
+
transports[sid] = transport;
|
|
753
|
+
}
|
|
754
|
+
});
|
|
755
|
+
transport.onclose = () => {
|
|
756
|
+
const sid = transport.sessionId;
|
|
757
|
+
if (sid && transports[sid])
|
|
758
|
+
delete transports[sid];
|
|
759
|
+
};
|
|
760
|
+
const server = buildServer(config);
|
|
761
|
+
await server.connect(transport);
|
|
762
|
+
}
|
|
763
|
+
else {
|
|
764
|
+
sendJson(res, 400, {
|
|
765
|
+
jsonrpc: "2.0",
|
|
766
|
+
error: { code: -32000, message: "Bad Request: No valid session ID provided" },
|
|
767
|
+
id: null
|
|
768
|
+
});
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
await transport.handleRequest(req, res, parsedBody);
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
// Health check
|
|
775
|
+
if (pathname === "/health" || pathname === "/") {
|
|
776
|
+
sendJson(res, 200, { status: "ok", server: "bookstack-mcp", transport: "http" });
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
sendJson(res, 404, { error: "Not Found" });
|
|
780
|
+
}
|
|
781
|
+
catch (err) {
|
|
782
|
+
console.error("HTTP handler error:", err);
|
|
783
|
+
if (!res.headersSent) {
|
|
784
|
+
sendJson(res, 500, {
|
|
785
|
+
jsonrpc: "2.0",
|
|
786
|
+
error: { code: -32603, message: "Internal server error" },
|
|
787
|
+
id: null
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
});
|
|
792
|
+
httpServer.listen(port, host, () => {
|
|
793
|
+
console.error(`BookStack MCP server listening on http://${host}:${port}`);
|
|
794
|
+
console.error(` Streamable HTTP: ${mcpPath}`);
|
|
795
|
+
console.error(allowedHosts
|
|
796
|
+
? ` Allowed Host headers: ${allowedHosts.join(", ")}`
|
|
797
|
+
: ` Host header validation: DISABLED (set MCP_HTTP_ALLOWED_HOSTS to enable)`);
|
|
798
|
+
});
|
|
799
|
+
const shutdown = async () => {
|
|
800
|
+
console.error("Shutting down HTTP server...");
|
|
801
|
+
for (const sid of Object.keys(transports)) {
|
|
802
|
+
try {
|
|
803
|
+
await transports[sid].close();
|
|
804
|
+
}
|
|
805
|
+
catch { }
|
|
806
|
+
delete transports[sid];
|
|
807
|
+
}
|
|
808
|
+
httpServer.close(() => process.exit(0));
|
|
809
|
+
};
|
|
810
|
+
process.on("SIGINT", shutdown);
|
|
811
|
+
process.on("SIGTERM", shutdown);
|
|
812
|
+
}
|
|
813
|
+
async function main() {
|
|
814
|
+
const config = {
|
|
815
|
+
baseUrl: getRequiredEnvVar('BOOKSTACK_BASE_URL'),
|
|
816
|
+
tokenId: getRequiredEnvVar('BOOKSTACK_TOKEN_ID'),
|
|
817
|
+
tokenSecret: getRequiredEnvVar('BOOKSTACK_TOKEN_SECRET'),
|
|
818
|
+
enableWrite: process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true'
|
|
819
|
+
};
|
|
820
|
+
console.error('Initializing BookStack MCP Server...');
|
|
821
|
+
console.error(`BookStack URL: ${config.baseUrl}`);
|
|
822
|
+
console.error(`Write operations: ${config.enableWrite ? 'ENABLED' : 'DISABLED'}`);
|
|
823
|
+
const transportMode = (process.env.MCP_TRANSPORT ?? "stdio").toLowerCase();
|
|
824
|
+
if (transportMode === "http" || transportMode === "sse") {
|
|
825
|
+
await startHttp(config);
|
|
826
|
+
}
|
|
827
|
+
else {
|
|
828
|
+
await startStdio(config);
|
|
829
|
+
}
|
|
507
830
|
}
|
|
831
|
+
main().catch((err) => {
|
|
832
|
+
console.error(err);
|
|
833
|
+
process.exit(1);
|
|
834
|
+
});
|