bookstack-mcp 4.0.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.
- package/README.md +11 -0
- package/dist/bookstack-client.js +134 -30
- package/dist/index.js +79 -9
- package/dist/oauth/entra-proxy.js +379 -0
- package/dist/oauth/kv-store.js +79 -0
- package/dist/prompts.js +51 -0
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -144,6 +144,17 @@ When binding to `0.0.0.0` (e.g. inside a container reachable from other services
|
|
|
144
144
|
|
|
145
145
|
Restart LibreChat after config changes.
|
|
146
146
|
|
|
147
|
+
### Remote hosting & Claude Connector (Docker + Entra OAuth)
|
|
148
|
+
|
|
149
|
+
A container image is published to `ghcr.io/ttpears/bookstack-mcp` (released `:X.Y.Z`/`:latest`,
|
|
150
|
+
plus per-PR preview tags `:branch-<slug>`). The server can run as a public **Claude Connector**
|
|
151
|
+
gated by Microsoft 365 / Entra ID login — users sign in, no API key or client credential to
|
|
152
|
+
paste; write tools are unlocked per session by an Entra app role.
|
|
153
|
+
|
|
154
|
+
See **[docs/SETUP.md](docs/SETUP.md)** for the full runbook: Entra app registration steps,
|
|
155
|
+
the environment-variable reference, internal LibreChat deployment, and the public OAuth
|
|
156
|
+
connector setup.
|
|
157
|
+
|
|
147
158
|
### Claude Code (CLI)
|
|
148
159
|
|
|
149
160
|
The recommended path is the `ttpears/claude-plugins` marketplace, which ships this repo's plugin manifest (`.claude-plugin/plugin.json`):
|
package/dist/bookstack-client.js
CHANGED
|
@@ -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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
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
|
-
|
|
222
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 —
|
|
479
|
-
//
|
|
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
|
-
|
|
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
|
@@ -10,6 +10,8 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
|
|
|
10
10
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
11
11
|
import { z } from "zod";
|
|
12
12
|
import { BookStackClient } from "./bookstack-client.js";
|
|
13
|
+
import { registerPrompts } from "./prompts.js";
|
|
14
|
+
import { loadOAuthConfig, initOAuthStore, handleOAuthRoutes, validateBearer, sendUnauthorized } from "./oauth/entra-proxy.js";
|
|
13
15
|
const PKG_VERSION = (() => {
|
|
14
16
|
try {
|
|
15
17
|
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
@@ -45,6 +47,7 @@ function buildServer(config) {
|
|
|
45
47
|
});
|
|
46
48
|
registerTools(server, client, config);
|
|
47
49
|
registerResources(server, client);
|
|
50
|
+
registerPrompts(server);
|
|
48
51
|
return server;
|
|
49
52
|
}
|
|
50
53
|
function registerResources(server, client) {
|
|
@@ -768,7 +771,7 @@ function registerTools(server, client, config) {
|
|
|
768
771
|
}
|
|
769
772
|
}
|
|
770
773
|
async function startStdio(config) {
|
|
771
|
-
const server = buildServer(config);
|
|
774
|
+
const server = buildServer(config.read);
|
|
772
775
|
const transport = new StdioServerTransport();
|
|
773
776
|
await server.connect(transport);
|
|
774
777
|
console.error("BookStack MCP server running on stdio");
|
|
@@ -799,6 +802,8 @@ async function startHttp(config) {
|
|
|
799
802
|
return allowedHosts.includes(hostname) ? null : `Host '${hostname}' not allowed`;
|
|
800
803
|
};
|
|
801
804
|
const transports = {};
|
|
805
|
+
// Per-session auth binding (OAuth mode only): subject + resolved write status, fixed at init.
|
|
806
|
+
const sessionAuth = {};
|
|
802
807
|
const readJsonBody = (req) => new Promise((resolve, reject) => {
|
|
803
808
|
const chunks = [];
|
|
804
809
|
req.on("data", (c) => chunks.push(c));
|
|
@@ -826,10 +831,24 @@ async function startHttp(config) {
|
|
|
826
831
|
sendJson(res, 421, { error: "Misdirected Request", message: hostError });
|
|
827
832
|
return;
|
|
828
833
|
}
|
|
834
|
+
// OAuth proxy surface (discovery metadata, DCR, authorize/callback/token).
|
|
835
|
+
if (config.oauth && (await handleOAuthRoutes(req, res, config.oauth))) {
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
829
838
|
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
830
839
|
const pathname = url.pathname;
|
|
831
840
|
// Streamable HTTP endpoint (recommended)
|
|
832
841
|
if (pathname === mcpPath) {
|
|
842
|
+
// Enforce the bearer and resolve the caller's authorization when OAuth is enabled.
|
|
843
|
+
let auth = null;
|
|
844
|
+
if (config.oauth) {
|
|
845
|
+
const result = await validateBearer(req, config.oauth);
|
|
846
|
+
if (!result.ok) {
|
|
847
|
+
sendUnauthorized(res, config.oauth);
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
auth = { sub: result.sub, isWriter: !!result.isWriter };
|
|
851
|
+
}
|
|
833
852
|
const sessionId = req.headers["mcp-session-id"];
|
|
834
853
|
let transport;
|
|
835
854
|
let parsedBody;
|
|
@@ -837,21 +856,38 @@ async function startHttp(config) {
|
|
|
837
856
|
parsedBody = await readJsonBody(req);
|
|
838
857
|
}
|
|
839
858
|
if (sessionId && transports[sessionId]) {
|
|
859
|
+
// Reject a valid token belonging to a different subject than the session was bound to.
|
|
860
|
+
if (config.oauth && sessionAuth[sessionId] && auth?.sub !== sessionAuth[sessionId].sub) {
|
|
861
|
+
sendJson(res, 403, {
|
|
862
|
+
jsonrpc: "2.0",
|
|
863
|
+
error: { code: -32003, message: "Forbidden: token does not match session" },
|
|
864
|
+
id: null
|
|
865
|
+
});
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
840
868
|
transport = transports[sessionId];
|
|
841
869
|
}
|
|
842
870
|
else if (!sessionId && req.method === "POST" && isInitializeRequest(parsedBody)) {
|
|
871
|
+
// Choose the per-session credential: writers (with a write token configured) get the
|
|
872
|
+
// write token and write tools; everyone else gets the read-only token.
|
|
873
|
+
const useWrite = !!(auth?.isWriter && config.write);
|
|
874
|
+
const sessionConfig = useWrite ? config.write : config.read;
|
|
843
875
|
transport = new StreamableHTTPServerTransport({
|
|
844
876
|
sessionIdGenerator: () => randomUUID(),
|
|
845
877
|
onsessioninitialized: (sid) => {
|
|
846
878
|
transports[sid] = transport;
|
|
879
|
+
if (config.oauth && auth)
|
|
880
|
+
sessionAuth[sid] = auth;
|
|
847
881
|
}
|
|
848
882
|
});
|
|
849
883
|
transport.onclose = () => {
|
|
850
884
|
const sid = transport.sessionId;
|
|
851
885
|
if (sid && transports[sid])
|
|
852
886
|
delete transports[sid];
|
|
887
|
+
if (sid && sessionAuth[sid])
|
|
888
|
+
delete sessionAuth[sid];
|
|
853
889
|
};
|
|
854
|
-
const server = buildServer(
|
|
890
|
+
const server = buildServer(sessionConfig);
|
|
855
891
|
await server.connect(transport);
|
|
856
892
|
}
|
|
857
893
|
else {
|
|
@@ -905,17 +941,51 @@ async function startHttp(config) {
|
|
|
905
941
|
process.on("SIGTERM", shutdown);
|
|
906
942
|
}
|
|
907
943
|
async function main() {
|
|
908
|
-
const
|
|
909
|
-
|
|
944
|
+
const baseUrl = getRequiredEnvVar('BOOKSTACK_BASE_URL');
|
|
945
|
+
const insecureSkipTlsVerify = process.env.BOOKSTACK_INSECURE_SKIP_TLS_VERIFY?.toLowerCase() === 'true';
|
|
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 oauth = loadOAuthConfig(process.env);
|
|
951
|
+
// Initialize the OAuth broker-state store (Redis when REDIS_URL is set) before
|
|
952
|
+
// the server handles any request, so DCR clients / pending flows / codes persist.
|
|
953
|
+
if (oauth) {
|
|
954
|
+
await initOAuthStore(process.env, oauth.serverUrl);
|
|
955
|
+
}
|
|
956
|
+
// The read-only credential is required. In OAuth mode it always runs read-only (write is
|
|
957
|
+
// reserved for role-bearing sessions on the separate write token); otherwise the legacy
|
|
958
|
+
// BOOKSTACK_ENABLE_WRITE flag governs it.
|
|
959
|
+
const read = {
|
|
960
|
+
baseUrl,
|
|
910
961
|
tokenId: getRequiredEnvVar('BOOKSTACK_TOKEN_ID'),
|
|
911
962
|
tokenSecret: getRequiredEnvVar('BOOKSTACK_TOKEN_SECRET'),
|
|
912
|
-
enableWrite:
|
|
913
|
-
insecureSkipTlsVerify
|
|
963
|
+
enableWrite: oauth ? false : envEnableWrite,
|
|
964
|
+
insecureSkipTlsVerify,
|
|
965
|
+
timeoutMs
|
|
914
966
|
};
|
|
967
|
+
// The write credential is optional and only used by the OAuth proxy for sessions whose
|
|
968
|
+
// token carries the configured app role.
|
|
969
|
+
const writeTokenId = process.env.BOOKSTACK_WRITE_TOKEN_ID;
|
|
970
|
+
const writeTokenSecret = process.env.BOOKSTACK_WRITE_TOKEN_SECRET;
|
|
971
|
+
const write = (writeTokenId && writeTokenSecret)
|
|
972
|
+
? { baseUrl, tokenId: writeTokenId, tokenSecret: writeTokenSecret, enableWrite: true, insecureSkipTlsVerify, timeoutMs }
|
|
973
|
+
: null;
|
|
974
|
+
const config = { read, write, oauth };
|
|
915
975
|
console.error('Initializing BookStack MCP Server...');
|
|
916
|
-
console.error(`BookStack URL: ${
|
|
917
|
-
|
|
918
|
-
|
|
976
|
+
console.error(`BookStack URL: ${baseUrl}`);
|
|
977
|
+
if (oauth) {
|
|
978
|
+
console.error(`Auth: Entra OAuth proxy ENABLED (tenant ${oauth.tenantId})`);
|
|
979
|
+
console.error(` Public URL: ${oauth.serverUrl}`);
|
|
980
|
+
console.error(` Write role: ${oauth.writeRole}`);
|
|
981
|
+
if (!write) {
|
|
982
|
+
console.error(' WARNING: no BOOKSTACK_WRITE_TOKEN_ID/SECRET set — all sessions are read-only regardless of role.');
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
else {
|
|
986
|
+
console.error(`Auth: none (token-only mode); Write operations: ${read.enableWrite ? 'ENABLED' : 'DISABLED'}`);
|
|
987
|
+
}
|
|
988
|
+
if (insecureSkipTlsVerify) {
|
|
919
989
|
console.error('WARNING: TLS certificate verification is DISABLED (BOOKSTACK_INSECURE_SKIP_TLS_VERIFY=true). Connections to BookStack are vulnerable to MITM attacks. Use only with trusted self-signed certs on a trusted network.');
|
|
920
990
|
}
|
|
921
991
|
const transportMode = (process.env.MCP_TRANSPORT ?? "stdio").toLowerCase();
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
// Entra (Microsoft 365) OAuth proxy for remote MCP / Claude Connectors.
|
|
2
|
+
//
|
|
3
|
+
// Modeled on zereight/gitlab-mcp's GITLAB_MCP_OAUTH mode: the MCP server hosts the
|
|
4
|
+
// OAuth surface Claude expects (discovery metadata + Dynamic Client Registration +
|
|
5
|
+
// authorize/token) and brokers the real login upstream to Entra ID. Claude self-registers
|
|
6
|
+
// (DCR is handled locally — Entra never sees it), logs the user in against the tenant, and
|
|
7
|
+
// receives the Entra access token, which the MCP server validates statelessly per request.
|
|
8
|
+
//
|
|
9
|
+
// This module is deliberately BookStack-agnostic so it can be reused across the MCP fleet.
|
|
10
|
+
// The only app-specific glue (mapping the `roles` claim to which credential/tool set to use)
|
|
11
|
+
// lives in the caller.
|
|
12
|
+
import { randomUUID, createHash, randomBytes } from "node:crypto";
|
|
13
|
+
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
14
|
+
import { InMemoryKvStore, createStore } from "./kv-store.js";
|
|
15
|
+
// Load config from env. Returns null when OAuth proxy mode is disabled.
|
|
16
|
+
export function loadOAuthConfig(env) {
|
|
17
|
+
if (env.MCP_OAUTH_ENABLE?.toLowerCase() !== "true")
|
|
18
|
+
return null;
|
|
19
|
+
const missing = [];
|
|
20
|
+
const req = (name) => {
|
|
21
|
+
const v = env[name];
|
|
22
|
+
if (!v)
|
|
23
|
+
missing.push(name);
|
|
24
|
+
return v ?? "";
|
|
25
|
+
};
|
|
26
|
+
const serverUrl = req("MCP_SERVER_URL").replace(/\/+$/, "");
|
|
27
|
+
const tenantId = req("OAUTH_TENANT_ID");
|
|
28
|
+
const clientId = req("OAUTH_CLIENT_ID");
|
|
29
|
+
const clientSecret = req("OAUTH_CLIENT_SECRET");
|
|
30
|
+
if (missing.length) {
|
|
31
|
+
console.error(`Error: MCP_OAUTH_ENABLE=true but missing required vars: ${missing.join(", ")}`);
|
|
32
|
+
process.exit(1);
|
|
33
|
+
}
|
|
34
|
+
const audience = env.OAUTH_AUDIENCE || `api://${clientId}`;
|
|
35
|
+
const scopes = env.OAUTH_SCOPES || `openid profile offline_access ${audience}/.default`;
|
|
36
|
+
const writeRole = env.OAUTH_WRITE_ROLE || "Writer";
|
|
37
|
+
const trustProxy = env.MCP_TRUST_PROXY?.toLowerCase() === "true";
|
|
38
|
+
const base = `https://login.microsoftonline.com/${tenantId}`;
|
|
39
|
+
return {
|
|
40
|
+
serverUrl,
|
|
41
|
+
tenantId,
|
|
42
|
+
clientId,
|
|
43
|
+
clientSecret,
|
|
44
|
+
audience,
|
|
45
|
+
scopes,
|
|
46
|
+
writeRole,
|
|
47
|
+
trustProxy,
|
|
48
|
+
authorizeEndpoint: `${base}/oauth2/v2.0/authorize`,
|
|
49
|
+
tokenEndpoint: `${base}/oauth2/v2.0/token`,
|
|
50
|
+
issuers: [
|
|
51
|
+
`${base}/v2.0`,
|
|
52
|
+
`https://sts.windows.net/${tenantId}/`,
|
|
53
|
+
],
|
|
54
|
+
jwksUri: `${base}/discovery/v2.0/keys`,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
const TTL_CLIENT = 1000 * 60 * 60 * 24 * 30; // 30d
|
|
58
|
+
const TTL_PENDING = 1000 * 60 * 10; // 10m
|
|
59
|
+
const TTL_CODE = 1000 * 60 * 5; // 5m
|
|
60
|
+
// Default to in-memory; initOAuthStore() upgrades to Redis when REDIS_URL is set.
|
|
61
|
+
// Keys: client:<id>, pending:<state>, code:<code>. TTL handled by the store.
|
|
62
|
+
let store = new InMemoryKvStore();
|
|
63
|
+
/**
|
|
64
|
+
* Initialize the broker-state store from the environment. With REDIS_URL set,
|
|
65
|
+
* broker state (DCR clients, pending flows, issued codes) persists across
|
|
66
|
+
* redeploys and can be shared by multiple replicas. Call once at startup; keys
|
|
67
|
+
* are namespaced by issuer host so co-tenant MCPs can share one Redis.
|
|
68
|
+
*/
|
|
69
|
+
export async function initOAuthStore(env, serverUrl) {
|
|
70
|
+
let host = "default";
|
|
71
|
+
try {
|
|
72
|
+
host = new URL(serverUrl).host;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
/* keep default */
|
|
76
|
+
}
|
|
77
|
+
const prefix = `${env.REDIS_KEY_PREFIX || "bookstack-mcp"}:${host}`;
|
|
78
|
+
store = await createStore(env.REDIS_URL, prefix);
|
|
79
|
+
}
|
|
80
|
+
// ---- HTTP helpers ----
|
|
81
|
+
function sendJson(res, status, body) {
|
|
82
|
+
res.writeHead(status, {
|
|
83
|
+
"Content-Type": "application/json",
|
|
84
|
+
"Cache-Control": "no-store",
|
|
85
|
+
});
|
|
86
|
+
res.end(JSON.stringify(body));
|
|
87
|
+
}
|
|
88
|
+
function readBody(req) {
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
const chunks = [];
|
|
91
|
+
req.on("data", (c) => chunks.push(c));
|
|
92
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
93
|
+
req.on("error", reject);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
function parseForm(raw) {
|
|
97
|
+
const out = {};
|
|
98
|
+
for (const [k, v] of new URLSearchParams(raw))
|
|
99
|
+
out[k] = v;
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
function s256(verifier) {
|
|
103
|
+
return createHash("sha256").update(verifier).digest("base64url");
|
|
104
|
+
}
|
|
105
|
+
// ---- JWKS / token validation ----
|
|
106
|
+
let jwks = null;
|
|
107
|
+
function getJwks(cfg) {
|
|
108
|
+
if (!jwks)
|
|
109
|
+
jwks = createRemoteJWKSet(new URL(cfg.jwksUri));
|
|
110
|
+
return jwks;
|
|
111
|
+
}
|
|
112
|
+
function audienceMatches(cfg, aud) {
|
|
113
|
+
const accepted = new Set([cfg.audience, cfg.clientId, `api://${cfg.clientId}`]);
|
|
114
|
+
if (typeof aud === "string")
|
|
115
|
+
return accepted.has(aud);
|
|
116
|
+
if (Array.isArray(aud))
|
|
117
|
+
return aud.some((a) => accepted.has(a));
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
export async function validateBearer(req, cfg) {
|
|
121
|
+
const header = req.headers["authorization"];
|
|
122
|
+
if (!header || Array.isArray(header) || !header.startsWith("Bearer ")) {
|
|
123
|
+
return { ok: false, error: "missing bearer token" };
|
|
124
|
+
}
|
|
125
|
+
const token = header.slice("Bearer ".length).trim();
|
|
126
|
+
try {
|
|
127
|
+
const { payload } = await jwtVerify(token, getJwks(cfg), {
|
|
128
|
+
issuer: cfg.issuers,
|
|
129
|
+
});
|
|
130
|
+
if (!audienceMatches(cfg, payload.aud)) {
|
|
131
|
+
return { ok: false, error: "audience mismatch" };
|
|
132
|
+
}
|
|
133
|
+
const roles = Array.isArray(payload.roles)
|
|
134
|
+
? payload.roles
|
|
135
|
+
: [];
|
|
136
|
+
return {
|
|
137
|
+
ok: true,
|
|
138
|
+
sub: typeof payload.sub === "string" ? payload.sub : undefined,
|
|
139
|
+
roles,
|
|
140
|
+
isWriter: roles.includes(cfg.writeRole),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
// Emit the 401 that bootstraps Claude's OAuth discovery (RFC 9728).
|
|
148
|
+
export function sendUnauthorized(res, cfg) {
|
|
149
|
+
res.writeHead(401, {
|
|
150
|
+
"Content-Type": "application/json",
|
|
151
|
+
"WWW-Authenticate": `Bearer resource_metadata="${cfg.serverUrl}/.well-known/oauth-protected-resource"`,
|
|
152
|
+
});
|
|
153
|
+
res.end(JSON.stringify({
|
|
154
|
+
jsonrpc: "2.0",
|
|
155
|
+
error: { code: -32001, message: "Unauthorized: authentication required" },
|
|
156
|
+
id: null,
|
|
157
|
+
}));
|
|
158
|
+
}
|
|
159
|
+
// ---- OAuth route handling ----
|
|
160
|
+
// Returns true if this request was an OAuth endpoint (handled here), false otherwise.
|
|
161
|
+
export async function handleOAuthRoutes(req, res, cfg) {
|
|
162
|
+
const url = new URL(req.url ?? "/", cfg.serverUrl);
|
|
163
|
+
const path = url.pathname;
|
|
164
|
+
if (["/register", "/authorize", "/callback", "/token"].includes(path)) {
|
|
165
|
+
console.error(`[oauth] ${req.method} ${path}` +
|
|
166
|
+
(path === "/callback"
|
|
167
|
+
? ` error=${url.searchParams.get("error") ?? ""} code=${url.searchParams.get("code") ? "yes" : "no"} state=${url.searchParams.get("state") ? "yes" : "no"}`
|
|
168
|
+
: ""));
|
|
169
|
+
}
|
|
170
|
+
// RFC 9728 — Protected Resource Metadata
|
|
171
|
+
if (path === "/.well-known/oauth-protected-resource") {
|
|
172
|
+
sendJson(res, 200, {
|
|
173
|
+
resource: cfg.serverUrl,
|
|
174
|
+
authorization_servers: [cfg.serverUrl],
|
|
175
|
+
bearer_methods_supported: ["header"],
|
|
176
|
+
scopes_supported: cfg.scopes.split(/\s+/).filter(Boolean),
|
|
177
|
+
});
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
// RFC 8414 — Authorization Server Metadata (we ARE the AS, proxying to Entra)
|
|
181
|
+
if (path === "/.well-known/oauth-authorization-server") {
|
|
182
|
+
sendJson(res, 200, {
|
|
183
|
+
issuer: cfg.serverUrl,
|
|
184
|
+
authorization_endpoint: `${cfg.serverUrl}/authorize`,
|
|
185
|
+
token_endpoint: `${cfg.serverUrl}/token`,
|
|
186
|
+
registration_endpoint: `${cfg.serverUrl}/register`,
|
|
187
|
+
response_types_supported: ["code"],
|
|
188
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
189
|
+
code_challenge_methods_supported: ["S256"],
|
|
190
|
+
token_endpoint_auth_methods_supported: ["none"],
|
|
191
|
+
scopes_supported: cfg.scopes.split(/\s+/).filter(Boolean),
|
|
192
|
+
});
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
// RFC 7591 — Dynamic Client Registration (handled locally)
|
|
196
|
+
if (path === "/register" && req.method === "POST") {
|
|
197
|
+
let meta = {};
|
|
198
|
+
try {
|
|
199
|
+
meta = JSON.parse((await readBody(req)) || "{}");
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
sendJson(res, 400, { error: "invalid_client_metadata" });
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
const redirectUris = Array.isArray(meta.redirect_uris)
|
|
206
|
+
? meta.redirect_uris
|
|
207
|
+
: [];
|
|
208
|
+
if (redirectUris.length === 0) {
|
|
209
|
+
sendJson(res, 400, {
|
|
210
|
+
error: "invalid_redirect_uri",
|
|
211
|
+
error_description: "redirect_uris is required",
|
|
212
|
+
});
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
const clientId = `mcp-${randomUUID()}`;
|
|
216
|
+
await store.set(`client:${clientId}`, { clientId, redirectUris }, TTL_CLIENT);
|
|
217
|
+
sendJson(res, 201, {
|
|
218
|
+
client_id: clientId,
|
|
219
|
+
redirect_uris: redirectUris,
|
|
220
|
+
token_endpoint_auth_method: "none",
|
|
221
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
222
|
+
response_types: ["code"],
|
|
223
|
+
});
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
// Authorization endpoint — redirect the browser up to Entra.
|
|
227
|
+
if (path === "/authorize" && req.method === "GET") {
|
|
228
|
+
const q = url.searchParams;
|
|
229
|
+
const clientId = q.get("client_id") ?? "";
|
|
230
|
+
const redirectUri = q.get("redirect_uri") ?? "";
|
|
231
|
+
const clientState = q.get("state") ?? "";
|
|
232
|
+
const codeChallenge = q.get("code_challenge") ?? "";
|
|
233
|
+
const method = q.get("code_challenge_method") ?? "";
|
|
234
|
+
const client = await store.get(`client:${clientId}`);
|
|
235
|
+
if (!client) {
|
|
236
|
+
sendJson(res, 400, { error: "invalid_client" });
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
if (!client.redirectUris.includes(redirectUri)) {
|
|
240
|
+
sendJson(res, 400, { error: "invalid_request", error_description: "redirect_uri mismatch" });
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
if (method !== "S256" || !codeChallenge) {
|
|
244
|
+
sendJson(res, 400, { error: "invalid_request", error_description: "PKCE S256 required" });
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
const upstreamState = randomBytes(24).toString("base64url");
|
|
248
|
+
await store.set(`pending:${upstreamState}`, {
|
|
249
|
+
clientId,
|
|
250
|
+
clientRedirectUri: redirectUri,
|
|
251
|
+
clientState,
|
|
252
|
+
codeChallenge,
|
|
253
|
+
}, TTL_PENDING);
|
|
254
|
+
const up = new URL(cfg.authorizeEndpoint);
|
|
255
|
+
up.searchParams.set("client_id", cfg.clientId);
|
|
256
|
+
up.searchParams.set("response_type", "code");
|
|
257
|
+
up.searchParams.set("redirect_uri", `${cfg.serverUrl}/callback`);
|
|
258
|
+
up.searchParams.set("response_mode", "query");
|
|
259
|
+
up.searchParams.set("scope", cfg.scopes);
|
|
260
|
+
up.searchParams.set("state", upstreamState);
|
|
261
|
+
res.writeHead(302, { Location: up.toString() });
|
|
262
|
+
res.end();
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
// Callback from Entra — exchange code upstream, then hand our own code to the client.
|
|
266
|
+
if (path === "/callback" && req.method === "GET") {
|
|
267
|
+
const q = url.searchParams;
|
|
268
|
+
const upstreamState = q.get("state") ?? "";
|
|
269
|
+
const code = q.get("code") ?? "";
|
|
270
|
+
const err = q.get("error");
|
|
271
|
+
const p = await store.get(`pending:${upstreamState}`);
|
|
272
|
+
if (!p) {
|
|
273
|
+
sendJson(res, 400, { error: "invalid_state" });
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
await store.del(`pending:${upstreamState}`);
|
|
277
|
+
if (err || !code) {
|
|
278
|
+
const dest = new URL(p.clientRedirectUri);
|
|
279
|
+
dest.searchParams.set("error", err || "invalid_request");
|
|
280
|
+
if (p.clientState)
|
|
281
|
+
dest.searchParams.set("state", p.clientState);
|
|
282
|
+
res.writeHead(302, { Location: dest.toString() });
|
|
283
|
+
res.end();
|
|
284
|
+
return true;
|
|
285
|
+
}
|
|
286
|
+
// Confidential-client code exchange with Entra.
|
|
287
|
+
const tokenRes = await fetch(cfg.tokenEndpoint, {
|
|
288
|
+
method: "POST",
|
|
289
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
290
|
+
body: new URLSearchParams({
|
|
291
|
+
client_id: cfg.clientId,
|
|
292
|
+
client_secret: cfg.clientSecret,
|
|
293
|
+
grant_type: "authorization_code",
|
|
294
|
+
code,
|
|
295
|
+
redirect_uri: `${cfg.serverUrl}/callback`,
|
|
296
|
+
scope: cfg.scopes,
|
|
297
|
+
}),
|
|
298
|
+
});
|
|
299
|
+
const rawTok = await tokenRes.text();
|
|
300
|
+
let tokenJson = null;
|
|
301
|
+
try {
|
|
302
|
+
tokenJson = JSON.parse(rawTok);
|
|
303
|
+
}
|
|
304
|
+
catch { /* non-JSON */ }
|
|
305
|
+
if (!tokenRes.ok || !tokenJson || !tokenJson.access_token) {
|
|
306
|
+
console.error(`[oauth] /callback Entra token exchange FAILED: status=${tokenRes.status} body=${rawTok.slice(0, 600)}`);
|
|
307
|
+
const dest = new URL(p.clientRedirectUri);
|
|
308
|
+
dest.searchParams.set("error", "server_error");
|
|
309
|
+
if (p.clientState)
|
|
310
|
+
dest.searchParams.set("state", p.clientState);
|
|
311
|
+
res.writeHead(302, { Location: dest.toString() });
|
|
312
|
+
res.end();
|
|
313
|
+
return true;
|
|
314
|
+
}
|
|
315
|
+
console.error("[oauth] /callback Entra token exchange OK; issuing client code");
|
|
316
|
+
const ourCode = randomBytes(32).toString("base64url");
|
|
317
|
+
await store.set(`code:${ourCode}`, {
|
|
318
|
+
clientId: p.clientId,
|
|
319
|
+
clientRedirectUri: p.clientRedirectUri,
|
|
320
|
+
codeChallenge: p.codeChallenge,
|
|
321
|
+
tokenResponse: tokenJson,
|
|
322
|
+
}, TTL_CODE);
|
|
323
|
+
const dest = new URL(p.clientRedirectUri);
|
|
324
|
+
dest.searchParams.set("code", ourCode);
|
|
325
|
+
if (p.clientState)
|
|
326
|
+
dest.searchParams.set("state", p.clientState);
|
|
327
|
+
res.writeHead(302, { Location: dest.toString() });
|
|
328
|
+
res.end();
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
331
|
+
// Token endpoint — code exchange (verify PKCE) and refresh pass-through.
|
|
332
|
+
if (path === "/token" && req.method === "POST") {
|
|
333
|
+
const form = parseForm(await readBody(req));
|
|
334
|
+
const grant = form["grant_type"];
|
|
335
|
+
if (grant === "authorization_code") {
|
|
336
|
+
const issued = await store.get(`code:${form["code"] ?? ""}`);
|
|
337
|
+
if (!issued) {
|
|
338
|
+
console.error("[oauth] /token authorization_code: invalid_grant (code not found/expired)");
|
|
339
|
+
sendJson(res, 400, { error: "invalid_grant" });
|
|
340
|
+
return true;
|
|
341
|
+
}
|
|
342
|
+
await store.del(`code:${form["code"]}`);
|
|
343
|
+
const verifier = form["code_verifier"] ?? "";
|
|
344
|
+
if (!verifier || s256(verifier) !== issued.codeChallenge) {
|
|
345
|
+
console.error(`[oauth] /token authorization_code: PKCE FAILED (verifier=${verifier ? "present" : "missing"})`);
|
|
346
|
+
sendJson(res, 400, { error: "invalid_grant", error_description: "PKCE verification failed" });
|
|
347
|
+
return true;
|
|
348
|
+
}
|
|
349
|
+
if (form["client_id"] && form["client_id"] !== issued.clientId) {
|
|
350
|
+
console.error(`[oauth] /token authorization_code: client mismatch (got=${form["client_id"]} want=${issued.clientId})`);
|
|
351
|
+
sendJson(res, 400, { error: "invalid_client" });
|
|
352
|
+
return true;
|
|
353
|
+
}
|
|
354
|
+
console.error("[oauth] /token authorization_code: OK (returning Entra token to client)");
|
|
355
|
+
sendJson(res, 200, issued.tokenResponse);
|
|
356
|
+
return true;
|
|
357
|
+
}
|
|
358
|
+
if (grant === "refresh_token") {
|
|
359
|
+
// Proxy the refresh straight to Entra (confidential client).
|
|
360
|
+
const refreshRes = await fetch(cfg.tokenEndpoint, {
|
|
361
|
+
method: "POST",
|
|
362
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
363
|
+
body: new URLSearchParams({
|
|
364
|
+
client_id: cfg.clientId,
|
|
365
|
+
client_secret: cfg.clientSecret,
|
|
366
|
+
grant_type: "refresh_token",
|
|
367
|
+
refresh_token: form["refresh_token"] ?? "",
|
|
368
|
+
scope: cfg.scopes,
|
|
369
|
+
}),
|
|
370
|
+
});
|
|
371
|
+
const refreshJson = await refreshRes.json().catch(() => null);
|
|
372
|
+
sendJson(res, refreshRes.ok ? 200 : 400, refreshJson ?? { error: "invalid_grant" });
|
|
373
|
+
return true;
|
|
374
|
+
}
|
|
375
|
+
sendJson(res, 400, { error: "unsupported_grant_type" });
|
|
376
|
+
return true;
|
|
377
|
+
}
|
|
378
|
+
return false;
|
|
379
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Minimal async key/value store with per-key TTL for the OAuth proxy's broker
|
|
2
|
+
// state (DCR clients, pending flows, issued codes). Redis-backed when REDIS_URL
|
|
3
|
+
// is set — so state survives redeploys and can run more than one replica —
|
|
4
|
+
// otherwise in-process memory. Mirrors the store in ttpears/gitlab-mcp.
|
|
5
|
+
const SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
|
6
|
+
/** In-process store with lazy expiry on read plus a periodic sweep. */
|
|
7
|
+
export class InMemoryKvStore {
|
|
8
|
+
prefix;
|
|
9
|
+
map = new Map();
|
|
10
|
+
sweep;
|
|
11
|
+
constructor(prefix = "bookstack-mcp:") {
|
|
12
|
+
this.prefix = prefix;
|
|
13
|
+
this.sweep = setInterval(() => {
|
|
14
|
+
const now = Date.now();
|
|
15
|
+
for (const [k, v] of this.map)
|
|
16
|
+
if (v.expiresAt < now)
|
|
17
|
+
this.map.delete(k);
|
|
18
|
+
}, SWEEP_INTERVAL_MS);
|
|
19
|
+
this.sweep.unref?.();
|
|
20
|
+
}
|
|
21
|
+
async get(key) {
|
|
22
|
+
const entry = this.map.get(this.prefix + key);
|
|
23
|
+
if (!entry)
|
|
24
|
+
return undefined;
|
|
25
|
+
if (entry.expiresAt < Date.now()) {
|
|
26
|
+
this.map.delete(this.prefix + key);
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
return entry.value;
|
|
30
|
+
}
|
|
31
|
+
async set(key, value, ttlMs) {
|
|
32
|
+
this.map.set(this.prefix + key, { value, expiresAt: Date.now() + ttlMs });
|
|
33
|
+
}
|
|
34
|
+
async del(key) {
|
|
35
|
+
this.map.delete(this.prefix + key);
|
|
36
|
+
}
|
|
37
|
+
dispose() {
|
|
38
|
+
if (this.sweep)
|
|
39
|
+
clearInterval(this.sweep);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Redis-backed store. TTL enforced by Redis (PX); no sweep needed. */
|
|
43
|
+
export class RedisKvStore {
|
|
44
|
+
client;
|
|
45
|
+
prefix;
|
|
46
|
+
constructor(client, prefix) {
|
|
47
|
+
this.client = client;
|
|
48
|
+
this.prefix = prefix;
|
|
49
|
+
}
|
|
50
|
+
async get(key) {
|
|
51
|
+
const raw = await this.client.get(this.prefix + key);
|
|
52
|
+
return raw == null ? undefined : JSON.parse(raw);
|
|
53
|
+
}
|
|
54
|
+
async set(key, value, ttlMs) {
|
|
55
|
+
await this.client.set(this.prefix + key, JSON.stringify(value), "PX", Math.max(1, Math.floor(ttlMs)));
|
|
56
|
+
}
|
|
57
|
+
async del(key) {
|
|
58
|
+
await this.client.del(this.prefix + key);
|
|
59
|
+
}
|
|
60
|
+
dispose() {
|
|
61
|
+
void this.client.quit();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Build the store. Redis when `redisUrl` is set (ioredis loaded lazily so
|
|
66
|
+
* non-Redis deployments don't pay for it); otherwise in-memory. `keyPrefix`
|
|
67
|
+
* should include the issuer host so co-tenant MCPs sharing one Redis don't
|
|
68
|
+
* collide while replicas of the same issuer DO share state.
|
|
69
|
+
*/
|
|
70
|
+
export async function createStore(redisUrl, keyPrefix) {
|
|
71
|
+
const prefix = keyPrefix.endsWith(":") ? keyPrefix : `${keyPrefix}:`;
|
|
72
|
+
if (redisUrl) {
|
|
73
|
+
const mod = await import("ioredis");
|
|
74
|
+
const Redis = mod.default || mod;
|
|
75
|
+
const client = new Redis(redisUrl, { maxRetriesPerRequest: 2, lazyConnect: false });
|
|
76
|
+
return new RedisKvStore(client, prefix);
|
|
77
|
+
}
|
|
78
|
+
return new InMemoryKvStore(prefix);
|
|
79
|
+
}
|
package/dist/prompts.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// MCP prompts for BookStack — one-click actions surfaced in Claude's connector menu
|
|
2
|
+
// (and any prompts-capable MCP client). Content-oriented and read-only: each prompt just
|
|
3
|
+
// returns a templated instruction that drives the existing read tools. No per-user
|
|
4
|
+
// identity is assumed (the connector uses a shared service token).
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
// Small helper: a prompt handler returns a single user message.
|
|
7
|
+
function userMessage(text) {
|
|
8
|
+
return { messages: [{ role: "user", content: { type: "text", text } }] };
|
|
9
|
+
}
|
|
10
|
+
export function registerPrompts(server) {
|
|
11
|
+
server.registerPrompt("answer_from_wiki", {
|
|
12
|
+
title: "Answer from the wiki",
|
|
13
|
+
description: "Answer a question using the BookStack wiki, with citations and links.",
|
|
14
|
+
argsSchema: {
|
|
15
|
+
question: z.string().describe("The question to answer from the wiki")
|
|
16
|
+
}
|
|
17
|
+
}, async ({ question }) => userMessage(`Answer this question using the BookStack wiki: "${question}".\n\n` +
|
|
18
|
+
`Use search_content to find the most relevant pages, read the top matches with ` +
|
|
19
|
+
`get_page, then answer concisely. Cite each source by page name with its URL. ` +
|
|
20
|
+
`If the wiki has nothing relevant, say so rather than guessing.`));
|
|
21
|
+
server.registerPrompt("find_pages", {
|
|
22
|
+
title: "Find pages about a topic",
|
|
23
|
+
description: "List BookStack pages matching a topic, with previews and links.",
|
|
24
|
+
argsSchema: {
|
|
25
|
+
topic: z.string().describe("Topic or keywords to search for")
|
|
26
|
+
}
|
|
27
|
+
}, async ({ topic }) => userMessage(`Find BookStack pages about "${topic}" using search_content (and search_pages if ` +
|
|
28
|
+
`helpful). Return a ranked list — for each result give the page name, a one-line ` +
|
|
29
|
+
`preview, and its URL. Do not read full page contents unless I ask.`));
|
|
30
|
+
server.registerPrompt("summarize_book", {
|
|
31
|
+
title: "Summarize a book",
|
|
32
|
+
description: "Produce a structured summary of a BookStack book with section links.",
|
|
33
|
+
argsSchema: {
|
|
34
|
+
book: z.string().describe("Book name or numeric id")
|
|
35
|
+
}
|
|
36
|
+
}, async ({ book }) => userMessage(`Summarize the BookStack book "${book}".\n\n` +
|
|
37
|
+
`If that is a name rather than a numeric id, first find it with search_content ` +
|
|
38
|
+
`using {type:book}. Then use get_book and get_pages to read its chapters and pages, ` +
|
|
39
|
+
`and produce a structured summary (overview, then key points per chapter/section). ` +
|
|
40
|
+
`Include a link to the book and to the sections you reference.`));
|
|
41
|
+
server.registerPrompt("recent_changes", {
|
|
42
|
+
title: "What changed recently",
|
|
43
|
+
description: "Summarize recently created or updated wiki content.",
|
|
44
|
+
argsSchema: {
|
|
45
|
+
days: z.string().optional().describe("How many days back to look (default 30)")
|
|
46
|
+
}
|
|
47
|
+
}, async ({ days }) => userMessage(`Summarize what changed in the BookStack wiki in the last ${days || "30"} days using ` +
|
|
48
|
+
`get_recent_changes. Group the changes by book (and note the type — page, chapter, ` +
|
|
49
|
+
`book), and include a link to each changed item. Highlight anything that looks ` +
|
|
50
|
+
`significant.`));
|
|
51
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bookstack-mcp",
|
|
3
|
-
"version": "
|
|
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": {
|
|
@@ -42,6 +42,8 @@
|
|
|
42
42
|
"dependencies": {
|
|
43
43
|
"@modelcontextprotocol/sdk": "^1.25.3",
|
|
44
44
|
"axios": "^1.6.0",
|
|
45
|
+
"ioredis": "^5.11.1",
|
|
46
|
+
"jose": "^6.2.3",
|
|
45
47
|
"zod": "^3.25.76"
|
|
46
48
|
},
|
|
47
49
|
"devDependencies": {
|