bookstack-mcp 5.1.0 → 5.2.3

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.
@@ -25,16 +25,36 @@ function validateUserIdFilters(query) {
25
25
  }
26
26
  }
27
27
  }
28
+ const DEFAULT_TIMEOUT_MS = 30000;
29
+ // How long a completed bulk warm stays fresh before the next lookup re-sweeps
30
+ // `/books` (books get created/renamed). Gaps within the window are handled by
31
+ // the lazy per-id fetch in getBookSlug.
32
+ const SLUG_CACHE_TTL_MS = 10 * 60 * 1000;
33
+ // Process-wide slug caches keyed by BookStack base URL. The book-id -> slug
34
+ // mapping is identical for every caller of the same BookStack instance
35
+ // regardless of which API token is used, so sharing it across the per-session
36
+ // BookStackClient instances (index.ts builds one per MCP session) turns a
37
+ // per-session bulk warm into one warm per process per TTL — far fewer /books
38
+ // calls against the single, rate-limited (180/min) shared service token.
39
+ const slugCaches = new Map();
40
+ function getSlugCacheEntry(baseUrl) {
41
+ let entry = slugCaches.get(baseUrl);
42
+ if (!entry) {
43
+ entry = { cache: new Map(), inflight: new Map() };
44
+ slugCaches.set(baseUrl, entry);
45
+ }
46
+ return entry;
47
+ }
28
48
  export class BookStackClient {
29
49
  client;
30
50
  enableWrite;
31
51
  baseUrl;
32
- bookSlugCache = new Map();
33
52
  constructor(config) {
34
53
  this.enableWrite = config.enableWrite || false;
35
54
  this.baseUrl = config.baseUrl;
36
55
  this.client = axios.create({
37
56
  baseURL: `${config.baseUrl}/api`,
57
+ timeout: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
38
58
  headers: {
39
59
  'Authorization': `Token ${config.tokenId}:${config.tokenSecret}`,
40
60
  'Content-Type': 'application/json'
@@ -67,21 +87,87 @@ export class BookStackClient {
67
87
  params[`filter[${key}]`] = value;
68
88
  }
69
89
  }
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);
90
+ /**
91
+ * Populate the process-wide book-slug cache from a single bulk `/books`
92
+ * listing. Enhancing a result set resolves a slug per item; without a warm
93
+ * cache a search whose results span (or even share) many books fires a
94
+ * concurrent `GET /books/{id}` per item — a cache stampede that BookStack
95
+ * rate-limits (429), and the retrying requests pile up in memory until the
96
+ * process OOMs. The warm is shared across all client instances for this base
97
+ * URL (see slugCaches) and re-runs at most once per SLUG_CACHE_TTL_MS, so
98
+ * many MCP sessions cost one sweep, not one each. Concurrent callers await the
99
+ * single in-flight warm. Failure is non-fatal: getBookSlug lazily fills gaps.
100
+ */
101
+ async warmBookSlugCache() {
102
+ const entry = getSlugCacheEntry(this.baseUrl);
103
+ // A completed warm is still fresh → nothing to do (lazy fetch covers gaps).
104
+ if (entry.warmedAt !== undefined && Date.now() - entry.warmedAt < SLUG_CACHE_TTL_MS) {
105
+ return;
84
106
  }
107
+ // A warm is already running → join it instead of starting another sweep.
108
+ if (entry.warm)
109
+ return entry.warm;
110
+ entry.warm = (async () => {
111
+ const pageSize = 500;
112
+ const maxPages = 20; // safety cap (10k books) — huge wikis fall back to lazy fills
113
+ try {
114
+ for (let page = 0; page < maxPages; page++) {
115
+ const response = await this.client.get('/books', {
116
+ params: { count: pageSize, offset: page * pageSize }
117
+ });
118
+ const books = response.data?.data ?? [];
119
+ for (const book of books) {
120
+ if (book?.id != null)
121
+ entry.cache.set(book.id, book.slug || String(book.id));
122
+ }
123
+ if (books.length < pageSize)
124
+ break;
125
+ }
126
+ }
127
+ catch {
128
+ // Non-fatal: leave the cache partially warm; getBookSlug lazily fills gaps.
129
+ }
130
+ finally {
131
+ // Stamp on completion (success or caught failure) so a broken BookStack
132
+ // can't trigger a warm-storm; clear the in-flight promise so the next
133
+ // lookup after the TTL can re-sweep.
134
+ entry.warmedAt = Date.now();
135
+ entry.warm = undefined;
136
+ }
137
+ })();
138
+ return entry.warm;
139
+ }
140
+ async getBookSlug(bookId) {
141
+ // A single bulk warm turns the per-result N+1 into +1; after it, every book
142
+ // that existed at warm time is a cache hit — shared across all sessions.
143
+ await this.warmBookSlugCache();
144
+ const entry = getSlugCacheEntry(this.baseUrl);
145
+ const cached = entry.cache.get(bookId);
146
+ if (cached !== undefined)
147
+ return cached;
148
+ // Gap (book created after warm, or beyond the warm cap): lazily fetch it, but
149
+ // share one in-flight request across concurrent callers so a batch of results
150
+ // referencing the same new book can't stampede.
151
+ const inflight = entry.inflight.get(bookId);
152
+ if (inflight)
153
+ return inflight;
154
+ const request = (async () => {
155
+ try {
156
+ const response = await this.client.get(`/books/${bookId}`);
157
+ const slug = response.data.slug || String(bookId);
158
+ entry.cache.set(bookId, slug);
159
+ return slug;
160
+ }
161
+ catch (error) {
162
+ // Fallback to ID if book fetch fails
163
+ return String(bookId);
164
+ }
165
+ finally {
166
+ entry.inflight.delete(bookId);
167
+ }
168
+ })();
169
+ entry.inflight.set(bookId, request);
170
+ return request;
85
171
  }
86
172
  // URL generation utilities
87
173
  generateBookUrl(book) {
@@ -212,18 +298,27 @@ export class BookStackClient {
212
298
  }
213
299
  async searchPages(query, options) {
214
300
  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
- }
301
+ const searchQuery = `{type:page} ${query}`.trim();
302
+ const bookId = options?.bookId;
303
+ const wanted = options?.count ? Math.min(options.count, 500) : undefined;
304
+ // BookStack search has NO book-scoping filter token — `{book_id:X}` is
305
+ // silently ignored (it returned the whole wiki), so scoping was a no-op that
306
+ // leaked other books' pages. Instead over-fetch and filter client-side on
307
+ // book_id. Best-effort: matches ranked beyond the 500-result ceiling can be
308
+ // missed, but every returned result genuinely belongs to the requested book.
220
309
  const params = { query: searchQuery };
221
- if (options?.count)
222
- params.count = Math.min(options.count, 500);
310
+ params.count = bookId ? 500 : wanted;
311
+ if (params.count === undefined)
312
+ delete params.count;
223
313
  if (options?.offset)
224
314
  params.offset = options.offset;
225
315
  const response = await this.client.get('/search', { params });
226
- const results = response.data.data || response.data;
316
+ let results = response.data.data || response.data;
317
+ if (bookId) {
318
+ results = results.filter((r) => r.book_id === bookId);
319
+ if (wanted)
320
+ results = results.slice(0, wanted);
321
+ }
227
322
  return await this.enhanceSearchResults(results, query);
228
323
  }
229
324
  async getBooks(options) {
@@ -463,20 +558,25 @@ export class BookStackClient {
463
558
  const dateThreshold = new Date();
464
559
  dateThreshold.setDate(dateThreshold.getDate() - days);
465
560
  const dateFilter = dateThreshold.toISOString().split('T')[0]; // YYYY-MM-DD format
466
- // Build search query for recent changes
467
- let searchQuery = `{updated_at:>=${dateFilter}}`;
561
+ // Build search query for recent changes. BookStack's search syntax uses
562
+ // `{updated_after:YYYY-MM-DD}` — NOT `{updated_at:>=...}` (that token does
563
+ // not exist, and BookStack silently ignores unknown `{...}` filters and
564
+ // returns the entire wiki). `/search` also does not honor a `sort` query
565
+ // param (sorting is `{sort_by:...}` in the query), so we sort client-side.
566
+ let searchQuery = `{updated_after:${dateFilter}}`;
468
567
  if (type !== 'all') {
469
568
  searchQuery = `{type:${type}} ${searchQuery}`;
470
569
  }
471
570
  const params = {
472
571
  query: searchQuery,
473
- count: limit,
474
- sort: 'updated_at' // Sort by most recently updated
572
+ count: limit
475
573
  };
476
574
  const response = await this.client.get('/search', { params });
477
575
  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.
576
+ // Use the search response data as-is — callers fetch full details via
577
+ // get_page/get_book/get_chapter if needed. URL enhancement resolves a book
578
+ // slug per item, but getBookSlug bulk-warms its cache once, so this is +1
579
+ // request, not the per-item N+1 it would otherwise be.
480
580
  const enhancedResults = await Promise.all(results.map(async (result) => {
481
581
  const url = await this.generateContentUrl(result);
482
582
  const preview = result.preview_content?.content;
@@ -486,10 +586,14 @@ export class BookStackClient {
486
586
  }
487
587
  return out;
488
588
  }));
589
+ // `/search` orders by relevance, not recency, so sort newest-first here.
590
+ enhancedResults.sort((a, b) => String(b.updated_at ?? '').localeCompare(String(a.updated_at ?? '')));
489
591
  return {
490
592
  date_threshold: dateFilter,
491
593
  type,
492
- total: results.length,
594
+ // The true match count for the window (results is only the current page).
595
+ total: response.data.total ?? results.length,
596
+ returned: enhancedResults.length,
493
597
  results: enhancedResults
494
598
  };
495
599
  }
package/dist/index.js CHANGED
@@ -944,6 +944,9 @@ 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;
947
950
  const oauth = loadOAuthConfig(process.env);
948
951
  // Initialize the OAuth broker-state store (Redis when REDIS_URL is set) before
949
952
  // the server handles any request, so DCR clients / pending flows / codes persist.
@@ -958,14 +961,15 @@ async function main() {
958
961
  tokenId: getRequiredEnvVar('BOOKSTACK_TOKEN_ID'),
959
962
  tokenSecret: getRequiredEnvVar('BOOKSTACK_TOKEN_SECRET'),
960
963
  enableWrite: oauth ? false : envEnableWrite,
961
- insecureSkipTlsVerify
964
+ insecureSkipTlsVerify,
965
+ timeoutMs
962
966
  };
963
967
  // The write credential is optional and only used by the OAuth proxy for sessions whose
964
968
  // token carries the configured app role.
965
969
  const writeTokenId = process.env.BOOKSTACK_WRITE_TOKEN_ID;
966
970
  const writeTokenSecret = process.env.BOOKSTACK_WRITE_TOKEN_SECRET;
967
971
  const write = (writeTokenId && writeTokenSecret)
968
- ? { baseUrl, tokenId: writeTokenId, tokenSecret: writeTokenSecret, enableWrite: true, insecureSkipTlsVerify }
972
+ ? { baseUrl, tokenId: writeTokenId, tokenSecret: writeTokenSecret, enableWrite: true, insecureSkipTlsVerify, timeoutMs }
969
973
  : null;
970
974
  const config = { read, write, oauth };
971
975
  console.error('Initializing BookStack MCP Server...');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bookstack-mcp",
3
- "version": "5.1.0",
3
+ "version": "5.2.3",
4
4
  "description": "MCP server for BookStack wiki — search, read, create, and manage documentation via AI assistants",
5
5
  "type": "module",
6
6
  "bin": {