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.
@@ -0,0 +1,908 @@
1
+ import fs from 'fs-extra';
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
4
+ import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
5
+ import { z } from 'zod';
6
+ import FlexSearch from 'flexsearch';
7
+
8
+ // src/mcp/server.ts
9
+ var FIELD_WEIGHTS = {
10
+ title: 3,
11
+ headings: 2,
12
+ description: 1.5,
13
+ content: 1
14
+ };
15
+ function englishStemmer(word) {
16
+ if (word.length <= 3) return word;
17
+ 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");
18
+ }
19
+ function createSearchIndex() {
20
+ return new FlexSearch.Document({
21
+ // Use 'full' tokenization for substring matching
22
+ // This allows "auth" to match "authentication"
23
+ tokenize: "full",
24
+ // Enable caching for faster repeated queries
25
+ cache: 100,
26
+ // Higher resolution = more granular ranking (1-9)
27
+ resolution: 9,
28
+ // Enable context for phrase/proximity matching
29
+ context: {
30
+ resolution: 2,
31
+ depth: 2,
32
+ bidirectional: true
33
+ },
34
+ // Apply stemming to normalize word forms
35
+ encode: (str) => {
36
+ const words = str.toLowerCase().split(/[\s\-_.,;:!?'"()[\]{}]+/);
37
+ return words.filter(Boolean).map(englishStemmer);
38
+ },
39
+ // Document schema
40
+ document: {
41
+ id: "id",
42
+ // Index these fields for searching
43
+ index: ["title", "content", "headings", "description"],
44
+ // Store these fields in results (for enriched queries)
45
+ store: ["title", "description"]
46
+ }
47
+ });
48
+ }
49
+ function searchIndex(index, docs, query, options = {}) {
50
+ const { limit = 5 } = options;
51
+ const rawResults = index.search(query, {
52
+ limit: limit * 3,
53
+ // Get extra results for better ranking after weighting
54
+ enrich: true
55
+ });
56
+ const docScores = /* @__PURE__ */ new Map();
57
+ for (const fieldResult of rawResults) {
58
+ const field = fieldResult.field;
59
+ const fieldWeight = FIELD_WEIGHTS[field] ?? 1;
60
+ const results2 = fieldResult.result;
61
+ for (let i = 0; i < results2.length; i++) {
62
+ const item = results2[i];
63
+ if (!item) continue;
64
+ const docId = typeof item === "string" ? item : item.id;
65
+ const positionScore = (results2.length - i) / results2.length;
66
+ const weightedScore = positionScore * fieldWeight;
67
+ const existingScore = docScores.get(docId) ?? 0;
68
+ docScores.set(docId, existingScore + weightedScore);
69
+ }
70
+ }
71
+ const results = [];
72
+ for (const [docId, score] of docScores) {
73
+ const doc = docs[docId];
74
+ if (!doc) continue;
75
+ results.push({
76
+ route: doc.route,
77
+ title: doc.title,
78
+ score,
79
+ snippet: generateSnippet(doc.markdown, query),
80
+ matchingHeadings: findMatchingHeadings(doc, query)
81
+ });
82
+ }
83
+ results.sort((a, b) => b.score - a.score);
84
+ return results.slice(0, limit);
85
+ }
86
+ function generateSnippet(markdown, query) {
87
+ const maxLength = 200;
88
+ const queryTerms = query.toLowerCase().split(/\s+/).filter(Boolean);
89
+ if (queryTerms.length === 0) {
90
+ return markdown.slice(0, maxLength) + (markdown.length > maxLength ? "..." : "");
91
+ }
92
+ const lowerMarkdown = markdown.toLowerCase();
93
+ let bestIndex = -1;
94
+ let bestTerm = "";
95
+ const allTerms = [...queryTerms, ...queryTerms.map(englishStemmer)];
96
+ for (const term of allTerms) {
97
+ const index = lowerMarkdown.indexOf(term);
98
+ if (index !== -1 && (bestIndex === -1 || index < bestIndex)) {
99
+ bestIndex = index;
100
+ bestTerm = term;
101
+ }
102
+ }
103
+ if (bestIndex === -1) {
104
+ return markdown.slice(0, maxLength) + (markdown.length > maxLength ? "..." : "");
105
+ }
106
+ const snippetStart = Math.max(0, bestIndex - 50);
107
+ const snippetEnd = Math.min(markdown.length, bestIndex + bestTerm.length + 150);
108
+ let snippet = markdown.slice(snippetStart, snippetEnd);
109
+ snippet = snippet.replace(/^#{1,6}\s+/gm, "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/!\[([^\]]*)\]\([^)]+\)/g, "").replace(/```[a-z]*\n?/g, "").replace(/`([^`]+)`/g, "$1").replace(/\s+/g, " ").trim();
110
+ const prefix = snippetStart > 0 ? "..." : "";
111
+ const suffix = snippetEnd < markdown.length ? "..." : "";
112
+ return prefix + snippet + suffix;
113
+ }
114
+ function findMatchingHeadings(doc, query) {
115
+ const queryTerms = query.toLowerCase().split(/\s+/).filter(Boolean);
116
+ const allTerms = [...queryTerms, ...queryTerms.map(englishStemmer)];
117
+ const matching = [];
118
+ for (const heading of doc.headings) {
119
+ const headingLower = heading.text.toLowerCase();
120
+ const headingStemmed = headingLower.split(/\s+/).map(englishStemmer).join(" ");
121
+ if (allTerms.some(
122
+ (term) => headingLower.includes(term) || headingStemmed.includes(englishStemmer(term))
123
+ )) {
124
+ matching.push(heading.text);
125
+ }
126
+ }
127
+ return matching.slice(0, 3);
128
+ }
129
+ async function importSearchIndex(data) {
130
+ const index = createSearchIndex();
131
+ for (const [key, value] of Object.entries(data)) {
132
+ await index.import(
133
+ key,
134
+ value
135
+ );
136
+ }
137
+ return index;
138
+ }
139
+
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;
151
+ }
152
+ function formatSearchResults(results, baseUrl) {
153
+ if (results.length === 0) {
154
+ return "No matching documents found.";
155
+ }
156
+ const lines = [`Found ${results.length} result(s):
157
+ `];
158
+ for (let i = 0; i < results.length; i++) {
159
+ const result = results[i];
160
+ if (!result) continue;
161
+ lines.push(`${i + 1}. **${result.title}**`);
162
+ if (baseUrl) {
163
+ const fullUrl = `${baseUrl.replace(/\/$/, "")}${result.route}`;
164
+ lines.push(` URL: ${fullUrl}`);
165
+ }
166
+ lines.push(` Route: ${result.route}`);
167
+ if (result.matchingHeadings && result.matchingHeadings.length > 0) {
168
+ lines.push(` Matching sections: ${result.matchingHeadings.join(", ")}`);
169
+ }
170
+ lines.push(` ${result.snippet}`);
171
+ lines.push("");
172
+ }
173
+ return lines.join("\n");
174
+ }
175
+
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
+ }
199
+ function formatPageContent(doc, baseUrl) {
200
+ if (!doc) {
201
+ return "Page not found. Please check the route path and try again.";
202
+ }
203
+ const lines = [];
204
+ lines.push(`# ${doc.title}`);
205
+ lines.push("");
206
+ if (doc.description) {
207
+ lines.push(`> ${doc.description}`);
208
+ lines.push("");
209
+ }
210
+ if (baseUrl) {
211
+ const fullUrl = `${baseUrl.replace(/\/$/, "")}${doc.route}`;
212
+ lines.push(`**URL:** ${fullUrl}`);
213
+ }
214
+ lines.push(`**Route:** ${doc.route}`);
215
+ lines.push("");
216
+ if (doc.headings.length > 0) {
217
+ lines.push("## Contents");
218
+ lines.push("");
219
+ for (const heading of doc.headings) {
220
+ if (heading.level <= 3) {
221
+ const indent = " ".repeat(heading.level - 1);
222
+ lines.push(`${indent}- [${heading.text}](#${heading.id})`);
223
+ }
224
+ }
225
+ lines.push("");
226
+ lines.push("---");
227
+ lines.push("");
228
+ }
229
+ lines.push(doc.markdown);
230
+ return lines.join("\n");
231
+ }
232
+
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
+ // src/mcp/server.ts
317
+ function isFileConfig(config) {
318
+ return "docsPath" in config && "indexPath" in config;
319
+ }
320
+ function isDataConfig(config) {
321
+ return "docs" in config && "searchIndexData" in config;
322
+ }
323
+ var McpDocsServer = class {
324
+ config;
325
+ docs = null;
326
+ searchIndex = null;
327
+ mcpServer;
328
+ initialized = false;
329
+ constructor(config) {
330
+ this.config = config;
331
+ this.mcpServer = new McpServer(
332
+ {
333
+ name: config.name,
334
+ version: config.version ?? "1.0.0"
335
+ },
336
+ {
337
+ capabilities: {
338
+ tools: {}
339
+ }
340
+ }
341
+ );
342
+ this.registerTools();
343
+ }
344
+ /**
345
+ * Register all MCP tools using the SDK's registerTool API
346
+ */
347
+ registerTools() {
348
+ this.mcpServer.registerTool(
349
+ "docs_search",
350
+ {
351
+ description: "Search the documentation for relevant pages. Returns matching documents with snippets and relevance scores. Use this to find information across all documentation.",
352
+ inputSchema: {
353
+ query: z.string().min(1).describe("The search query string"),
354
+ limit: z.number().int().min(1).max(20).optional().default(5).describe("Maximum number of results to return (1-20, default: 5)")
355
+ }
356
+ },
357
+ async ({ query, limit }) => {
358
+ await this.initialize();
359
+ if (!this.docs || !this.searchIndex) {
360
+ return {
361
+ content: [{ type: "text", text: "Server not initialized. Please try again." }],
362
+ isError: true
363
+ };
364
+ }
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
+ };
371
+ }
372
+ );
373
+ this.mcpServer.registerTool(
374
+ "docs_get_page",
375
+ {
376
+ description: "Retrieve the complete content of a documentation page as markdown. Use this when you need the full content of a specific page.",
377
+ inputSchema: {
378
+ route: z.string().min(1).describe('The page route path (e.g., "/docs/getting-started" or "/api/reference")')
379
+ }
380
+ },
381
+ async ({ route }) => {
382
+ await this.initialize();
383
+ if (!this.docs) {
384
+ return {
385
+ content: [{ type: "text", text: "Server not initialized. Please try again." }],
386
+ isError: true
387
+ };
388
+ }
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) {
409
+ return {
410
+ content: [{ type: "text", text: "Server not initialized. Please try again." }],
411
+ isError: true
412
+ };
413
+ }
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
+ }
424
+ );
425
+ }
426
+ /**
427
+ * Load docs and search index
428
+ *
429
+ * For file-based config: reads from disk
430
+ * For data config: uses pre-loaded data directly
431
+ */
432
+ async initialize() {
433
+ if (this.initialized) {
434
+ return;
435
+ }
436
+ try {
437
+ if (isDataConfig(this.config)) {
438
+ this.docs = this.config.docs;
439
+ this.searchIndex = await importSearchIndex(this.config.searchIndexData);
440
+ } 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
+ }
452
+ } else {
453
+ throw new Error("Invalid server config: must provide either file paths or pre-loaded data");
454
+ }
455
+ this.initialized = true;
456
+ } catch (error) {
457
+ console.error("[MCP] Failed to initialize:", error);
458
+ throw error;
459
+ }
460
+ }
461
+ /**
462
+ * Handle an HTTP request using the MCP SDK's transport
463
+ *
464
+ * This method is designed for serverless environments (Vercel, Netlify).
465
+ * It creates a stateless transport instance and processes the request.
466
+ *
467
+ * @param req - Node.js IncomingMessage or compatible request object
468
+ * @param res - Node.js ServerResponse or compatible response object
469
+ * @param parsedBody - Optional pre-parsed request body
470
+ */
471
+ async handleHttpRequest(req, res, parsedBody) {
472
+ await this.initialize();
473
+ const transport = new StreamableHTTPServerTransport({
474
+ sessionIdGenerator: void 0,
475
+ // Stateless mode - no session tracking
476
+ enableJsonResponse: true
477
+ // Return JSON instead of SSE streams
478
+ });
479
+ await this.mcpServer.connect(transport);
480
+ try {
481
+ await transport.handleRequest(req, res, parsedBody);
482
+ } finally {
483
+ await transport.close();
484
+ }
485
+ }
486
+ /**
487
+ * Handle a Web Standard Request (Cloudflare Workers, Deno, Bun)
488
+ *
489
+ * This method is designed for Web Standard environments that use
490
+ * the Fetch API Request/Response pattern.
491
+ *
492
+ * @param request - Web Standard Request object
493
+ * @returns Web Standard Response object
494
+ */
495
+ async handleWebRequest(request) {
496
+ await this.initialize();
497
+ const transport = new WebStandardStreamableHTTPServerTransport({
498
+ sessionIdGenerator: void 0,
499
+ // Stateless mode
500
+ enableJsonResponse: true
501
+ });
502
+ await this.mcpServer.connect(transport);
503
+ try {
504
+ return await transport.handleRequest(request);
505
+ } finally {
506
+ await transport.close();
507
+ }
508
+ }
509
+ /**
510
+ * Get server status information
511
+ *
512
+ * Useful for health checks and debugging
513
+ */
514
+ async getStatus() {
515
+ return {
516
+ name: this.config.name,
517
+ version: this.config.version ?? "1.0.0",
518
+ initialized: this.initialized,
519
+ docCount: this.docs ? Object.keys(this.docs).length : 0,
520
+ baseUrl: this.config.baseUrl
521
+ };
522
+ }
523
+ /**
524
+ * Get the underlying McpServer instance
525
+ *
526
+ * Useful for advanced use cases like custom transports
527
+ */
528
+ getMcpServer() {
529
+ return this.mcpServer;
530
+ }
531
+ };
532
+
533
+ // src/adapters/vercel.ts
534
+ function createVercelHandler(config) {
535
+ let server = null;
536
+ function getServer() {
537
+ if (!server) {
538
+ server = new McpDocsServer(config);
539
+ }
540
+ return server;
541
+ }
542
+ return async function handler(req, res) {
543
+ if (req.method === "GET") {
544
+ const mcpServer = getServer();
545
+ const status = await mcpServer.getStatus();
546
+ return res.status(200).json(status);
547
+ }
548
+ if (req.method !== "POST") {
549
+ return res.status(405).json({
550
+ jsonrpc: "2.0",
551
+ id: null,
552
+ error: {
553
+ code: -32600,
554
+ message: "Method not allowed. Use POST for MCP requests, GET for status."
555
+ }
556
+ });
557
+ }
558
+ try {
559
+ const mcpServer = getServer();
560
+ await mcpServer.handleHttpRequest(req, res, req.body);
561
+ } catch (error) {
562
+ const errorMessage = error instanceof Error ? error.message : String(error);
563
+ console.error("MCP Server Error:", error);
564
+ return res.status(500).json({
565
+ jsonrpc: "2.0",
566
+ id: null,
567
+ error: {
568
+ code: -32603,
569
+ message: `Internal server error: ${errorMessage}`
570
+ }
571
+ });
572
+ }
573
+ };
574
+ }
575
+
576
+ // src/adapters/netlify.ts
577
+ function eventToRequest(event) {
578
+ const url = event.rawUrl || `https://localhost${event.path || "/"}`;
579
+ const headers = new Headers();
580
+ for (const [key, value] of Object.entries(event.headers)) {
581
+ if (value) {
582
+ headers.set(key, value);
583
+ }
584
+ }
585
+ let body = event.body;
586
+ if (body && event.isBase64Encoded) {
587
+ body = Buffer.from(body, "base64").toString("utf-8");
588
+ }
589
+ return new Request(url, {
590
+ method: event.httpMethod,
591
+ headers,
592
+ body: event.httpMethod !== "GET" && event.httpMethod !== "HEAD" ? body : void 0
593
+ });
594
+ }
595
+ async function responseToNetlify(response) {
596
+ const headers = {};
597
+ response.headers.forEach((value, key) => {
598
+ headers[key] = value;
599
+ });
600
+ const body = await response.text();
601
+ return {
602
+ statusCode: response.status,
603
+ headers,
604
+ body: body || void 0
605
+ };
606
+ }
607
+ function createNetlifyHandler(config) {
608
+ let server = null;
609
+ function getServer() {
610
+ if (!server) {
611
+ server = new McpDocsServer(config);
612
+ }
613
+ return server;
614
+ }
615
+ return async function handler(event, _context) {
616
+ const headers = {
617
+ "Content-Type": "application/json"
618
+ };
619
+ if (event.httpMethod === "GET") {
620
+ const mcpServer = getServer();
621
+ const status = await mcpServer.getStatus();
622
+ return {
623
+ statusCode: 200,
624
+ headers,
625
+ body: JSON.stringify(status)
626
+ };
627
+ }
628
+ if (event.httpMethod !== "POST") {
629
+ return {
630
+ statusCode: 405,
631
+ headers,
632
+ body: JSON.stringify({
633
+ jsonrpc: "2.0",
634
+ id: null,
635
+ error: {
636
+ code: -32600,
637
+ message: "Method not allowed. Use POST for MCP requests, GET for status."
638
+ }
639
+ })
640
+ };
641
+ }
642
+ try {
643
+ const mcpServer = getServer();
644
+ const request = eventToRequest(event);
645
+ const response = await mcpServer.handleWebRequest(request);
646
+ return await responseToNetlify(response);
647
+ } catch (error) {
648
+ const errorMessage = error instanceof Error ? error.message : String(error);
649
+ console.error("MCP Server Error:", error);
650
+ return {
651
+ statusCode: 500,
652
+ headers,
653
+ body: JSON.stringify({
654
+ jsonrpc: "2.0",
655
+ id: null,
656
+ error: {
657
+ code: -32603,
658
+ message: `Internal server error: ${errorMessage}`
659
+ }
660
+ })
661
+ };
662
+ }
663
+ };
664
+ }
665
+
666
+ // src/adapters/cloudflare.ts
667
+ function createCloudflareHandler(config) {
668
+ let server = null;
669
+ const serverConfig = {
670
+ docs: config.docs,
671
+ searchIndexData: config.searchIndexData,
672
+ name: config.name,
673
+ version: config.version,
674
+ baseUrl: config.baseUrl
675
+ };
676
+ function getServer() {
677
+ if (!server) {
678
+ server = new McpDocsServer(serverConfig);
679
+ }
680
+ return server;
681
+ }
682
+ return async function fetch(request) {
683
+ const headers = {
684
+ "Access-Control-Allow-Origin": "*",
685
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
686
+ "Access-Control-Allow-Headers": "Content-Type"
687
+ };
688
+ if (request.method === "OPTIONS") {
689
+ return new Response(null, { status: 204, headers });
690
+ }
691
+ if (request.method === "GET") {
692
+ const mcpServer = getServer();
693
+ const status = await mcpServer.getStatus();
694
+ return new Response(JSON.stringify(status), {
695
+ status: 200,
696
+ headers: { ...headers, "Content-Type": "application/json" }
697
+ });
698
+ }
699
+ if (request.method !== "POST") {
700
+ return new Response(
701
+ JSON.stringify({
702
+ jsonrpc: "2.0",
703
+ id: null,
704
+ error: {
705
+ code: -32600,
706
+ message: "Method not allowed. Use POST for MCP requests, GET for status."
707
+ }
708
+ }),
709
+ {
710
+ status: 405,
711
+ headers: { ...headers, "Content-Type": "application/json" }
712
+ }
713
+ );
714
+ }
715
+ try {
716
+ const mcpServer = getServer();
717
+ const response = await mcpServer.handleWebRequest(request);
718
+ const newHeaders = new Headers(response.headers);
719
+ Object.entries(headers).forEach(([key, value]) => {
720
+ newHeaders.set(key, value);
721
+ });
722
+ return new Response(response.body, {
723
+ status: response.status,
724
+ statusText: response.statusText,
725
+ headers: newHeaders
726
+ });
727
+ } catch (error) {
728
+ const errorMessage = error instanceof Error ? error.message : String(error);
729
+ console.error("MCP Server Error:", error);
730
+ return new Response(
731
+ JSON.stringify({
732
+ jsonrpc: "2.0",
733
+ id: null,
734
+ error: {
735
+ code: -32603,
736
+ message: `Internal server error: ${errorMessage}`
737
+ }
738
+ }),
739
+ {
740
+ status: 500,
741
+ headers: { ...headers, "Content-Type": "application/json" }
742
+ }
743
+ );
744
+ }
745
+ };
746
+ }
747
+
748
+ // src/adapters/generator.ts
749
+ function generateAdapterFiles(options) {
750
+ const { platform, name, baseUrl } = options;
751
+ switch (platform) {
752
+ case "vercel":
753
+ return generateVercelFiles(name, baseUrl);
754
+ case "netlify":
755
+ return generateNetlifyFiles(name, baseUrl);
756
+ case "cloudflare":
757
+ return generateCloudflareFiles(name, baseUrl);
758
+ default:
759
+ throw new Error(`Unknown platform: ${platform}`);
760
+ }
761
+ }
762
+ function generateVercelFiles(name, baseUrl) {
763
+ return [
764
+ {
765
+ path: "api/mcp.js",
766
+ description: "Vercel serverless function for MCP server",
767
+ content: `/**
768
+ * Vercel API route for MCP server
769
+ * Deploy to Vercel and this will be available at /api/mcp
770
+ */
771
+
772
+ const { createVercelHandler } = require('docusaurus-plugin-mcp-server/adapters');
773
+ const path = require('path');
774
+
775
+ const projectRoot = path.join(__dirname, '..');
776
+
777
+ module.exports = createVercelHandler({
778
+ docsPath: path.join(projectRoot, 'build/mcp/docs.json'),
779
+ indexPath: path.join(projectRoot, 'build/mcp/search-index.json'),
780
+ name: '${name}',
781
+ version: '1.0.0',
782
+ baseUrl: '${baseUrl}',
783
+ });
784
+ `
785
+ },
786
+ {
787
+ path: "vercel.json",
788
+ description: "Vercel configuration (merge with existing if present)",
789
+ content: `{
790
+ "functions": {
791
+ "api/mcp.js": {
792
+ "includeFiles": "build/mcp/**"
793
+ }
794
+ },
795
+ "rewrites": [
796
+ {
797
+ "source": "/mcp",
798
+ "destination": "/api/mcp"
799
+ }
800
+ ]
801
+ }
802
+ `
803
+ }
804
+ ];
805
+ }
806
+ function generateNetlifyFiles(name, baseUrl) {
807
+ return [
808
+ {
809
+ path: "netlify/functions/mcp.js",
810
+ description: "Netlify serverless function for MCP server",
811
+ content: `/**
812
+ * Netlify function for MCP server
813
+ * Deploy to Netlify and this will be available at /.netlify/functions/mcp
814
+ */
815
+
816
+ const { createNetlifyHandler } = require('docusaurus-plugin-mcp-server/adapters');
817
+ const path = require('path');
818
+
819
+ const projectRoot = path.join(__dirname, '../..');
820
+
821
+ exports.handler = createNetlifyHandler({
822
+ docsPath: path.join(projectRoot, 'build/mcp/docs.json'),
823
+ indexPath: path.join(projectRoot, 'build/mcp/search-index.json'),
824
+ name: '${name}',
825
+ version: '1.0.0',
826
+ baseUrl: '${baseUrl}',
827
+ });
828
+ `
829
+ },
830
+ {
831
+ path: "netlify.toml",
832
+ description: "Netlify configuration (merge with existing if present)",
833
+ content: `[build]
834
+ publish = "build"
835
+ command = "npm run build"
836
+
837
+ [functions]
838
+ directory = "netlify/functions"
839
+ included_files = ["build/mcp/**"]
840
+
841
+ [[redirects]]
842
+ from = "/mcp"
843
+ to = "/.netlify/functions/mcp"
844
+ status = 200
845
+ `
846
+ }
847
+ ];
848
+ }
849
+ function generateCloudflareFiles(name, baseUrl) {
850
+ return [
851
+ {
852
+ path: "workers/mcp.js",
853
+ description: "Cloudflare Worker for MCP server",
854
+ content: `/**
855
+ * Cloudflare Worker for MCP server
856
+ *
857
+ * Note: This requires bundling docs.json and search-index.json with the worker,
858
+ * or using Cloudflare KV/R2 for storage.
859
+ *
860
+ * For bundling, use wrangler with custom build configuration.
861
+ */
862
+
863
+ import { createCloudflareHandler } from 'docusaurus-plugin-mcp-server/adapters';
864
+
865
+ // Option 1: Import bundled data (requires bundler configuration)
866
+ // import docs from '../build/mcp/docs.json';
867
+ // import searchIndex from '../build/mcp/search-index.json';
868
+
869
+ // Option 2: Use KV bindings (requires KV namespace configuration)
870
+ // const docs = await env.MCP_KV.get('docs', { type: 'json' });
871
+ // const searchIndex = await env.MCP_KV.get('search-index', { type: 'json' });
872
+
873
+ export default {
874
+ fetch: createCloudflareHandler({
875
+ name: '${name}',
876
+ version: '1.0.0',
877
+ baseUrl: '${baseUrl}',
878
+ // docsPath and indexPath are used for file-based loading
879
+ // For Workers, you'll need to configure data loading differently
880
+ docsPath: './mcp/docs.json',
881
+ indexPath: './mcp/search-index.json',
882
+ }),
883
+ };
884
+ `
885
+ },
886
+ {
887
+ path: "wrangler.toml",
888
+ description: "Cloudflare Wrangler configuration",
889
+ content: `name = "${name}-mcp"
890
+ main = "workers/mcp.js"
891
+ compatibility_date = "2024-01-01"
892
+
893
+ # Uncomment to use KV for storing docs
894
+ # [[kv_namespaces]]
895
+ # binding = "MCP_KV"
896
+ # id = "your-kv-namespace-id"
897
+
898
+ # Static assets (the Docusaurus build)
899
+ # [site]
900
+ # bucket = "./build"
901
+ `
902
+ }
903
+ ];
904
+ }
905
+
906
+ export { createCloudflareHandler, createNetlifyHandler, createVercelHandler, generateAdapterFiles };
907
+ //# sourceMappingURL=adapters-entry.mjs.map
908
+ //# sourceMappingURL=adapters-entry.mjs.map