docusaurus-plugin-mcp-server 0.6.0 → 0.8.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,9 +1,10 @@
1
- import fs from 'fs-extra';
2
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
2
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
4
3
  import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
5
4
  import { z } from 'zod';
6
5
  import FlexSearch from 'flexsearch';
6
+ import fs from 'fs-extra';
7
+ import 'http';
7
8
 
8
9
  // src/mcp/server.ts
9
10
  var FIELD_WEIGHTS = {
@@ -136,19 +137,126 @@ async function importSearchIndex(data) {
136
137
  }
137
138
  return index;
138
139
  }
140
+ var FlexSearchProvider = class {
141
+ name = "flexsearch";
142
+ docs = null;
143
+ searchIndex = null;
144
+ ready = false;
145
+ async initialize(_context, initData) {
146
+ if (!initData) {
147
+ throw new Error("[FlexSearch] SearchProviderInitData required for FlexSearch provider");
148
+ }
149
+ if (initData.docs && initData.indexData) {
150
+ this.docs = initData.docs;
151
+ this.searchIndex = await importSearchIndex(initData.indexData);
152
+ this.ready = true;
153
+ return;
154
+ }
155
+ if (initData.docsPath && initData.indexPath) {
156
+ if (await fs.pathExists(initData.docsPath)) {
157
+ this.docs = await fs.readJson(initData.docsPath);
158
+ } else {
159
+ throw new Error(`[FlexSearch] Docs file not found: ${initData.docsPath}`);
160
+ }
161
+ if (await fs.pathExists(initData.indexPath)) {
162
+ const indexData = await fs.readJson(initData.indexPath);
163
+ this.searchIndex = await importSearchIndex(indexData);
164
+ } else {
165
+ throw new Error(`[FlexSearch] Search index not found: ${initData.indexPath}`);
166
+ }
167
+ this.ready = true;
168
+ return;
169
+ }
170
+ throw new Error(
171
+ "[FlexSearch] Invalid init data: must provide either file paths (docsPath, indexPath) or pre-loaded data (docs, indexData)"
172
+ );
173
+ }
174
+ isReady() {
175
+ return this.ready && this.docs !== null && this.searchIndex !== null;
176
+ }
177
+ async search(query, options) {
178
+ if (!this.isReady() || !this.docs || !this.searchIndex) {
179
+ throw new Error("[FlexSearch] Provider not initialized");
180
+ }
181
+ const limit = options?.limit ?? 5;
182
+ return searchIndex(this.searchIndex, this.docs, query, { limit });
183
+ }
184
+ async getDocument(route) {
185
+ if (!this.docs) {
186
+ throw new Error("[FlexSearch] Provider not initialized");
187
+ }
188
+ if (this.docs[route]) {
189
+ return this.docs[route];
190
+ }
191
+ const normalizedRoute = route.startsWith("/") ? route : `/${route}`;
192
+ const withoutSlash = route.startsWith("/") ? route.slice(1) : route;
193
+ return this.docs[normalizedRoute] ?? this.docs[withoutSlash] ?? null;
194
+ }
195
+ async healthCheck() {
196
+ if (!this.isReady()) {
197
+ return { healthy: false, message: "FlexSearch provider not initialized" };
198
+ }
199
+ const docCount = this.docs ? Object.keys(this.docs).length : 0;
200
+ return {
201
+ healthy: true,
202
+ message: `FlexSearch provider ready with ${docCount} documents`
203
+ };
204
+ }
205
+ /**
206
+ * Get all loaded documents (for compatibility with existing server code)
207
+ */
208
+ getDocs() {
209
+ return this.docs;
210
+ }
211
+ /**
212
+ * Get the FlexSearch index (for compatibility with existing server code)
213
+ */
214
+ getSearchIndex() {
215
+ return this.searchIndex;
216
+ }
217
+ };
139
218
 
