bookstack-mcp 5.1.0 → 5.3.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.
@@ -1,5 +1,6 @@
1
1
  import axios from 'axios';
2
2
  import https from 'https';
3
+ import { Semaphore } from './util/semaphore.js';
3
4
  const MAX_RETRIES_429 = 5;
4
5
  function parseRetryAfter(value) {
5
6
  if (typeof value !== 'string' || !value)
@@ -25,23 +26,63 @@ function validateUserIdFilters(query) {
25
26
  }
26
27
  }
27
28
  }
29
+ const DEFAULT_TIMEOUT_MS = 30000;
30
+ // How long a completed bulk warm stays fresh before the next lookup re-sweeps
31
+ // `/books` (books get created/renamed). Gaps within the window are handled by
32
+ // the lazy per-id fetch in getBookSlug.
33
+ const SLUG_CACHE_TTL_MS = 10 * 60 * 1000;
34
+ // Process-wide slug caches keyed by BookStack base URL. The book-id -> slug
35
+ // mapping is identical for every caller of the same BookStack instance
36
+ // regardless of which API token is used, so sharing it across the per-session
37
+ // BookStackClient instances (index.ts builds one per MCP session) turns a
38
+ // per-session bulk warm into one warm per process per TTL — far fewer /books
39
+ // calls against the single, rate-limited (180/min) shared service token.
40
+ const slugCaches = new Map();
41
+ function getSlugCacheEntry(baseUrl) {
42
+ let entry = slugCaches.get(baseUrl);
43
+ if (!entry) {
44
+ entry = { cache: new Map(), inflight: new Map() };
45
+ slugCaches.set(baseUrl, entry);
46
+ }
47
+ return entry;
48
+ }
49
+ const DEFAULT_MAX_CONCURRENCY = 4;
50
+ // Process-wide concurrency limiters, one per BookStack base URL — shared across
51
+ // all sessions/clients so they cannot collectively exceed the per-token rate
52
+ // limit. Mirrors the slugCaches sharing model.
53
+ const concurrencyLimiters = new Map();
54
+ function getConcurrencyLimiter(baseUrl, max) {
55
+ let limiter = concurrencyLimiters.get(baseUrl);
56
+ if (!limiter) {
57
+ limiter = new Semaphore(max);
58
+ concurrencyLimiters.set(baseUrl, limiter);
59
+ }
60
+ return limiter;
61
+ }
28
62
  export class BookStackClient {
29
63
  client;
30
64
  enableWrite;
31
65
  baseUrl;
32
- bookSlugCache = new Map();
33
66
  constructor(config) {
34
67
  this.enableWrite = config.enableWrite || false;
35
68
  this.baseUrl = config.baseUrl;
69
+ const limiter = getConcurrencyLimiter(config.baseUrl, config.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY);
70
+ const baseAdapter = axios.getAdapter(axios.defaults.adapter);
36
71
  this.client = axios.create({
37
72
  baseURL: `${config.baseUrl}/api`,
73
+ timeout: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
38
74
  headers: {
39
75
  'Authorization': `Token ${config.tokenId}:${config.tokenSecret}`,
40
76
  'Content-Type': 'application/json'
41
77
  },
42
78
  httpsAgent: config.insecureSkipTlsVerify
43
79
  ? new https.Agent({ rejectUnauthorized: false })
44
- : undefined
80
+ : undefined,
81
+ // Every request — including the 429-retry re-issue below — flows through
82
+ // this adapter exactly once per HTTP attempt. The retry's backoff sleep
83
+ // happens in the response interceptor (outside the adapter), so the
84
+ // permit is released between attempts, not held during the wait.
85
+ adapter: (requestConfig) => limiter.run(() => baseAdapter(requestConfig)),
45
86
  });
46
87
  this.client.interceptors.response.use(undefined, async (error) => {
47
88
  const cfg = error.config;
@@ -67,21 +108,87 @@ export class BookStackClient {
67
108
  params[`filter[${key}]`] = value;
68
109
  }
69
110
  }
70
- async getBookSlug(bookId) {
71
- // Check cache first
72
- if (this.bookSlugCache.has(bookId)) {
73
- return this.bookSlugCache.get(bookId);
74
- }
75
- try {
76
- const response = await this.client.get(`/books/${bookId}`);
77
- const slug = response.data.slug || String(bookId);
78
- this.bookSlugCache.set(bookId, slug);
79
- return slug;
80
- }
81
- catch (error) {
82
- // Fallback to ID if book fetch fails
83
- return String(bookId);
111
+ /**
112
+ * Populate the process-wide book-slug cache from a single bulk `/books`
113
+ * listing. Enhancing a result set resolves a slug per item; without a warm
114
+ * cache a search whose results span (or even share) many books fires a
115
+ * concurrent `GET /books/{id}` per item — a cache stampede that BookStack
116
+ * rate-limits (429), and the retrying requests pile up in memory until the
117
+ * process OOMs. The warm is shared across all client instances for this base
118
+ * URL (see slugCaches) and re-runs at most once per SLUG_CACHE_TTL_MS, so
119
+ * many MCP sessions cost one sweep, not one each. Concurrent callers await the
120
+ * single in-flight warm. Failure is non-fatal: getBookSlug lazily fills gaps.
121
+ */
122
+ async warmBookSlugCache() {
123
+ const entry = getSlugCacheEntry(this.baseUrl);
124
+ // A completed warm is still fresh → nothing to do (lazy fetch covers gaps).
125
+ if (entry.warmedAt !== undefined && Date.now() - entry.warmedAt < SLUG_CACHE_TTL_MS) {
126
+ return;
84
127
  }
128
+ // A warm is already running → join it instead of starting another sweep.
129
+ if (entry.warm)
130
+ return entry.warm;
131
+ entry.warm = (async () => {
132
+ const pageSize = 500;
133
+ const maxPages = 20; // safety cap (10k books) — huge wikis fall back to lazy fills
134
+ try {
135
+ for (let page = 0; page < maxPages; page++) {
136
+ const response = await this.client.get('/books', {
137
+ params: { count: pageSize, offset: page * pageSize }
138
+ });
139
+ const books = response.data?.data ?? [];
140
+ for (const book of books) {
141
+ if (book?.id != null)
142
+ entry.cache.set(book.id, book.slug || String(book.id));
143
+ }
144
+ if (books.length < pageSize)
145
+ break;
146
+ }
147
+ }
148
+ catch {
149
+ // Non-fatal: leave the cache partially warm; getBookSlug lazily fills gaps.
150
+ }
151
+ finally {
152
+ // Stamp on completion (success or caught failure) so a broken BookStack
153
+ // can't trigger a warm-storm; clear the in-flight promise so the next
154
+ // lookup after the TTL can re-sweep.
155
+ entry.warmedAt = Date.now();
156
+ entry.warm = undefined;
157
+ }
158
+ })();
159
+ return entry.warm;
160
+ }
161
+ async getBookSlug(bookId) {
162
+ // A single bulk warm turns the per-result N+1 into +1; after it, every book
163
+ // that existed at warm time is a cache hit — shared across all sessions.
164
+ await this.warmBookSlugCache();
165
+ const entry = getSlugCacheEntry(this.baseUrl);
166
+ const cached = entry.cache.get(bookId);
167
+ if (cached !== undefined)
168
+ return cached;
169
+ // Gap (book created after warm, or beyond the warm cap): lazily fetch it, but
170
+ // share one in-flight request across concurrent callers so a batch of results
171
+ // referencing the same new book can't stampede.
172
+ const inflight = entry.inflight.get(bookId);
173
+ if (inflight)
174
+ return inflight;
175
+ const request = (async () => {
176
+ try {
177
+ const response = await this.client.get(`/books/${bookId}`);
178
+ const slug = response.data.slug || String(bookId);
179
+ entry.cache.set(bookId, slug);
180
+ return slug;
181
+ }
182
+ catch (error) {
183
+ // Fallback to ID if book fetch fails
184
+ return String(bookId);
185
+ }
186
+ finally {
187
+ entry.inflight.delete(bookId);
188
+ }
189
+ })();
190
+ entry.inflight.set(bookId, request);
191
+ return request;
85
192
  }
86
193
  // URL generation utilities
87
194
  generateBookUrl(book) {
@@ -212,18 +319,27 @@ export class BookStackClient {
212
319
  }
213
320
  async searchPages(query, options) {
214
321
  validateUserIdFilters(query);
215
- let searchQuery = `{type:page} ${query}`.trim();
216
- // Add book filtering if specified
217
- if (options?.bookId) {
218
- searchQuery = `{book_id:${options.bookId}} ${searchQuery}`;
219
- }
322
+ const searchQuery = `{type:page} ${query}`.trim();
323
+ const bookId = options?.bookId;
324
+ const wanted = options?.count ? Math.min(options.count, 500) : undefined;
325
+ // BookStack search has NO book-scoping filter token — `{book_id:X}` is
326
+ // silently ignored (it returned the whole wiki), so scoping was a no-op that
327
+ // leaked other books' pages. Instead over-fetch and filter client-side on
328
+ // book_id. Best-effort: matches ranked beyond the 500-result ceiling can be
329
+ // missed, but every returned result genuinely belongs to the requested book.
220
330
  const params = { query: searchQuery };
221
- if (options?.count)
222
- params.count = Math.min(options.count, 500);
331
+ params.count = bookId ? 500 : wanted;
332
+ if (params.count === undefined)
333
+ delete params.count;
223
334
  if (options?.offset)
224
335
  params.offset = options.offset;
225
336
  const response = await this.client.get('/search', { params });
226
- const results = response.data.data || response.data;
337
+ let results = response.data.data || response.data;
338
+ if (bookId) {
339
+ results = results.filter((r) => r.book_id === bookId);
340
+ if (wanted)
341
+ results = results.slice(0, wanted);
342
+ }
227
343
  return await this.enhanceSearchResults(results, query);
228
344
  }
229
345
  async getBooks(options) {
@@ -463,20 +579,25 @@ export class BookStackClient {
463
579
  const dateThreshold = new Date();
464
580
  dateThreshold.setDate(dateThreshold.getDate() - days);
465
581
  const dateFilter = dateThreshold.toISOString().split('T')[0]; // YYYY-MM-DD format
466
- // Build search query for recent changes
467
- let searchQuery = `{updated_at:>=${dateFilter}}`;
582
+ // Build search query for recent changes. BookStack's search syntax uses
583
+ // `{updated_after:YYYY-MM-DD}` — NOT `{updated_at:>=...}` (that token does
584
+ // not exist, and BookStack silently ignores unknown `{...}` filters and
585
+ // returns the entire wiki). `/search` also does not honor a `sort` query
586
+ // param (sorting is `{sort_by:...}` in the query), so we sort client-side.
587
+ let searchQuery = `{updated_after:${dateFilter}}`;
468
588
  if (type !== 'all') {
469
589
  searchQuery = `{type:${type}} ${searchQuery}`;
470
590
  }
471
591
  const params = {
472
592
  query: searchQuery,
473
- count: limit,
474
- sort: 'updated_at' // Sort by most recently updated
593
+ count: limit
475
594
  };
476
595
  const response = await this.client.get('/search', { params });
477
596
  const results = response.data.data || response.data;
478
- // Use the search response data as-is — no per-item BookStack fetch (was N+1).
479
- // Callers can fetch full details via get_page/get_book/get_chapter if needed.
597
+ // Use the search response data as-is — callers fetch full details via
598
+ // get_page/get_book/get_chapter if needed. URL enhancement resolves a book
599
+ // slug per item, but getBookSlug bulk-warms its cache once, so this is +1
600
+ // request, not the per-item N+1 it would otherwise be.
480
601
  const enhancedResults = await Promise.all(results.map(async (result) => {
481
602
  const url = await this.generateContentUrl(result);
482
603
  const preview = result.preview_content?.content;
@@ -486,10 +607,14 @@ export class BookStackClient {
486
607
  }
487
608
  return out;
488
609
  }));
610
+ // `/search` orders by relevance, not recency, so sort newest-first here.
611
+ enhancedResults.sort((a, b) => String(b.updated_at ?? '').localeCompare(String(a.updated_at ?? '')));
489
612
  return {
490
613
  date_threshold: dateFilter,
491
614
  type,
492
- total: results.length,
615
+ // The true match count for the window (results is only the current page).
616
+ total: response.data.total ?? results.length,
617
+ returned: enhancedResults.length,
493
618
  results: enhancedResults
494
619
  };
495
620
  }
package/dist/index.js CHANGED
@@ -944,6 +944,14 @@ async function main() {
944
944
  const baseUrl = getRequiredEnvVar('BOOKSTACK_BASE_URL');
945
945
  const insecureSkipTlsVerify = process.env.BOOKSTACK_INSECURE_SKIP_TLS_VERIFY?.toLowerCase() === 'true';
946
946
  const envEnableWrite = process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true';
947
+ const timeoutRaw = process.env.BOOKSTACK_TIMEOUT_MS;
948
+ const timeoutParsed = timeoutRaw ? parseInt(timeoutRaw, 10) : NaN;
949
+ const timeoutMs = Number.isFinite(timeoutParsed) && timeoutParsed > 0 ? timeoutParsed : undefined;
950
+ const concurrencyRaw = process.env.BOOKSTACK_MAX_CONCURRENCY;
951
+ const concurrencyParsed = concurrencyRaw ? parseInt(concurrencyRaw, 10) : NaN;
952
+ const maxConcurrency = Number.isFinite(concurrencyParsed) && concurrencyParsed > 0
953
+ ? concurrencyParsed
954
+ : undefined;
947
955
  const oauth = loadOAuthConfig(process.env);
948
956
  // Initialize the OAuth broker-state store (Redis when REDIS_URL is set) before
949
957
  // the server handles any request, so DCR clients / pending flows / codes persist.
@@ -958,14 +966,16 @@ async function main() {
958
966
  tokenId: getRequiredEnvVar('BOOKSTACK_TOKEN_ID'),
959
967
  tokenSecret: getRequiredEnvVar('BOOKSTACK_TOKEN_SECRET'),
960
968
  enableWrite: oauth ? false : envEnableWrite,
961
- insecureSkipTlsVerify
969
+ insecureSkipTlsVerify,
970
+ timeoutMs,
971
+ maxConcurrency
962
972
  };
963
973
  // The write credential is optional and only used by the OAuth proxy for sessions whose
964
974
  // token carries the configured app role.
965
975
  const writeTokenId = process.env.BOOKSTACK_WRITE_TOKEN_ID;
966
976
  const writeTokenSecret = process.env.BOOKSTACK_WRITE_TOKEN_SECRET;
967
977
  const write = (writeTokenId && writeTokenSecret)
968
- ? { baseUrl, tokenId: writeTokenId, tokenSecret: writeTokenSecret, enableWrite: true, insecureSkipTlsVerify }
978
+ ? { baseUrl, tokenId: writeTokenId, tokenSecret: writeTokenSecret, enableWrite: true, insecureSkipTlsVerify, timeoutMs, maxConcurrency }
969
979
  : null;
970
980
  const config = { read, write, oauth };
971
981
  console.error('Initializing BookStack MCP Server...');
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bookstack-mcp",
3
- "version": "5.1.0",
3
+ "version": "5.3.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
  },