docusaurus-plugin-mcp-server 0.5.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/LICENSE +21 -0
- package/README.md +505 -0
- package/dist/adapters-entry.d.mts +180 -0
- package/dist/adapters-entry.d.ts +180 -0
- package/dist/adapters-entry.js +918 -0
- package/dist/adapters-entry.js.map +1 -0
- package/dist/adapters-entry.mjs +908 -0
- package/dist/adapters-entry.mjs.map +1 -0
- package/dist/cli/verify.d.mts +1 -0
- package/dist/cli/verify.d.ts +1 -0
- package/dist/cli/verify.js +710 -0
- package/dist/cli/verify.js.map +1 -0
- package/dist/cli/verify.mjs +702 -0
- package/dist/cli/verify.mjs.map +1 -0
- package/dist/index-CzA4FjeE.d.mts +190 -0
- package/dist/index-CzA4FjeE.d.ts +190 -0
- package/dist/index.d.mts +234 -0
- package/dist/index.d.ts +234 -0
- package/dist/index.js +1070 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1037 -0
- package/dist/index.mjs.map +1 -0
- package/dist/theme/index.d.mts +87 -0
- package/dist/theme/index.d.ts +87 -0
- package/dist/theme/index.js +299 -0
- package/dist/theme/index.js.map +1 -0
- package/dist/theme/index.mjs +291 -0
- package/dist/theme/index.mjs.map +1 -0
- package/package.json +145 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1037 @@
|
|
|
1
|
+
import path2 from 'path';
|
|
2
|
+
import fs3 from 'fs-extra';
|
|
3
|
+
import pMap from 'p-map';
|
|
4
|
+
import { unified } from 'unified';
|
|
5
|
+
import rehypeParse from 'rehype-parse';
|
|
6
|
+
import { select } from 'hast-util-select';
|
|
7
|
+
import { toString } from 'hast-util-to-string';
|
|
8
|
+
import rehypeRemark from 'rehype-remark';
|
|
9
|
+
import remarkStringify from 'remark-stringify';
|
|
10
|
+
import remarkGfm from 'remark-gfm';
|
|
11
|
+
import FlexSearch from 'flexsearch';
|
|
12
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
13
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
14
|
+
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
|
15
|
+
import { z } from 'zod';
|
|
16
|
+
|
|
17
|
+
// src/plugin/docusaurus-plugin.ts
|
|
18
|
+
|
|
19
|
+
// src/types/index.ts
|
|
20
|
+
var DEFAULT_OPTIONS = {
|
|
21
|
+
outputDir: "mcp",
|
|
22
|
+
contentSelectors: ["article", "main", ".main-wrapper", '[role="main"]'],
|
|
23
|
+
excludeSelectors: [
|
|
24
|
+
"nav",
|
|
25
|
+
"header",
|
|
26
|
+
"footer",
|
|
27
|
+
"aside",
|
|
28
|
+
'[role="navigation"]',
|
|
29
|
+
'[role="banner"]',
|
|
30
|
+
'[role="contentinfo"]'
|
|
31
|
+
],
|
|
32
|
+
minContentLength: 50,
|
|
33
|
+
server: {
|
|
34
|
+
name: "docs-mcp-server",
|
|
35
|
+
version: "1.0.0"
|
|
36
|
+
},
|
|
37
|
+
excludeRoutes: ["/404*", "/search*"]
|
|
38
|
+
};
|
|
39
|
+
function filterRoutes(routes, excludePatterns) {
|
|
40
|
+
return routes.filter((route) => {
|
|
41
|
+
return !excludePatterns.some((pattern) => {
|
|
42
|
+
const regexPattern = pattern.replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
43
|
+
const regex = new RegExp(`^${regexPattern}$`);
|
|
44
|
+
return regex.test(route.path);
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
async function discoverHtmlFiles(outDir) {
|
|
49
|
+
const routes = [];
|
|
50
|
+
async function scanDirectory(dir) {
|
|
51
|
+
const entries = await fs3.readdir(dir, { withFileTypes: true });
|
|
52
|
+
for (const entry of entries) {
|
|
53
|
+
const fullPath = path2.join(dir, entry.name);
|
|
54
|
+
if (entry.isDirectory()) {
|
|
55
|
+
if (["assets", "img", "static"].includes(entry.name)) {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
await scanDirectory(fullPath);
|
|
59
|
+
} else if (entry.name === "index.html") {
|
|
60
|
+
const relativePath = path2.relative(outDir, fullPath);
|
|
61
|
+
let routePath = "/" + path2.dirname(relativePath).replace(/\\/g, "/");
|
|
62
|
+
if (routePath === "/.") {
|
|
63
|
+
routePath = "/";
|
|
64
|
+
}
|
|
65
|
+
routes.push({
|
|
66
|
+
path: routePath,
|
|
67
|
+
htmlPath: fullPath
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
await scanDirectory(outDir);
|
|
73
|
+
return routes;
|
|
74
|
+
}
|
|
75
|
+
async function collectRoutes(outDir, excludePatterns) {
|
|
76
|
+
const allRoutes = await discoverHtmlFiles(outDir);
|
|
77
|
+
const filteredRoutes = filterRoutes(allRoutes, excludePatterns);
|
|
78
|
+
const uniqueRoutes = /* @__PURE__ */ new Map();
|
|
79
|
+
for (const route of filteredRoutes) {
|
|
80
|
+
if (!uniqueRoutes.has(route.path)) {
|
|
81
|
+
uniqueRoutes.set(route.path, route);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return Array.from(uniqueRoutes.values());
|
|
85
|
+
}
|
|
86
|
+
function parseHtml(html) {
|
|
87
|
+
const processor = unified().use(rehypeParse);
|
|
88
|
+
return processor.parse(html);
|
|
89
|
+
}
|
|
90
|
+
async function parseHtmlFile(filePath) {
|
|
91
|
+
const html = await fs3.readFile(filePath, "utf-8");
|
|
92
|
+
return parseHtml(html);
|
|
93
|
+
}
|
|
94
|
+
function extractTitle(tree) {
|
|
95
|
+
const h1Element = select("h1", tree);
|
|
96
|
+
if (h1Element) {
|
|
97
|
+
return toString(h1Element).trim();
|
|
98
|
+
}
|
|
99
|
+
const titleElement = select("title", tree);
|
|
100
|
+
if (titleElement) {
|
|
101
|
+
return toString(titleElement).trim();
|
|
102
|
+
}
|
|
103
|
+
return "Untitled";
|
|
104
|
+
}
|
|
105
|
+
function extractDescription(tree) {
|
|
106
|
+
const metaDescription = select('meta[name="description"]', tree);
|
|
107
|
+
if (metaDescription && metaDescription.properties?.content) {
|
|
108
|
+
return String(metaDescription.properties.content);
|
|
109
|
+
}
|
|
110
|
+
const ogDescription = select('meta[property="og:description"]', tree);
|
|
111
|
+
if (ogDescription && ogDescription.properties?.content) {
|
|
112
|
+
return String(ogDescription.properties.content);
|
|
113
|
+
}
|
|
114
|
+
return "";
|
|
115
|
+
}
|
|
116
|
+
function findContentElement(tree, selectors) {
|
|
117
|
+
for (const selector of selectors) {
|
|
118
|
+
const element = select(selector, tree);
|
|
119
|
+
if (element) {
|
|
120
|
+
const text = toString(element).trim();
|
|
121
|
+
if (text.length > 50) {
|
|
122
|
+
return element;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
var ALWAYS_EXCLUDED = ["script", "style", "noscript"];
|
|
129
|
+
function cleanContentElement(element, excludeSelectors) {
|
|
130
|
+
const allSelectors = [...ALWAYS_EXCLUDED, ...excludeSelectors];
|
|
131
|
+
const cloned = JSON.parse(JSON.stringify(element));
|
|
132
|
+
function removeUnwanted(node) {
|
|
133
|
+
if (!node.children) return;
|
|
134
|
+
node.children = node.children.filter((child) => {
|
|
135
|
+
if (child.type !== "element") return true;
|
|
136
|
+
const childElement = child;
|
|
137
|
+
for (const selector of allSelectors) {
|
|
138
|
+
if (selector.startsWith(".")) {
|
|
139
|
+
const className = selector.slice(1);
|
|
140
|
+
const classes = childElement.properties?.className;
|
|
141
|
+
if (Array.isArray(classes) && classes.includes(className)) {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
if (typeof classes === "string" && classes.includes(className)) {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
} else if (selector.startsWith("[")) {
|
|
148
|
+
const match = selector.match(/\[([^=]+)="([^"]+)"\]/);
|
|
149
|
+
if (match) {
|
|
150
|
+
const [, attr, value] = match;
|
|
151
|
+
if (attr && childElement.properties?.[attr] === value) {
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
} else {
|
|
156
|
+
if (childElement.tagName === selector) {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
removeUnwanted(childElement);
|
|
162
|
+
return true;
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
removeUnwanted(cloned);
|
|
166
|
+
return cloned;
|
|
167
|
+
}
|
|
168
|
+
async function extractContent(filePath, options) {
|
|
169
|
+
const tree = await parseHtmlFile(filePath);
|
|
170
|
+
const title = extractTitle(tree);
|
|
171
|
+
const description = extractDescription(tree);
|
|
172
|
+
let contentElement = findContentElement(tree, options.contentSelectors);
|
|
173
|
+
if (!contentElement) {
|
|
174
|
+
const body = select("body", tree);
|
|
175
|
+
if (body) {
|
|
176
|
+
contentElement = body;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
let contentHtml = "";
|
|
180
|
+
if (contentElement) {
|
|
181
|
+
const cleanedElement = cleanContentElement(contentElement, options.excludeSelectors);
|
|
182
|
+
contentHtml = serializeElement(cleanedElement);
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
title,
|
|
186
|
+
description,
|
|
187
|
+
contentHtml
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function serializeElement(element) {
|
|
191
|
+
const voidElements = /* @__PURE__ */ new Set([
|
|
192
|
+
"area",
|
|
193
|
+
"base",
|
|
194
|
+
"br",
|
|
195
|
+
"col",
|
|
196
|
+
"embed",
|
|
197
|
+
"hr",
|
|
198
|
+
"img",
|
|
199
|
+
"input",
|
|
200
|
+
"link",
|
|
201
|
+
"meta",
|
|
202
|
+
"param",
|
|
203
|
+
"source",
|
|
204
|
+
"track",
|
|
205
|
+
"wbr"
|
|
206
|
+
]);
|
|
207
|
+
function serialize(node) {
|
|
208
|
+
if (!node || typeof node !== "object") return "";
|
|
209
|
+
const n = node;
|
|
210
|
+
if (n.type === "text") {
|
|
211
|
+
return n.value ?? "";
|
|
212
|
+
}
|
|
213
|
+
if (n.type === "element" && n.tagName) {
|
|
214
|
+
const tagName = n.tagName;
|
|
215
|
+
const props = n.properties ?? {};
|
|
216
|
+
const attrs = [];
|
|
217
|
+
for (const [key, value] of Object.entries(props)) {
|
|
218
|
+
if (key === "className" && Array.isArray(value)) {
|
|
219
|
+
attrs.push(`class="${value.join(" ")}"`);
|
|
220
|
+
} else if (typeof value === "boolean") {
|
|
221
|
+
if (value) attrs.push(key);
|
|
222
|
+
} else if (value !== void 0 && value !== null) {
|
|
223
|
+
attrs.push(`${key}="${String(value)}"`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
|
|
227
|
+
if (voidElements.has(tagName)) {
|
|
228
|
+
return `<${tagName}${attrStr} />`;
|
|
229
|
+
}
|
|
230
|
+
const children = n.children ?? [];
|
|
231
|
+
const childrenHtml = children.map(serialize).join("");
|
|
232
|
+
return `<${tagName}${attrStr}>${childrenHtml}</${tagName}>`;
|
|
233
|
+
}
|
|
234
|
+
if (n.type === "root" && n.children) {
|
|
235
|
+
return n.children.map(serialize).join("");
|
|
236
|
+
}
|
|
237
|
+
return "";
|
|
238
|
+
}
|
|
239
|
+
return serialize(element);
|
|
240
|
+
}
|
|
241
|
+
async function htmlToMarkdown(html) {
|
|
242
|
+
if (!html || html.trim().length === 0) {
|
|
243
|
+
return "";
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
const processor = unified().use(rehypeParse, { fragment: true }).use(rehypeRemark).use(remarkGfm).use(remarkStringify, {
|
|
247
|
+
bullet: "-",
|
|
248
|
+
fences: true
|
|
249
|
+
});
|
|
250
|
+
const result = await processor.process(html);
|
|
251
|
+
let markdown = String(result);
|
|
252
|
+
markdown = cleanMarkdown(markdown);
|
|
253
|
+
return markdown;
|
|
254
|
+
} catch (error) {
|
|
255
|
+
console.error("Error converting HTML to Markdown:", error);
|
|
256
|
+
return extractTextFallback(html);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function cleanMarkdown(markdown) {
|
|
260
|
+
return markdown.replace(/\n{3,}/g, "\n\n").split("\n").map((line) => line.trimEnd()).join("\n").trim() + "\n";
|
|
261
|
+
}
|
|
262
|
+
function extractTextFallback(html) {
|
|
263
|
+
let text = html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "");
|
|
264
|
+
text = text.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
|
|
265
|
+
text = text.replace(/<br\s*\/?>/gi, "\n");
|
|
266
|
+
text = text.replace(/<\/p>/gi, "\n\n");
|
|
267
|
+
text = text.replace(/<\/h[1-6]>/gi, "\n\n");
|
|
268
|
+
text = text.replace(/<\/li>/gi, "\n");
|
|
269
|
+
text = text.replace(/<\/div>/gi, "\n");
|
|
270
|
+
text = text.replace(/<[^>]+>/g, "");
|
|
271
|
+
text = text.replace(/ /g, " ");
|
|
272
|
+
text = text.replace(/&/g, "&");
|
|
273
|
+
text = text.replace(/</g, "<");
|
|
274
|
+
text = text.replace(/>/g, ">");
|
|
275
|
+
text = text.replace(/"/g, '"');
|
|
276
|
+
text = text.replace(/'/g, "'");
|
|
277
|
+
text = text.replace(/[ \t]+/g, " ");
|
|
278
|
+
text = text.replace(/\n{3,}/g, "\n\n");
|
|
279
|
+
return text.trim();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/processing/heading-extractor.ts
|
|
283
|
+
function extractHeadingsFromMarkdown(markdown) {
|
|
284
|
+
const headings = [];
|
|
285
|
+
const lines = markdown.split("\n");
|
|
286
|
+
let currentOffset = 0;
|
|
287
|
+
for (let i = 0; i < lines.length; i++) {
|
|
288
|
+
const line = lines[i] ?? "";
|
|
289
|
+
const headingMatch = line.match(/^(#{1,6})\s+(.+?)(?:\s+\{#([^}]+)\})?$/);
|
|
290
|
+
if (headingMatch) {
|
|
291
|
+
const hashes = headingMatch[1] ?? "";
|
|
292
|
+
const level = hashes.length;
|
|
293
|
+
let text = headingMatch[2] ?? "";
|
|
294
|
+
let id = headingMatch[3] ?? "";
|
|
295
|
+
if (!id) {
|
|
296
|
+
id = generateHeadingId(text);
|
|
297
|
+
}
|
|
298
|
+
text = text.replace(/\*\*([^*]+)\*\*/g, "$1");
|
|
299
|
+
text = text.replace(/_([^_]+)_/g, "$1");
|
|
300
|
+
text = text.replace(/`([^`]+)`/g, "$1");
|
|
301
|
+
headings.push({
|
|
302
|
+
level,
|
|
303
|
+
text: text.trim(),
|
|
304
|
+
id,
|
|
305
|
+
startOffset: currentOffset,
|
|
306
|
+
endOffset: -1
|
|
307
|
+
// Will be calculated below
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
currentOffset += line.length + 1;
|
|
311
|
+
}
|
|
312
|
+
for (let i = 0; i < headings.length; i++) {
|
|
313
|
+
const current = headings[i];
|
|
314
|
+
if (!current) continue;
|
|
315
|
+
let endOffset = markdown.length;
|
|
316
|
+
for (let j = i + 1; j < headings.length; j++) {
|
|
317
|
+
const next = headings[j];
|
|
318
|
+
if (next && next.level <= current.level) {
|
|
319
|
+
endOffset = next.startOffset;
|
|
320
|
+
break;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
current.endOffset = endOffset;
|
|
324
|
+
}
|
|
325
|
+
return headings;
|
|
326
|
+
}
|
|
327
|
+
function generateHeadingId(text) {
|
|
328
|
+
return text.toLowerCase().replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
|
|
329
|
+
}
|
|
330
|
+
function extractSection(markdown, headingId, headings) {
|
|
331
|
+
const heading = headings.find((h) => h.id === headingId);
|
|
332
|
+
if (!heading) {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
return markdown.slice(heading.startOffset, heading.endOffset).trim();
|
|
336
|
+
}
|
|
337
|
+
var FIELD_WEIGHTS = {
|
|
338
|
+
title: 3,
|
|
339
|
+
headings: 2,
|
|
340
|
+
description: 1.5,
|
|
341
|
+
content: 1
|
|
342
|
+
};
|
|
343
|
+
function englishStemmer(word) {
|
|
344
|
+
if (word.length <= 3) return word;
|
|
345
|
+
return word.replace(/ing$/, "").replace(/tion$/, "t").replace(/sion$/, "s").replace(/([^aeiou])ed$/, "$1").replace(/([^aeiou])es$/, "$1").replace(/ly$/, "").replace(/ment$/, "").replace(/ness$/, "").replace(/ies$/, "y").replace(/([^s])s$/, "$1");
|
|
346
|
+
}
|
|
347
|
+
function createSearchIndex() {
|
|
348
|
+
return new FlexSearch.Document({
|
|
349
|
+
// Use 'full' tokenization for substring matching
|
|
350
|
+
// This allows "auth" to match "authentication"
|
|
351
|
+
tokenize: "full",
|
|
352
|
+
// Enable caching for faster repeated queries
|
|
353
|
+
cache: 100,
|
|
354
|
+
// Higher resolution = more granular ranking (1-9)
|
|
355
|
+
resolution: 9,
|
|
356
|
+
// Enable context for phrase/proximity matching
|
|
357
|
+
context: {
|
|
358
|
+
resolution: 2,
|
|
359
|
+
depth: 2,
|
|
360
|
+
bidirectional: true
|
|
361
|
+
},
|
|
362
|
+
// Apply stemming to normalize word forms
|
|
363
|
+
encode: (str) => {
|
|
364
|
+
const words = str.toLowerCase().split(/[\s\-_.,;:!?'"()[\]{}]+/);
|
|
365
|
+
return words.filter(Boolean).map(englishStemmer);
|
|
366
|
+
},
|
|
367
|
+
// Document schema
|
|
368
|
+
document: {
|
|
369
|
+
id: "id",
|
|
370
|
+
// Index these fields for searching
|
|
371
|
+
index: ["title", "content", "headings", "description"],
|
|
372
|
+
// Store these fields in results (for enriched queries)
|
|
373
|
+
store: ["title", "description"]
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
function addDocumentToIndex(index, doc) {
|
|
378
|
+
const indexable = {
|
|
379
|
+
id: doc.route,
|
|
380
|
+
title: doc.title,
|
|
381
|
+
content: doc.markdown,
|
|
382
|
+
headings: doc.headings.map((h) => h.text).join(" "),
|
|
383
|
+
description: doc.description
|
|
384
|
+
};
|
|
385
|
+
index.add(indexable);
|
|
386
|
+
}
|
|
387
|
+
function buildSearchIndex(docs) {
|
|
388
|
+
const index = createSearchIndex();
|
|
389
|
+
for (const doc of docs) {
|
|
390
|
+
addDocumentToIndex(index, doc);
|
|
391
|
+
}
|
|
392
|
+
return index;
|
|
393
|
+
}
|
|
394
|
+
function searchIndex(index, docs, query, options = {}) {
|
|
395
|
+
const { limit = 5 } = options;
|
|
396
|
+
const rawResults = index.search(query, {
|
|
397
|
+
limit: limit * 3,
|
|
398
|
+
// Get extra results for better ranking after weighting
|
|
399
|
+
enrich: true
|
|
400
|
+
});
|
|
401
|
+
const docScores = /* @__PURE__ */ new Map();
|
|
402
|
+
for (const fieldResult of rawResults) {
|
|
403
|
+
const field = fieldResult.field;
|
|
404
|
+
const fieldWeight = FIELD_WEIGHTS[field] ?? 1;
|
|
405
|
+
const results2 = fieldResult.result;
|
|
406
|
+
for (let i = 0; i < results2.length; i++) {
|
|
407
|
+
const item = results2[i];
|
|
408
|
+
if (!item) continue;
|
|
409
|
+
const docId = typeof item === "string" ? item : item.id;
|
|
410
|
+
const positionScore = (results2.length - i) / results2.length;
|
|
411
|
+
const weightedScore = positionScore * fieldWeight;
|
|
412
|
+
const existingScore = docScores.get(docId) ?? 0;
|
|
413
|
+
docScores.set(docId, existingScore + weightedScore);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
const results = [];
|
|
417
|
+
for (const [docId, score] of docScores) {
|
|
418
|
+
const doc = docs[docId];
|
|
419
|
+
if (!doc) continue;
|
|
420
|
+
results.push({
|
|
421
|
+
route: doc.route,
|
|
422
|
+
title: doc.title,
|
|
423
|
+
score,
|
|
424
|
+
snippet: generateSnippet(doc.markdown, query),
|
|
425
|
+
matchingHeadings: findMatchingHeadings(doc, query)
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
results.sort((a, b) => b.score - a.score);
|
|
429
|
+
return results.slice(0, limit);
|
|
430
|
+
}
|
|
431
|
+
function generateSnippet(markdown, query) {
|
|
432
|
+
const maxLength = 200;
|
|
433
|
+
const queryTerms = query.toLowerCase().split(/\s+/).filter(Boolean);
|
|
434
|
+
if (queryTerms.length === 0) {
|
|
435
|
+
return markdown.slice(0, maxLength) + (markdown.length > maxLength ? "..." : "");
|
|
436
|
+
}
|
|
437
|
+
const lowerMarkdown = markdown.toLowerCase();
|
|
438
|
+
let bestIndex = -1;
|
|
439
|
+
let bestTerm = "";
|
|
440
|
+
const allTerms = [...queryTerms, ...queryTerms.map(englishStemmer)];
|
|
441
|
+
for (const term of allTerms) {
|
|
442
|
+
const index = lowerMarkdown.indexOf(term);
|
|
443
|
+
if (index !== -1 && (bestIndex === -1 || index < bestIndex)) {
|
|
444
|
+
bestIndex = index;
|
|
445
|
+
bestTerm = term;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
if (bestIndex === -1) {
|
|
449
|
+
return markdown.slice(0, maxLength) + (markdown.length > maxLength ? "..." : "");
|
|
450
|
+
}
|
|
451
|
+
const snippetStart = Math.max(0, bestIndex - 50);
|
|
452
|
+
const snippetEnd = Math.min(markdown.length, bestIndex + bestTerm.length + 150);
|
|
453
|
+
let snippet = markdown.slice(snippetStart, snippetEnd);
|
|
454
|
+
snippet = snippet.replace(/^#{1,6}\s+/gm, "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/!\[([^\]]*)\]\([^)]+\)/g, "").replace(/```[a-z]*\n?/g, "").replace(/`([^`]+)`/g, "$1").replace(/\s+/g, " ").trim();
|
|
455
|
+
const prefix = snippetStart > 0 ? "..." : "";
|
|
456
|
+
const suffix = snippetEnd < markdown.length ? "..." : "";
|
|
457
|
+
return prefix + snippet + suffix;
|
|
458
|
+
}
|
|
459
|
+
function findMatchingHeadings(doc, query) {
|
|
460
|
+
const queryTerms = query.toLowerCase().split(/\s+/).filter(Boolean);
|
|
461
|
+
const allTerms = [...queryTerms, ...queryTerms.map(englishStemmer)];
|
|
462
|
+
const matching = [];
|
|
463
|
+
for (const heading of doc.headings) {
|
|
464
|
+
const headingLower = heading.text.toLowerCase();
|
|
465
|
+
const headingStemmed = headingLower.split(/\s+/).map(englishStemmer).join(" ");
|
|
466
|
+
if (allTerms.some(
|
|
467
|
+
(term) => headingLower.includes(term) || headingStemmed.includes(englishStemmer(term))
|
|
468
|
+
)) {
|
|
469
|
+
matching.push(heading.text);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
return matching.slice(0, 3);
|
|
473
|
+
}
|
|
474
|
+
async function exportSearchIndex(index) {
|
|
475
|
+
const exportData = {};
|
|
476
|
+
await index.export((key, data) => {
|
|
477
|
+
exportData[key] = data;
|
|
478
|
+
});
|
|
479
|
+
return exportData;
|
|
480
|
+
}
|
|
481
|
+
async function importSearchIndex(data) {
|
|
482
|
+
const index = createSearchIndex();
|
|
483
|
+
for (const [key, value] of Object.entries(data)) {
|
|
484
|
+
await index.import(
|
|
485
|
+
key,
|
|
486
|
+
value
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
return index;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// src/plugin/docusaurus-plugin.ts
|
|
493
|
+
function resolveOptions(options) {
|
|
494
|
+
return {
|
|
495
|
+
...DEFAULT_OPTIONS,
|
|
496
|
+
...options,
|
|
497
|
+
server: {
|
|
498
|
+
...DEFAULT_OPTIONS.server,
|
|
499
|
+
...options.server
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
async function processHtmlFile(htmlPath, route, options) {
|
|
504
|
+
try {
|
|
505
|
+
const extractOptions = {
|
|
506
|
+
contentSelectors: options.contentSelectors,
|
|
507
|
+
excludeSelectors: options.excludeSelectors
|
|
508
|
+
};
|
|
509
|
+
const extracted = await extractContent(htmlPath, extractOptions);
|
|
510
|
+
if (!extracted.contentHtml) {
|
|
511
|
+
console.warn(`[MCP] No content found in ${htmlPath}`);
|
|
512
|
+
return null;
|
|
513
|
+
}
|
|
514
|
+
const markdown = await htmlToMarkdown(extracted.contentHtml);
|
|
515
|
+
if (!markdown || markdown.trim().length < options.minContentLength) {
|
|
516
|
+
console.warn(`[MCP] Insufficient content in ${htmlPath}`);
|
|
517
|
+
return null;
|
|
518
|
+
}
|
|
519
|
+
const headings = extractHeadingsFromMarkdown(markdown);
|
|
520
|
+
return {
|
|
521
|
+
route,
|
|
522
|
+
title: extracted.title,
|
|
523
|
+
description: extracted.description,
|
|
524
|
+
markdown,
|
|
525
|
+
headings
|
|
526
|
+
};
|
|
527
|
+
} catch (error) {
|
|
528
|
+
console.error(`[MCP] Error processing ${htmlPath}:`, error);
|
|
529
|
+
return null;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
function mcpServerPlugin(context, options) {
|
|
533
|
+
const resolvedOptions = resolveOptions(options);
|
|
534
|
+
return {
|
|
535
|
+
name: "docusaurus-plugin-mcp-server",
|
|
536
|
+
// Expose configuration to theme components via globalData
|
|
537
|
+
async contentLoaded({ actions }) {
|
|
538
|
+
const { setGlobalData } = actions;
|
|
539
|
+
const serverUrl = `${context.siteConfig.url}/${resolvedOptions.outputDir}`;
|
|
540
|
+
setGlobalData({
|
|
541
|
+
serverUrl,
|
|
542
|
+
serverName: resolvedOptions.server.name
|
|
543
|
+
});
|
|
544
|
+
},
|
|
545
|
+
async postBuild({ outDir }) {
|
|
546
|
+
console.log("[MCP] Starting MCP artifact generation...");
|
|
547
|
+
const startTime = Date.now();
|
|
548
|
+
const routes = await collectRoutes(outDir, resolvedOptions.excludeRoutes);
|
|
549
|
+
console.log(`[MCP] Found ${routes.length} routes to process`);
|
|
550
|
+
if (routes.length === 0) {
|
|
551
|
+
console.warn("[MCP] No routes found to process");
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
const processOptions = {
|
|
555
|
+
contentSelectors: resolvedOptions.contentSelectors,
|
|
556
|
+
excludeSelectors: resolvedOptions.excludeSelectors,
|
|
557
|
+
minContentLength: resolvedOptions.minContentLength
|
|
558
|
+
};
|
|
559
|
+
const processedDocs = await pMap(
|
|
560
|
+
routes,
|
|
561
|
+
async (route) => {
|
|
562
|
+
return processHtmlFile(route.htmlPath, route.path, processOptions);
|
|
563
|
+
},
|
|
564
|
+
{ concurrency: 10 }
|
|
565
|
+
);
|
|
566
|
+
const validDocs = processedDocs.filter((doc) => doc !== null);
|
|
567
|
+
console.log(`[MCP] Successfully processed ${validDocs.length} documents`);
|
|
568
|
+
if (validDocs.length === 0) {
|
|
569
|
+
console.warn("[MCP] No valid documents to index");
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
const docsIndex = {};
|
|
573
|
+
for (const doc of validDocs) {
|
|
574
|
+
docsIndex[doc.route] = doc;
|
|
575
|
+
}
|
|
576
|
+
console.log("[MCP] Building search index...");
|
|
577
|
+
const searchIndex2 = buildSearchIndex(validDocs);
|
|
578
|
+
const exportedIndex = await exportSearchIndex(searchIndex2);
|
|
579
|
+
const manifest = {
|
|
580
|
+
version: resolvedOptions.server.version,
|
|
581
|
+
buildTime: (/* @__PURE__ */ new Date()).toISOString(),
|
|
582
|
+
docCount: validDocs.length,
|
|
583
|
+
serverName: resolvedOptions.server.name,
|
|
584
|
+
baseUrl: context.siteConfig.url
|
|
585
|
+
};
|
|
586
|
+
const mcpOutputDir = path2.join(outDir, resolvedOptions.outputDir);
|
|
587
|
+
await fs3.ensureDir(mcpOutputDir);
|
|
588
|
+
await Promise.all([
|
|
589
|
+
fs3.writeJson(path2.join(mcpOutputDir, "docs.json"), docsIndex, { spaces: 0 }),
|
|
590
|
+
fs3.writeJson(path2.join(mcpOutputDir, "search-index.json"), exportedIndex, { spaces: 0 }),
|
|
591
|
+
fs3.writeJson(path2.join(mcpOutputDir, "manifest.json"), manifest, { spaces: 2 })
|
|
592
|
+
]);
|
|
593
|
+
const elapsed = Date.now() - startTime;
|
|
594
|
+
console.log(`[MCP] Artifacts written to ${mcpOutputDir}`);
|
|
595
|
+
console.log(`[MCP] Generation complete in ${elapsed}ms`);
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// src/mcp/tools/docs-search.ts
|
|
601
|
+
var docsSearchTool = {
|
|
602
|
+
name: "docs_search",
|
|
603
|
+
description: "Search across developer documentation. Returns ranked results with snippets and matching headings.",
|
|
604
|
+
inputSchema: {
|
|
605
|
+
type: "object",
|
|
606
|
+
properties: {
|
|
607
|
+
query: {
|
|
608
|
+
type: "string",
|
|
609
|
+
description: "Search query string"
|
|
610
|
+
},
|
|
611
|
+
limit: {
|
|
612
|
+
type: "number",
|
|
613
|
+
description: "Maximum number of results to return (default: 5, max: 20)",
|
|
614
|
+
default: 5
|
|
615
|
+
}
|
|
616
|
+
},
|
|
617
|
+
required: ["query"]
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
function executeDocsSearch(params, index, docs) {
|
|
621
|
+
const { query, limit = 5 } = params;
|
|
622
|
+
if (!query || typeof query !== "string" || query.trim().length === 0) {
|
|
623
|
+
throw new Error("Query parameter is required and must be a non-empty string");
|
|
624
|
+
}
|
|
625
|
+
const effectiveLimit = Math.min(Math.max(1, limit), 20);
|
|
626
|
+
const results = searchIndex(index, docs, query.trim(), {
|
|
627
|
+
limit: effectiveLimit
|
|
628
|
+
});
|
|
629
|
+
return results;
|
|
630
|
+
}
|
|
631
|
+
function formatSearchResults(results, baseUrl) {
|
|
632
|
+
if (results.length === 0) {
|
|
633
|
+
return "No matching documents found.";
|
|
634
|
+
}
|
|
635
|
+
const lines = [`Found ${results.length} result(s):
|
|
636
|
+
`];
|
|
637
|
+
for (let i = 0; i < results.length; i++) {
|
|
638
|
+
const result = results[i];
|
|
639
|
+
if (!result) continue;
|
|
640
|
+
lines.push(`${i + 1}. **${result.title}**`);
|
|
641
|
+
if (baseUrl) {
|
|
642
|
+
const fullUrl = `${baseUrl.replace(/\/$/, "")}${result.route}`;
|
|
643
|
+
lines.push(` URL: ${fullUrl}`);
|
|
644
|
+
}
|
|
645
|
+
lines.push(` Route: ${result.route}`);
|
|
646
|
+
if (result.matchingHeadings && result.matchingHeadings.length > 0) {
|
|
647
|
+
lines.push(` Matching sections: ${result.matchingHeadings.join(", ")}`);
|
|
648
|
+
}
|
|
649
|
+
lines.push(` ${result.snippet}`);
|
|
650
|
+
lines.push("");
|
|
651
|
+
}
|
|
652
|
+
return lines.join("\n");
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// src/mcp/tools/docs-get-page.ts
|
|
656
|
+
var docsGetPageTool = {
|
|
657
|
+
name: "docs_get_page",
|
|
658
|
+
description: "Retrieve the full content of a documentation page as markdown. Use this after searching to get complete page content.",
|
|
659
|
+
inputSchema: {
|
|
660
|
+
type: "object",
|
|
661
|
+
properties: {
|
|
662
|
+
route: {
|
|
663
|
+
type: "string",
|
|
664
|
+
description: "The route path of the page (e.g., /docs/getting-started)"
|
|
665
|
+
}
|
|
666
|
+
},
|
|
667
|
+
required: ["route"]
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
function executeDocsGetPage(params, docs) {
|
|
671
|
+
const { route } = params;
|
|
672
|
+
if (!route || typeof route !== "string") {
|
|
673
|
+
throw new Error("Route parameter is required and must be a string");
|
|
674
|
+
}
|
|
675
|
+
let normalizedRoute = route.trim();
|
|
676
|
+
if (!normalizedRoute.startsWith("/")) {
|
|
677
|
+
normalizedRoute = "/" + normalizedRoute;
|
|
678
|
+
}
|
|
679
|
+
if (normalizedRoute.length > 1 && normalizedRoute.endsWith("/")) {
|
|
680
|
+
normalizedRoute = normalizedRoute.slice(0, -1);
|
|
681
|
+
}
|
|
682
|
+
const doc = docs[normalizedRoute];
|
|
683
|
+
if (!doc) {
|
|
684
|
+
const altRoute = normalizedRoute.slice(1);
|
|
685
|
+
if (docs[altRoute]) {
|
|
686
|
+
return docs[altRoute] ?? null;
|
|
687
|
+
}
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
690
|
+
return doc;
|
|
691
|
+
}
|
|
692
|
+
function formatPageContent(doc, baseUrl) {
|
|
693
|
+
if (!doc) {
|
|
694
|
+
return "Page not found. Please check the route path and try again.";
|
|
695
|
+
}
|
|
696
|
+
const lines = [];
|
|
697
|
+
lines.push(`# ${doc.title}`);
|
|
698
|
+
lines.push("");
|
|
699
|
+
if (doc.description) {
|
|
700
|
+
lines.push(`> ${doc.description}`);
|
|
701
|
+
lines.push("");
|
|
702
|
+
}
|
|
703
|
+
if (baseUrl) {
|
|
704
|
+
const fullUrl = `${baseUrl.replace(/\/$/, "")}${doc.route}`;
|
|
705
|
+
lines.push(`**URL:** ${fullUrl}`);
|
|
706
|
+
}
|
|
707
|
+
lines.push(`**Route:** ${doc.route}`);
|
|
708
|
+
lines.push("");
|
|
709
|
+
if (doc.headings.length > 0) {
|
|
710
|
+
lines.push("## Contents");
|
|
711
|
+
lines.push("");
|
|
712
|
+
for (const heading of doc.headings) {
|
|
713
|
+
if (heading.level <= 3) {
|
|
714
|
+
const indent = " ".repeat(heading.level - 1);
|
|
715
|
+
lines.push(`${indent}- [${heading.text}](#${heading.id})`);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
lines.push("");
|
|
719
|
+
lines.push("---");
|
|
720
|
+
lines.push("");
|
|
721
|
+
}
|
|
722
|
+
lines.push(doc.markdown);
|
|
723
|
+
return lines.join("\n");
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// src/mcp/tools/docs-get-section.ts
|
|
727
|
+
var docsGetSectionTool = {
|
|
728
|
+
name: "docs_get_section",
|
|
729
|
+
description: "Retrieve a specific section of a documentation page by heading ID. Use this to get focused content from a larger page.",
|
|
730
|
+
inputSchema: {
|
|
731
|
+
type: "object",
|
|
732
|
+
properties: {
|
|
733
|
+
route: {
|
|
734
|
+
type: "string",
|
|
735
|
+
description: "The route path of the page (e.g., /docs/getting-started)"
|
|
736
|
+
},
|
|
737
|
+
headingId: {
|
|
738
|
+
type: "string",
|
|
739
|
+
description: "The ID of the heading to retrieve (e.g., authentication)"
|
|
740
|
+
}
|
|
741
|
+
},
|
|
742
|
+
required: ["route", "headingId"]
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
function executeDocsGetSection(params, docs) {
|
|
746
|
+
const { route, headingId } = params;
|
|
747
|
+
if (!route || typeof route !== "string") {
|
|
748
|
+
throw new Error("Route parameter is required and must be a string");
|
|
749
|
+
}
|
|
750
|
+
if (!headingId || typeof headingId !== "string") {
|
|
751
|
+
throw new Error("HeadingId parameter is required and must be a string");
|
|
752
|
+
}
|
|
753
|
+
let normalizedRoute = route.trim();
|
|
754
|
+
if (!normalizedRoute.startsWith("/")) {
|
|
755
|
+
normalizedRoute = "/" + normalizedRoute;
|
|
756
|
+
}
|
|
757
|
+
if (normalizedRoute.length > 1 && normalizedRoute.endsWith("/")) {
|
|
758
|
+
normalizedRoute = normalizedRoute.slice(0, -1);
|
|
759
|
+
}
|
|
760
|
+
const doc = docs[normalizedRoute];
|
|
761
|
+
if (!doc) {
|
|
762
|
+
return {
|
|
763
|
+
content: null,
|
|
764
|
+
doc: null,
|
|
765
|
+
headingText: null,
|
|
766
|
+
availableHeadings: []
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
const availableHeadings = doc.headings.map((h) => ({
|
|
770
|
+
id: h.id,
|
|
771
|
+
text: h.text,
|
|
772
|
+
level: h.level
|
|
773
|
+
}));
|
|
774
|
+
const heading = doc.headings.find((h) => h.id === headingId.trim());
|
|
775
|
+
if (!heading) {
|
|
776
|
+
return {
|
|
777
|
+
content: null,
|
|
778
|
+
doc,
|
|
779
|
+
headingText: null,
|
|
780
|
+
availableHeadings
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
const content = extractSection(doc.markdown, headingId.trim(), doc.headings);
|
|
784
|
+
return {
|
|
785
|
+
content,
|
|
786
|
+
doc,
|
|
787
|
+
headingText: heading.text,
|
|
788
|
+
availableHeadings
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
function formatSectionContent(result, headingId, baseUrl) {
|
|
792
|
+
if (!result.doc) {
|
|
793
|
+
return "Page not found. Please check the route path and try again.";
|
|
794
|
+
}
|
|
795
|
+
if (!result.content) {
|
|
796
|
+
const lines2 = [`Section "${headingId}" not found in this document.`, "", "Available sections:"];
|
|
797
|
+
for (const heading of result.availableHeadings) {
|
|
798
|
+
const indent = " ".repeat(heading.level - 1);
|
|
799
|
+
lines2.push(`${indent}- ${heading.text} (id: ${heading.id})`);
|
|
800
|
+
}
|
|
801
|
+
return lines2.join("\n");
|
|
802
|
+
}
|
|
803
|
+
const lines = [];
|
|
804
|
+
const fullUrl = baseUrl ? `${baseUrl.replace(/\/$/, "")}${result.doc.route}#${headingId}` : null;
|
|
805
|
+
lines.push(`# ${result.headingText}`);
|
|
806
|
+
if (fullUrl) {
|
|
807
|
+
lines.push(`> From: ${result.doc.title} - ${fullUrl}`);
|
|
808
|
+
} else {
|
|
809
|
+
lines.push(`> From: ${result.doc.title} (${result.doc.route})`);
|
|
810
|
+
}
|
|
811
|
+
lines.push("");
|
|
812
|
+
lines.push("---");
|
|
813
|
+
lines.push("");
|
|
814
|
+
lines.push(result.content);
|
|
815
|
+
return lines.join("\n");
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// src/mcp/server.ts
|
|
819
|
+
function isFileConfig(config) {
|
|
820
|
+
return "docsPath" in config && "indexPath" in config;
|
|
821
|
+
}
|
|
822
|
+
function isDataConfig(config) {
|
|
823
|
+
return "docs" in config && "searchIndexData" in config;
|
|
824
|
+
}
|
|
825
|
+
var McpDocsServer = class {
|
|
826
|
+
config;
|
|
827
|
+
docs = null;
|
|
828
|
+
searchIndex = null;
|
|
829
|
+
mcpServer;
|
|
830
|
+
initialized = false;
|
|
831
|
+
constructor(config) {
|
|
832
|
+
this.config = config;
|
|
833
|
+
this.mcpServer = new McpServer(
|
|
834
|
+
{
|
|
835
|
+
name: config.name,
|
|
836
|
+
version: config.version ?? "1.0.0"
|
|
837
|
+
},
|
|
838
|
+
{
|
|
839
|
+
capabilities: {
|
|
840
|
+
tools: {}
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
);
|
|
844
|
+
this.registerTools();
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Register all MCP tools using the SDK's registerTool API
|
|
848
|
+
*/
|
|
849
|
+
registerTools() {
|
|
850
|
+
this.mcpServer.registerTool(
|
|
851
|
+
"docs_search",
|
|
852
|
+
{
|
|
853
|
+
description: "Search the documentation for relevant pages. Returns matching documents with snippets and relevance scores. Use this to find information across all documentation.",
|
|
854
|
+
inputSchema: {
|
|
855
|
+
query: z.string().min(1).describe("The search query string"),
|
|
856
|
+
limit: z.number().int().min(1).max(20).optional().default(5).describe("Maximum number of results to return (1-20, default: 5)")
|
|
857
|
+
}
|
|
858
|
+
},
|
|
859
|
+
async ({ query, limit }) => {
|
|
860
|
+
await this.initialize();
|
|
861
|
+
if (!this.docs || !this.searchIndex) {
|
|
862
|
+
return {
|
|
863
|
+
content: [{ type: "text", text: "Server not initialized. Please try again." }],
|
|
864
|
+
isError: true
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
const results = executeDocsSearch({ query, limit }, this.searchIndex, this.docs);
|
|
868
|
+
return {
|
|
869
|
+
content: [
|
|
870
|
+
{ type: "text", text: formatSearchResults(results, this.config.baseUrl) }
|
|
871
|
+
]
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
);
|
|
875
|
+
this.mcpServer.registerTool(
|
|
876
|
+
"docs_get_page",
|
|
877
|
+
{
|
|
878
|
+
description: "Retrieve the complete content of a documentation page as markdown. Use this when you need the full content of a specific page.",
|
|
879
|
+
inputSchema: {
|
|
880
|
+
route: z.string().min(1).describe('The page route path (e.g., "/docs/getting-started" or "/api/reference")')
|
|
881
|
+
}
|
|
882
|
+
},
|
|
883
|
+
async ({ route }) => {
|
|
884
|
+
await this.initialize();
|
|
885
|
+
if (!this.docs) {
|
|
886
|
+
return {
|
|
887
|
+
content: [{ type: "text", text: "Server not initialized. Please try again." }],
|
|
888
|
+
isError: true
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
const doc = executeDocsGetPage({ route }, this.docs);
|
|
892
|
+
return {
|
|
893
|
+
content: [{ type: "text", text: formatPageContent(doc, this.config.baseUrl) }]
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
);
|
|
897
|
+
this.mcpServer.registerTool(
|
|
898
|
+
"docs_get_section",
|
|
899
|
+
{
|
|
900
|
+
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.",
|
|
901
|
+
inputSchema: {
|
|
902
|
+
route: z.string().min(1).describe("The page route path"),
|
|
903
|
+
headingId: z.string().min(1).describe(
|
|
904
|
+
'The heading ID of the section to extract (e.g., "installation", "api-reference")'
|
|
905
|
+
)
|
|
906
|
+
}
|
|
907
|
+
},
|
|
908
|
+
async ({ route, headingId }) => {
|
|
909
|
+
await this.initialize();
|
|
910
|
+
if (!this.docs) {
|
|
911
|
+
return {
|
|
912
|
+
content: [{ type: "text", text: "Server not initialized. Please try again." }],
|
|
913
|
+
isError: true
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
const result = executeDocsGetSection({ route, headingId }, this.docs);
|
|
917
|
+
return {
|
|
918
|
+
content: [
|
|
919
|
+
{
|
|
920
|
+
type: "text",
|
|
921
|
+
text: formatSectionContent(result, headingId, this.config.baseUrl)
|
|
922
|
+
}
|
|
923
|
+
]
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
);
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Load docs and search index
|
|
930
|
+
*
|
|
931
|
+
* For file-based config: reads from disk
|
|
932
|
+
* For data config: uses pre-loaded data directly
|
|
933
|
+
*/
|
|
934
|
+
async initialize() {
|
|
935
|
+
if (this.initialized) {
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
try {
|
|
939
|
+
if (isDataConfig(this.config)) {
|
|
940
|
+
this.docs = this.config.docs;
|
|
941
|
+
this.searchIndex = await importSearchIndex(this.config.searchIndexData);
|
|
942
|
+
} else if (isFileConfig(this.config)) {
|
|
943
|
+
if (await fs3.pathExists(this.config.docsPath)) {
|
|
944
|
+
this.docs = await fs3.readJson(this.config.docsPath);
|
|
945
|
+
} else {
|
|
946
|
+
throw new Error(`Docs file not found: ${this.config.docsPath}`);
|
|
947
|
+
}
|
|
948
|
+
if (await fs3.pathExists(this.config.indexPath)) {
|
|
949
|
+
const indexData = await fs3.readJson(this.config.indexPath);
|
|
950
|
+
this.searchIndex = await importSearchIndex(indexData);
|
|
951
|
+
} else {
|
|
952
|
+
throw new Error(`Search index not found: ${this.config.indexPath}`);
|
|
953
|
+
}
|
|
954
|
+
} else {
|
|
955
|
+
throw new Error("Invalid server config: must provide either file paths or pre-loaded data");
|
|
956
|
+
}
|
|
957
|
+
this.initialized = true;
|
|
958
|
+
} catch (error) {
|
|
959
|
+
console.error("[MCP] Failed to initialize:", error);
|
|
960
|
+
throw error;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
/**
|
|
964
|
+
* Handle an HTTP request using the MCP SDK's transport
|
|
965
|
+
*
|
|
966
|
+
* This method is designed for serverless environments (Vercel, Netlify).
|
|
967
|
+
* It creates a stateless transport instance and processes the request.
|
|
968
|
+
*
|
|
969
|
+
* @param req - Node.js IncomingMessage or compatible request object
|
|
970
|
+
* @param res - Node.js ServerResponse or compatible response object
|
|
971
|
+
* @param parsedBody - Optional pre-parsed request body
|
|
972
|
+
*/
|
|
973
|
+
async handleHttpRequest(req, res, parsedBody) {
|
|
974
|
+
await this.initialize();
|
|
975
|
+
const transport = new StreamableHTTPServerTransport({
|
|
976
|
+
sessionIdGenerator: void 0,
|
|
977
|
+
// Stateless mode - no session tracking
|
|
978
|
+
enableJsonResponse: true
|
|
979
|
+
// Return JSON instead of SSE streams
|
|
980
|
+
});
|
|
981
|
+
await this.mcpServer.connect(transport);
|
|
982
|
+
try {
|
|
983
|
+
await transport.handleRequest(req, res, parsedBody);
|
|
984
|
+
} finally {
|
|
985
|
+
await transport.close();
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
/**
|
|
989
|
+
* Handle a Web Standard Request (Cloudflare Workers, Deno, Bun)
|
|
990
|
+
*
|
|
991
|
+
* This method is designed for Web Standard environments that use
|
|
992
|
+
* the Fetch API Request/Response pattern.
|
|
993
|
+
*
|
|
994
|
+
* @param request - Web Standard Request object
|
|
995
|
+
* @returns Web Standard Response object
|
|
996
|
+
*/
|
|
997
|
+
async handleWebRequest(request) {
|
|
998
|
+
await this.initialize();
|
|
999
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
1000
|
+
sessionIdGenerator: void 0,
|
|
1001
|
+
// Stateless mode
|
|
1002
|
+
enableJsonResponse: true
|
|
1003
|
+
});
|
|
1004
|
+
await this.mcpServer.connect(transport);
|
|
1005
|
+
try {
|
|
1006
|
+
return await transport.handleRequest(request);
|
|
1007
|
+
} finally {
|
|
1008
|
+
await transport.close();
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* Get server status information
|
|
1013
|
+
*
|
|
1014
|
+
* Useful for health checks and debugging
|
|
1015
|
+
*/
|
|
1016
|
+
async getStatus() {
|
|
1017
|
+
return {
|
|
1018
|
+
name: this.config.name,
|
|
1019
|
+
version: this.config.version ?? "1.0.0",
|
|
1020
|
+
initialized: this.initialized,
|
|
1021
|
+
docCount: this.docs ? Object.keys(this.docs).length : 0,
|
|
1022
|
+
baseUrl: this.config.baseUrl
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
/**
|
|
1026
|
+
* Get the underlying McpServer instance
|
|
1027
|
+
*
|
|
1028
|
+
* Useful for advanced use cases like custom transports
|
|
1029
|
+
*/
|
|
1030
|
+
getMcpServer() {
|
|
1031
|
+
return this.mcpServer;
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
export { DEFAULT_OPTIONS, McpDocsServer, buildSearchIndex, collectRoutes, mcpServerPlugin as default, discoverHtmlFiles, docsGetPageTool, docsGetSectionTool, docsSearchTool, exportSearchIndex, extractContent, extractHeadingsFromMarkdown, extractSection, htmlToMarkdown, importSearchIndex, mcpServerPlugin, parseHtml, parseHtmlFile, searchIndex };
|
|
1036
|
+
//# sourceMappingURL=index.mjs.map
|
|
1037
|
+
//# sourceMappingURL=index.mjs.map
|