140
- // src/mcp/tools/docs-search.ts
141
- function executeDocsSearch(params, index, docs) {
142
- const { query, limit = 5 } = params;
143
- if (!query || typeof query !== "string" || query.trim().length === 0) {
144
- throw new Error("Query parameter is required and must be a non-empty string");
145
- }
146
- const effectiveLimit = Math.min(Math.max(1, limit), 20);
147
- const results = searchIndex(index, docs, query.trim(), {
148
- limit: effectiveLimit
149
- });
150
- return results;
219
+ // src/providers/loader.ts
220
+ async function loadSearchProvider(specifier) {
221
+ if (specifier === "flexsearch") {
222
+ return new FlexSearchProvider();
223
+ }
224
+ try {
225
+ const module = await import(specifier);
226
+ const ProviderClass = module.default;
227
+ if (typeof ProviderClass === "function") {
228
+ const instance = new ProviderClass();
229
+ if (!isSearchProvider(instance)) {
230
+ throw new Error(
231
+ `Invalid search provider module "${specifier}": does not implement SearchProvider interface`
232
+ );
233
+ }
234
+ return instance;
235
+ }
236
+ if (isSearchProvider(ProviderClass)) {
237
+ return ProviderClass;
238
+ }
239
+ throw new Error(
240
+ `Invalid search provider module "${specifier}": must export a default class or SearchProvider instance`
241
+ );
242
+ } catch (error) {
243
+ if (error instanceof Error && error.message.includes("Cannot find module")) {
244
+ throw new Error(
245
+ `Search provider module not found: "${specifier}". Check the path or package name.`
246
+ );
247
+ }
248
+ throw error;
249
+ }
250
+ }
251
+ function isSearchProvider(obj) {
252
+ if (!obj || typeof obj !== "object") {
253
+ return false;
254
+ }
255
+ const provider = obj;
256
+ return typeof provider.name === "string" && typeof provider.initialize === "function" && typeof provider.isReady === "function" && typeof provider.search === "function";
151
257
  }
258
+
259
+ // src/mcp/tools/docs-search.ts
152
260
  function formatSearchResults(results, baseUrl) {
153
261
  if (results.length === 0) {
154
262
  return "No matching documents found.";
@@ -173,29 +281,7 @@ function formatSearchResults(results, baseUrl) {
173
281
  return lines.join("\n");
174
282
  }
175
283
 
176
- // src/mcp/tools/docs-get-page.ts
177
- function executeDocsGetPage(params, docs) {
178
- const { route } = params;
179
- if (!route || typeof route !== "string") {
180
- throw new Error("Route parameter is required and must be a string");
181
- }
182
- let normalizedRoute = route.trim();
183
- if (!normalizedRoute.startsWith("/")) {
184
- normalizedRoute = "/" + normalizedRoute;
185
- }
186
- if (normalizedRoute.length > 1 && normalizedRoute.endsWith("/")) {
187
- normalizedRoute = normalizedRoute.slice(0, -1);
188
- }
189
- const doc = docs[normalizedRoute];
190
- if (!doc) {
191
- const altRoute = normalizedRoute.slice(1);
192
- if (docs[altRoute]) {
193
- return docs[altRoute] ?? null;
194
- }
195
- return null;
196
- }
197
- return doc;
198
- }
284
+ // src/mcp/tools/docs-fetch.ts
199
285
  function formatPageContent(doc, baseUrl) {
200
286
  if (!doc) {
201
287
  return "Page not found. Please check the route path and try again.";
@@ -230,89 +316,6 @@ function formatPageContent(doc, baseUrl) {
230
316
  return lines.join("\n");
231
317
  }
232
318
 
233
- // src/processing/heading-extractor.ts
234
- function extractSection(markdown, headingId, headings) {
235
- const heading = headings.find((h) => h.id === headingId);
236
- if (!heading) {
237
- return null;
238
- }
239
- return markdown.slice(heading.startOffset, heading.endOffset).trim();
240
- }
241
-
242
- // src/mcp/tools/docs-get-section.ts
243
- function executeDocsGetSection(params, docs) {
244
- const { route, headingId } = params;
245
- if (!route || typeof route !== "string") {
246
- throw new Error("Route parameter is required and must be a string");
247
- }
248
- if (!headingId || typeof headingId !== "string") {
249
- throw new Error("HeadingId parameter is required and must be a string");
250
- }
251
- let normalizedRoute = route.trim();
252
- if (!normalizedRoute.startsWith("/")) {
253
- normalizedRoute = "/" + normalizedRoute;
254
- }
255
- if (normalizedRoute.length > 1 && normalizedRoute.endsWith("/")) {
256
- normalizedRoute = normalizedRoute.slice(0, -1);
257
- }
258
- const doc = docs[normalizedRoute];
259
- if (!doc) {
260
- return {
261
- content: null,
262
- doc: null,
263
- headingText: null,
264
- availableHeadings: []
265
- };
266
- }
267
- const availableHeadings = doc.headings.map((h) => ({
268
- id: h.id,
269
- text: h.text,
270
- level: h.level
271
- }));
272
- const heading = doc.headings.find((h) => h.id === headingId.trim());
273
- if (!heading) {
274
- return {
275
- content: null,
276
- doc,
277
- headingText: null,
278
- availableHeadings
279
- };
280
- }
281
- const content = extractSection(doc.markdown, headingId.trim(), doc.headings);
282
- return {
283
- content,
284
- doc,
285
- headingText: heading.text,
286
- availableHeadings
287
- };
288
- }
289
- function formatSectionContent(result, headingId, baseUrl) {
290
- if (!result.doc) {
291
- return "Page not found. Please check the route path and try again.";
292
- }
293
- if (!result.content) {
294
- const lines2 = [`Section "${headingId}" not found in this document.`, "", "Available sections:"];
295
- for (const heading of result.availableHeadings) {
296
- const indent = " ".repeat(heading.level - 1);
297
- lines2.push(`${indent}- ${heading.text} (id: ${heading.id})`);
298
- }
299
- return lines2.join("\n");
300
- }
301
- const lines = [];
302
- const fullUrl = baseUrl ? `${baseUrl.replace(/\/$/, "")}${result.doc.route}#${headingId}` : null;
303
- lines.push(`# ${result.headingText}`);
304
- if (fullUrl) {
305
- lines.push(`> From: ${result.doc.title} - ${fullUrl}`);
306
- } else {
307
- lines.push(`> From: ${result.doc.title} (${result.doc.route})`);
308
- }
309
- lines.push("");
310
- lines.push("---");
311
- lines.push("");
312
- lines.push(result.content);
313
- return lines.join("\n");
314
- }
315
-
316
319
  // src/mcp/server.ts
317
320
  function isFileConfig(config) {
318
321
  return "docsPath" in config && "indexPath" in config;
@@ -322,8 +325,7 @@ function isDataConfig(config) {
322
325
  }
323
326
  var McpDocsServer = class {
324
327
  config;
325
- docs = null;
326
- searchIndex = null;
328
+ searchProvider = null;
327
329
  mcpServer;
328
330
  initialized = false;
329
331
  constructor(config) {
@@ -356,75 +358,83 @@ var McpDocsServer = class {
356
358
  },
357
359
  async ({ query, limit }) => {
358
360
  await this.initialize();
359
- if (!this.docs || !this.searchIndex) {
361
+ if (!this.searchProvider || !this.searchProvider.isReady()) {
360
362
  return {
361
363
  content: [{ type: "text", text: "Server not initialized. Please try again." }],
362
364
  isError: true
363
365
  };
364
366
  }
365
- const results = executeDocsSearch({ query, limit }, this.searchIndex, this.docs);
366
- return {
367
- content: [
368
- { type: "text", text: formatSearchResults(results, this.config.baseUrl) }
369
- ]
370
- };
367
+ try {
368
+ const results = await this.searchProvider.search(query, { limit });
369
+ return {
370
+ content: [
371
+ { type: "text", text: formatSearchResults(results, this.config.baseUrl) }
372
+ ]
373
+ };
374
+ } catch (error) {
375
+ console.error("[MCP] Search error:", error);
376
+ return {
377
+ content: [{ type: "text", text: `Search error: ${String(error)}` }],
378
+ isError: true
379
+ };
380
+ }
371
381
  }
372
382
  );
373
383
  this.mcpServer.registerTool(
374
- "docs_get_page",
384
+ "docs_fetch",
375
385
  {
376
- description: "Retrieve the complete content of a documentation page as markdown. Use this when you need the full content of a specific page.",
386
+ description: "Fetch the complete content of a documentation page. Use this when you need the full content of a specific page.",
377
387
  inputSchema: {
378
388
  route: z.string().min(1).describe('The page route path (e.g., "/docs/getting-started" or "/api/reference")')
379
389
  }
380
390
  },
381
391
  async ({ route }) => {
382
392
  await this.initialize();
383
- if (!this.docs) {
393
+ if (!this.searchProvider || !this.searchProvider.isReady()) {
384
394
  return {
385
395
  content: [{ type: "text", text: "Server not initialized. Please try again." }],
386
396
  isError: true
387
397
  };
388
398
  }
389
- const doc = executeDocsGetPage({ route }, this.docs);
390
- return {
391
- content: [{ type: "text", text: formatPageContent(doc, this.config.baseUrl) }]
392
- };
393
- }
394
- );
395
- this.mcpServer.registerTool(
396
- "docs_get_section",
397
- {
398
- description: "Retrieve a specific section from a documentation page by its heading ID. Use this when you need only a portion of a page rather than the entire content.",
399
- inputSchema: {
400
- route: z.string().min(1).describe("The page route path"),
401
- headingId: z.string().min(1).describe(
402
- 'The heading ID of the section to extract (e.g., "installation", "api-reference")'
403
- )
404
- }
405
- },
406
- async ({ route, headingId }) => {
407
- await this.initialize();
408
- if (!this.docs) {
399
+ try {
400
+ const doc = await this.getDocument(route);
409
401
  return {
410
- content: [{ type: "text", text: "Server not initialized. Please try again." }],
402
+ content: [{ type: "text", text: formatPageContent(doc, this.config.baseUrl) }]
403
+ };
404
+ } catch (error) {
405
+ console.error("[MCP] Get page error:", error);
406
+ return {
407
+ content: [{ type: "text", text: `Error getting page: ${String(error)}` }],
411
408
  isError: true
412
409
  };
413
410
  }
414
- const result = executeDocsGetSection({ route, headingId }, this.docs);
415
- return {
416
- content: [
417
- {
418
- type: "text",
419
- text: formatSectionContent(result, headingId, this.config.baseUrl)
420
- }
421
- ]
422
- };
423
411
  }
424
412
  );
425
413
  }
426
414
  /**
427
- * Load docs and search index
415
+ * Get a document by route using the search provider
416
+ */
417
+ async getDocument(route) {
418
+ if (!this.searchProvider) {
419
+ return null;
420
+ }
421
+ if (this.searchProvider.getDocument) {
422
+ return this.searchProvider.getDocument(route);
423
+ }
424
+ if (this.searchProvider instanceof FlexSearchProvider) {
425
+ const docs = this.searchProvider.getDocs();
426
+ if (!docs) return null;
427
+ if (docs[route]) {
428
+ return docs[route];
429
+ }
430
+ const normalizedRoute = route.startsWith("/") ? route : `/${route}`;
431
+ const withoutSlash = route.startsWith("/") ? route.slice(1) : route;
432
+ return docs[normalizedRoute] ?? docs[withoutSlash] ?? null;
433
+ }
434
+ return null;
435
+ }
436
+ /**
437
+ * Load docs and search index using the configured search provider
428
438
  *
429
439
  * For file-based config: reads from disk
430
440
  * For data config: uses pre-loaded data directly
@@ -434,24 +444,26 @@ var McpDocsServer = class {
434
444
  return;
435
445
  }
436
446
  try {
447
+ const searchSpecifier = this.config.search ?? "flexsearch";
448
+ this.searchProvider = await loadSearchProvider(searchSpecifier);
449
+ const providerContext = {
450
+ baseUrl: this.config.baseUrl ?? "",
451
+ serverName: this.config.name,
452
+ serverVersion: this.config.version ?? "1.0.0",
453
+ outputDir: ""
454
+ // Not relevant for runtime
455
+ };
456
+ const initData = {};
437
457
  if (isDataConfig(this.config)) {
438
- this.docs = this.config.docs;
439
- this.searchIndex = await importSearchIndex(this.config.searchIndexData);
458
+ initData.docs = this.config.docs;
459
+ initData.indexData = this.config.searchIndexData;
440
460
  } else if (isFileConfig(this.config)) {
441
- if (await fs.pathExists(this.config.docsPath)) {
442
- this.docs = await fs.readJson(this.config.docsPath);
443
- } else {
444
- throw new Error(`Docs file not found: ${this.config.docsPath}`);
445
- }
446
- if (await fs.pathExists(this.config.indexPath)) {
447
- const indexData = await fs.readJson(this.config.indexPath);
448
- this.searchIndex = await importSearchIndex(indexData);
449
- } else {
450
- throw new Error(`Search index not found: ${this.config.indexPath}`);
451
- }
461
+ initData.docsPath = this.config.docsPath;
462
+ initData.indexPath = this.config.indexPath;
452
463
  } else {
453
464
  throw new Error("Invalid server config: must provide either file paths or pre-loaded data");
454
465
  }
466
+ await this.searchProvider.initialize(providerContext, initData);
455
467
  this.initialized = true;
456
468
  } catch (error) {
457
469
  console.error("[MCP] Failed to initialize:", error);
@@ -512,12 +524,18 @@ var McpDocsServer = class {
512
524
  * Useful for health checks and debugging
513
525
  */
514
526
  async getStatus() {
527
+ let docCount = 0;
528
+ if (this.searchProvider instanceof FlexSearchProvider) {
529
+ const docs = this.searchProvider.getDocs();
530
+ docCount = docs ? Object.keys(docs).length : 0;
531
+ }
515
532
  return {
516
533
  name: this.config.name,
517
534
  version: this.config.version ?? "1.0.0",
518
535
  initialized: this.initialized,
519
- docCount: this.docs ? Object.keys(this.docs).length : 0,
520
- baseUrl: this.config.baseUrl
536
+ docCount,
537
+ baseUrl: this.config.baseUrl,
538
+ searchProvider: this.searchProvider?.name
521
539
  };
522
540
  }
523
541
  /**