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