@arabold/docs-mcp-server 1.14.0 → 1.15.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/README.md +84 -28
- package/dist/{EmbeddingFactory-Dz1hdJJe.js → EmbeddingFactory-C6_OpOiy.js} +2 -2
- package/dist/{EmbeddingFactory-Dz1hdJJe.js.map → EmbeddingFactory-C6_OpOiy.js.map} +1 -1
- package/dist/assets/main.css +1 -1
- package/dist/index.js +6047 -0
- package/dist/index.js.map +1 -0
- package/package.json +45 -45
- package/public/assets/main.css +1 -1
- package/dist/DocumentManagementService-BZ_ZZgPI.js +0 -3483
- package/dist/DocumentManagementService-BZ_ZZgPI.js.map +0 -1
- package/dist/FindVersionTool-Dfw5Lbql.js +0 -140
- package/dist/FindVersionTool-Dfw5Lbql.js.map +0 -1
- package/dist/RemoveTool-w8KGOaXw.js +0 -65
- package/dist/RemoveTool-w8KGOaXw.js.map +0 -1
- package/dist/cli.js +0 -236
- package/dist/cli.js.map +0 -1
- package/dist/server.js +0 -769
- package/dist/server.js.map +0 -1
- package/dist/web.js +0 -956
- package/dist/web.js.map +0 -1
package/dist/server.js
DELETED
|
@@ -1,769 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import "dotenv/config";
|
|
3
|
-
import { program } from "commander";
|
|
4
|
-
import { l as logger, P as PipelineJobStatus, D as DocumentManagementService, a as PipelineManager, b as DEFAULT_MAX_DEPTH, c as DEFAULT_MAX_PAGES, L as LibraryNotFoundError, V as VersionNotFoundError, s as setLogLevel, d as LogLevel, H as HttpFetcher, F as FileFetcher, S as SearchTool, e as ScrapeTool, f as ListLibrariesTool, g as DEFAULT_PROTOCOL, h as DEFAULT_HTTP_PORT } from "./DocumentManagementService-BZ_ZZgPI.js";
|
|
5
|
-
import * as http from "node:http";
|
|
6
|
-
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
|
7
|
-
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
8
|
-
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
9
|
-
import { z } from "zod";
|
|
10
|
-
import "cheerio";
|
|
11
|
-
import "node:vm";
|
|
12
|
-
import "jsdom";
|
|
13
|
-
import "playwright";
|
|
14
|
-
import "@joplin/turndown-plugin-gfm";
|
|
15
|
-
import "turndown";
|
|
16
|
-
import "node:util";
|
|
17
|
-
import "semver";
|
|
18
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
19
|
-
import { F as FetchUrlTool, a as FindVersionTool } from "./FindVersionTool-Dfw5Lbql.js";
|
|
20
|
-
import { R as RemoveTool, L as ListJobsTool } from "./RemoveTool-w8KGOaXw.js";
|
|
21
|
-
class CancelJobTool {
|
|
22
|
-
manager;
|
|
23
|
-
/**
|
|
24
|
-
* Creates an instance of CancelJobTool.
|
|
25
|
-
* @param manager The PipelineManager instance.
|
|
26
|
-
*/
|
|
27
|
-
constructor(manager) {
|
|
28
|
-
this.manager = manager;
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Executes the tool to attempt cancellation of a specific job.
|
|
32
|
-
* @param input - The input parameters, containing the jobId.
|
|
33
|
-
* @returns A promise that resolves with the outcome message.
|
|
34
|
-
*/
|
|
35
|
-
async execute(input) {
|
|
36
|
-
try {
|
|
37
|
-
const job = await this.manager.getJob(input.jobId);
|
|
38
|
-
if (!job) {
|
|
39
|
-
logger.warn(`[CancelJobTool] Job not found: ${input.jobId}`);
|
|
40
|
-
return {
|
|
41
|
-
message: `Job with ID ${input.jobId} not found.`,
|
|
42
|
-
success: false
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
if (job.status === PipelineJobStatus.COMPLETED || // Use enum member
|
|
46
|
-
job.status === PipelineJobStatus.FAILED || // Use enum member
|
|
47
|
-
job.status === PipelineJobStatus.CANCELLED) {
|
|
48
|
-
logger.info(
|
|
49
|
-
`[CancelJobTool] Job ${input.jobId} is already in a final state: ${job.status}.`
|
|
50
|
-
);
|
|
51
|
-
return {
|
|
52
|
-
message: `Job ${input.jobId} is already ${job.status}. No action taken.`,
|
|
53
|
-
success: true
|
|
54
|
-
// Considered success as no cancellation needed
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
await this.manager.cancelJob(input.jobId);
|
|
58
|
-
const updatedJob = await this.manager.getJob(input.jobId);
|
|
59
|
-
const finalStatus = updatedJob?.status ?? "UNKNOWN (job disappeared?)";
|
|
60
|
-
logger.info(
|
|
61
|
-
`[CancelJobTool] Cancellation requested for job ${input.jobId}. Current status: ${finalStatus}`
|
|
62
|
-
);
|
|
63
|
-
return {
|
|
64
|
-
message: `Cancellation requested for job ${input.jobId}. Current status: ${finalStatus}.`,
|
|
65
|
-
success: true
|
|
66
|
-
};
|
|
67
|
-
} catch (error) {
|
|
68
|
-
logger.error(`[CancelJobTool] Error cancelling job ${input.jobId}: ${error}`);
|
|
69
|
-
return {
|
|
70
|
-
message: `Failed to cancel job ${input.jobId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
71
|
-
success: false
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
class GetJobInfoTool {
|
|
77
|
-
manager;
|
|
78
|
-
/**
|
|
79
|
-
* Creates an instance of GetJobInfoTool.
|
|
80
|
-
* @param manager The PipelineManager instance.
|
|
81
|
-
*/
|
|
82
|
-
constructor(manager) {
|
|
83
|
-
this.manager = manager;
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* Executes the tool to retrieve simplified info for a specific job.
|
|
87
|
-
* @param input - The input parameters, containing the jobId.
|
|
88
|
-
* @returns A promise that resolves with the simplified job info or null if not found.
|
|
89
|
-
*/
|
|
90
|
-
async execute(input) {
|
|
91
|
-
const job = await this.manager.getJob(input.jobId);
|
|
92
|
-
if (!job) {
|
|
93
|
-
return { job: null };
|
|
94
|
-
}
|
|
95
|
-
const jobInfo = {
|
|
96
|
-
id: job.id,
|
|
97
|
-
library: job.library,
|
|
98
|
-
version: job.version,
|
|
99
|
-
status: job.status,
|
|
100
|
-
createdAt: job.createdAt.toISOString(),
|
|
101
|
-
startedAt: job.startedAt?.toISOString() ?? null,
|
|
102
|
-
finishedAt: job.finishedAt?.toISOString() ?? null,
|
|
103
|
-
error: job.error?.message ?? null
|
|
104
|
-
};
|
|
105
|
-
return { job: jobInfo };
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
let docService;
|
|
109
|
-
let pipelineManager;
|
|
110
|
-
async function initializeServices() {
|
|
111
|
-
if (docService || pipelineManager) {
|
|
112
|
-
logger.warn("Services already initialized.");
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
docService = new DocumentManagementService();
|
|
116
|
-
try {
|
|
117
|
-
await docService.initialize();
|
|
118
|
-
logger.debug("DocumentManagementService initialized.");
|
|
119
|
-
pipelineManager = new PipelineManager(docService);
|
|
120
|
-
await pipelineManager.start();
|
|
121
|
-
logger.debug("PipelineManager initialized and started.");
|
|
122
|
-
} catch (error) {
|
|
123
|
-
logger.error(`Failed to initialize services: ${error}`);
|
|
124
|
-
await shutdownServices();
|
|
125
|
-
throw error;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
async function shutdownServices() {
|
|
129
|
-
if (pipelineManager) {
|
|
130
|
-
await pipelineManager.stop();
|
|
131
|
-
logger.info("PipelineManager stopped.");
|
|
132
|
-
pipelineManager = void 0;
|
|
133
|
-
}
|
|
134
|
-
if (docService) {
|
|
135
|
-
await docService.shutdown();
|
|
136
|
-
logger.info("DocumentManagementService shutdown.");
|
|
137
|
-
docService = void 0;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
function getDocService() {
|
|
141
|
-
if (!docService) {
|
|
142
|
-
throw new Error("DocumentManagementService has not been initialized.");
|
|
143
|
-
}
|
|
144
|
-
return docService;
|
|
145
|
-
}
|
|
146
|
-
function getPipelineManager() {
|
|
147
|
-
if (!pipelineManager) {
|
|
148
|
-
throw new Error("PipelineManager has not been initialized.");
|
|
149
|
-
}
|
|
150
|
-
return pipelineManager;
|
|
151
|
-
}
|
|
152
|
-
function createResponse(text) {
|
|
153
|
-
return {
|
|
154
|
-
content: [
|
|
155
|
-
{
|
|
156
|
-
type: "text",
|
|
157
|
-
text
|
|
158
|
-
}
|
|
159
|
-
],
|
|
160
|
-
isError: false
|
|
161
|
-
};
|
|
162
|
-
}
|
|
163
|
-
function createError(text) {
|
|
164
|
-
return {
|
|
165
|
-
content: [
|
|
166
|
-
{
|
|
167
|
-
type: "text",
|
|
168
|
-
text
|
|
169
|
-
}
|
|
170
|
-
],
|
|
171
|
-
isError: true
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
function createMcpServerInstance(tools) {
|
|
175
|
-
const server = new McpServer(
|
|
176
|
-
{
|
|
177
|
-
name: "docs-mcp-server",
|
|
178
|
-
version: "0.1.0"
|
|
179
|
-
},
|
|
180
|
-
{
|
|
181
|
-
capabilities: {
|
|
182
|
-
tools: {},
|
|
183
|
-
prompts: {},
|
|
184
|
-
resources: {}
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
);
|
|
188
|
-
server.tool(
|
|
189
|
-
"scrape_docs",
|
|
190
|
-
"Scrape and index documentation from a URL",
|
|
191
|
-
{
|
|
192
|
-
url: z.string().url().describe("URL of the documentation to scrape"),
|
|
193
|
-
library: z.string().describe("Name of the library"),
|
|
194
|
-
version: z.string().optional().describe("Version of the library"),
|
|
195
|
-
maxPages: z.number().optional().default(DEFAULT_MAX_PAGES).describe(`Maximum number of pages to scrape (default: ${DEFAULT_MAX_PAGES})`),
|
|
196
|
-
maxDepth: z.number().optional().default(DEFAULT_MAX_DEPTH).describe(`Maximum navigation depth (default: ${DEFAULT_MAX_DEPTH})`),
|
|
197
|
-
scope: z.enum(["subpages", "hostname", "domain"]).optional().default("subpages").describe("Defines the crawling boundary: 'subpages', 'hostname', or 'domain'"),
|
|
198
|
-
followRedirects: z.boolean().optional().default(true).describe("Whether to follow HTTP redirects (3xx responses)")
|
|
199
|
-
},
|
|
200
|
-
async ({ url, library, version, maxPages, maxDepth, scope, followRedirects }) => {
|
|
201
|
-
try {
|
|
202
|
-
const result = await tools.scrape.execute({
|
|
203
|
-
url,
|
|
204
|
-
library,
|
|
205
|
-
version,
|
|
206
|
-
waitForCompletion: false,
|
|
207
|
-
// Don't wait for completion
|
|
208
|
-
// onProgress: undefined, // Explicitly undefined or omitted
|
|
209
|
-
options: {
|
|
210
|
-
maxPages,
|
|
211
|
-
maxDepth,
|
|
212
|
-
scope,
|
|
213
|
-
followRedirects
|
|
214
|
-
}
|
|
215
|
-
});
|
|
216
|
-
if ("jobId" in result) {
|
|
217
|
-
return createResponse(`🚀 Scraping job started with ID: ${result.jobId}.`);
|
|
218
|
-
}
|
|
219
|
-
return createResponse(
|
|
220
|
-
`Scraping finished immediately (unexpectedly) with ${result.pagesScraped} pages.`
|
|
221
|
-
);
|
|
222
|
-
} catch (error) {
|
|
223
|
-
return createError(
|
|
224
|
-
`Failed to scrape documentation: ${error instanceof Error ? error.message : String(error)}`
|
|
225
|
-
);
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
);
|
|
229
|
-
server.tool(
|
|
230
|
-
"search_docs",
|
|
231
|
-
'Searches up-to-date documentation for a library. Examples:\n\n- {library: "react", query: "hooks lifecycle"} -> matches latest version of React\n- {library: "react", version: "18.0.0", query: "hooks lifecycle"} -> matches React 18.0.0 or earlier\n- {library: "typescript", version: "5.x", query: "ReturnType example"} -> any TypeScript 5.x.x version\n- {library: "typescript", version: "5.2.x", query: "ReturnType example"} -> any TypeScript 5.2.x version',
|
|
232
|
-
{
|
|
233
|
-
library: z.string().describe("Name of the library"),
|
|
234
|
-
version: z.string().optional().describe(
|
|
235
|
-
"Version of the library (supports exact versions like '18.0.0' or X-Range patterns like '5.x', '5.2.x')"
|
|
236
|
-
),
|
|
237
|
-
query: z.string().describe("Search query"),
|
|
238
|
-
limit: z.number().optional().default(5).describe("Maximum number of results")
|
|
239
|
-
},
|
|
240
|
-
async ({ library, version, query, limit }) => {
|
|
241
|
-
try {
|
|
242
|
-
const result = await tools.search.execute({
|
|
243
|
-
library,
|
|
244
|
-
version,
|
|
245
|
-
query,
|
|
246
|
-
limit,
|
|
247
|
-
exactMatch: false
|
|
248
|
-
// Always false for MCP interface
|
|
249
|
-
});
|
|
250
|
-
const formattedResults = result.results.map(
|
|
251
|
-
(r, i) => `
|
|
252
|
-
------------------------------------------------------------
|
|
253
|
-
Result ${i + 1}: ${r.url}
|
|
254
|
-
|
|
255
|
-
${r.content}
|
|
256
|
-
`
|
|
257
|
-
);
|
|
258
|
-
if (formattedResults.length === 0) {
|
|
259
|
-
return createResponse(
|
|
260
|
-
`No results found for '${query}' in ${library}. Try to use a different or more general query.`
|
|
261
|
-
);
|
|
262
|
-
}
|
|
263
|
-
return createResponse(
|
|
264
|
-
`Search results for '${query}' in ${library}:
|
|
265
|
-
${formattedResults.join("")}`
|
|
266
|
-
);
|
|
267
|
-
} catch (error) {
|
|
268
|
-
if (error instanceof LibraryNotFoundError) {
|
|
269
|
-
return createResponse(
|
|
270
|
-
[
|
|
271
|
-
`Library "${library}" not found.`,
|
|
272
|
-
error.suggestions?.length ? `Did you mean: ${error.suggestions?.join(", ")}?` : void 0
|
|
273
|
-
].join(" ")
|
|
274
|
-
);
|
|
275
|
-
}
|
|
276
|
-
if (error instanceof VersionNotFoundError) {
|
|
277
|
-
const indexedVersions = error.availableVersions.map((v) => v.version);
|
|
278
|
-
return createResponse(
|
|
279
|
-
[
|
|
280
|
-
`Version "${version}" not found.`,
|
|
281
|
-
indexedVersions.length > 0 ? `Available indexed versions for ${library}: ${indexedVersions.join(", ")}` : void 0
|
|
282
|
-
].join(" ")
|
|
283
|
-
);
|
|
284
|
-
}
|
|
285
|
-
return createError(
|
|
286
|
-
`Failed to search documentation: ${error instanceof Error ? error.message : String(error)}`
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
);
|
|
291
|
-
server.tool("list_libraries", "List all indexed libraries", {}, async () => {
|
|
292
|
-
try {
|
|
293
|
-
const result = await tools.listLibraries.execute();
|
|
294
|
-
if (result.libraries.length === 0) {
|
|
295
|
-
return createResponse("No libraries indexed yet.");
|
|
296
|
-
}
|
|
297
|
-
return createResponse(
|
|
298
|
-
`Indexed libraries:
|
|
299
|
-
|
|
300
|
-
${result.libraries.map((lib) => `- ${lib.name}`).join("\n")}`
|
|
301
|
-
);
|
|
302
|
-
} catch (error) {
|
|
303
|
-
return createError(
|
|
304
|
-
`Failed to list libraries: ${error instanceof Error ? error.message : String(error)}`
|
|
305
|
-
);
|
|
306
|
-
}
|
|
307
|
-
});
|
|
308
|
-
server.tool(
|
|
309
|
-
"find_version",
|
|
310
|
-
"Find best matching version for a library",
|
|
311
|
-
{
|
|
312
|
-
library: z.string().describe("Name of the library"),
|
|
313
|
-
targetVersion: z.string().optional().describe(
|
|
314
|
-
"Pattern to match (supports exact versions like '18.0.0' or X-Range patterns like '5.x', '5.2.x')"
|
|
315
|
-
)
|
|
316
|
-
},
|
|
317
|
-
async ({ library, targetVersion }) => {
|
|
318
|
-
try {
|
|
319
|
-
const message = await tools.findVersion.execute({
|
|
320
|
-
library,
|
|
321
|
-
targetVersion
|
|
322
|
-
});
|
|
323
|
-
if (!message) {
|
|
324
|
-
return createError("No matching version found");
|
|
325
|
-
}
|
|
326
|
-
return createResponse(message);
|
|
327
|
-
} catch (error) {
|
|
328
|
-
return createError(
|
|
329
|
-
`Failed to find version: ${error instanceof Error ? error.message : String(error)}`
|
|
330
|
-
);
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
);
|
|
334
|
-
server.tool(
|
|
335
|
-
"list_jobs",
|
|
336
|
-
"List pipeline jobs, optionally filtering by status.",
|
|
337
|
-
{
|
|
338
|
-
status: z.nativeEnum(PipelineJobStatus).optional().describe("Optional status to filter jobs by.")
|
|
339
|
-
},
|
|
340
|
-
async ({ status }) => {
|
|
341
|
-
try {
|
|
342
|
-
const result = await tools.listJobs.execute({ status });
|
|
343
|
-
const formattedJobs = result.jobs.map(
|
|
344
|
-
(job) => `- ID: ${job.id}
|
|
345
|
-
Status: ${job.status}
|
|
346
|
-
Library: ${job.library}
|
|
347
|
-
Version: ${job.version}
|
|
348
|
-
Created: ${job.createdAt}${job.startedAt ? `
|
|
349
|
-
Started: ${job.startedAt}` : ""}${job.finishedAt ? `
|
|
350
|
-
Finished: ${job.finishedAt}` : ""}${job.error ? `
|
|
351
|
-
Error: ${job.error}` : ""}`
|
|
352
|
-
).join("\n\n");
|
|
353
|
-
return createResponse(
|
|
354
|
-
result.jobs.length > 0 ? `Current Jobs:
|
|
355
|
-
|
|
356
|
-
${formattedJobs}` : "No jobs found."
|
|
357
|
-
);
|
|
358
|
-
} catch (error) {
|
|
359
|
-
return createError(
|
|
360
|
-
`Failed to list jobs: ${error instanceof Error ? error.message : String(error)}`
|
|
361
|
-
);
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
);
|
|
365
|
-
server.tool(
|
|
366
|
-
"get_job_info",
|
|
367
|
-
"Get the simplified info for a specific pipeline job.",
|
|
368
|
-
{
|
|
369
|
-
jobId: z.string().uuid().describe("The ID of the job to query.")
|
|
370
|
-
},
|
|
371
|
-
async ({ jobId }) => {
|
|
372
|
-
try {
|
|
373
|
-
const result = await tools.getJobInfo.execute({ jobId });
|
|
374
|
-
if (!result.job) {
|
|
375
|
-
return createError(`Job with ID ${jobId} not found.`);
|
|
376
|
-
}
|
|
377
|
-
const job = result.job;
|
|
378
|
-
const formattedJob = `- ID: ${job.id}
|
|
379
|
-
Status: ${job.status}
|
|
380
|
-
Library: ${job.library}@${job.version}
|
|
381
|
-
Created: ${job.createdAt}${job.startedAt ? `
|
|
382
|
-
Started: ${job.startedAt}` : ""}${job.finishedAt ? `
|
|
383
|
-
Finished: ${job.finishedAt}` : ""}${job.error ? `
|
|
384
|
-
Error: ${job.error}` : ""}`;
|
|
385
|
-
return createResponse(`Job Info:
|
|
386
|
-
|
|
387
|
-
${formattedJob}`);
|
|
388
|
-
} catch (error) {
|
|
389
|
-
return createError(
|
|
390
|
-
`Failed to get job info for ${jobId}: ${error instanceof Error ? error.message : String(error)}`
|
|
391
|
-
);
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
);
|
|
395
|
-
server.tool(
|
|
396
|
-
"fetch_url",
|
|
397
|
-
"Fetch a single URL and convert its content to Markdown",
|
|
398
|
-
{
|
|
399
|
-
url: z.string().url().describe("The URL to fetch and convert to markdown"),
|
|
400
|
-
followRedirects: z.boolean().optional().default(true).describe("Whether to follow HTTP redirects (3xx responses)")
|
|
401
|
-
},
|
|
402
|
-
async ({ url, followRedirects }) => {
|
|
403
|
-
try {
|
|
404
|
-
const result = await tools.fetchUrl.execute({ url, followRedirects });
|
|
405
|
-
return createResponse(result);
|
|
406
|
-
} catch (error) {
|
|
407
|
-
return createError(
|
|
408
|
-
`Failed to fetch URL: ${error instanceof Error ? error.message : String(error)}`
|
|
409
|
-
);
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
);
|
|
413
|
-
server.tool(
|
|
414
|
-
"cancel_job",
|
|
415
|
-
"Attempt to cancel a queued or running pipeline job.",
|
|
416
|
-
{
|
|
417
|
-
jobId: z.string().uuid().describe("The ID of the job to cancel.")
|
|
418
|
-
},
|
|
419
|
-
async ({ jobId }) => {
|
|
420
|
-
try {
|
|
421
|
-
const result = await tools.cancelJob.execute({ jobId });
|
|
422
|
-
if (result.success) {
|
|
423
|
-
return createResponse(result.message);
|
|
424
|
-
}
|
|
425
|
-
return createError(result.message);
|
|
426
|
-
} catch (error) {
|
|
427
|
-
return createError(
|
|
428
|
-
`Failed to cancel job ${jobId}: ${error instanceof Error ? error.message : String(error)}`
|
|
429
|
-
);
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
);
|
|
433
|
-
server.tool(
|
|
434
|
-
"remove_docs",
|
|
435
|
-
"Remove indexed documentation for a library version.",
|
|
436
|
-
{
|
|
437
|
-
library: z.string().describe("Name of the library"),
|
|
438
|
-
version: z.string().optional().describe("Version of the library (optional, removes unversioned if omitted)")
|
|
439
|
-
},
|
|
440
|
-
async ({ library, version }) => {
|
|
441
|
-
try {
|
|
442
|
-
const result = await tools.remove.execute({ library, version });
|
|
443
|
-
return createResponse(result.message);
|
|
444
|
-
} catch (error) {
|
|
445
|
-
return createError(
|
|
446
|
-
`Failed to remove documents: ${error instanceof Error ? error.message : String(error)}`
|
|
447
|
-
);
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
);
|
|
451
|
-
server.prompt(
|
|
452
|
-
"docs",
|
|
453
|
-
"Search indexed documentation",
|
|
454
|
-
{
|
|
455
|
-
library: z.string().describe("Name of the library"),
|
|
456
|
-
version: z.string().optional().describe("Version of the library"),
|
|
457
|
-
query: z.string().describe("Search query")
|
|
458
|
-
},
|
|
459
|
-
async ({ library, version, query }) => {
|
|
460
|
-
return {
|
|
461
|
-
messages: [
|
|
462
|
-
{
|
|
463
|
-
role: "user",
|
|
464
|
-
content: {
|
|
465
|
-
type: "text",
|
|
466
|
-
text: `Please search ${library} ${version || ""} documentation for this query: ${query}`
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
]
|
|
470
|
-
};
|
|
471
|
-
}
|
|
472
|
-
);
|
|
473
|
-
server.resource(
|
|
474
|
-
"libraries",
|
|
475
|
-
"docs://libraries",
|
|
476
|
-
{
|
|
477
|
-
description: "List all indexed libraries"
|
|
478
|
-
},
|
|
479
|
-
async (uri) => {
|
|
480
|
-
const result = await tools.listLibraries.execute();
|
|
481
|
-
return {
|
|
482
|
-
contents: result.libraries.map((lib) => ({
|
|
483
|
-
uri: new URL(lib.name, uri).href,
|
|
484
|
-
text: lib.name
|
|
485
|
-
}))
|
|
486
|
-
};
|
|
487
|
-
}
|
|
488
|
-
);
|
|
489
|
-
server.resource(
|
|
490
|
-
"versions",
|
|
491
|
-
new ResourceTemplate("docs://libraries/{library}/versions", {
|
|
492
|
-
list: void 0
|
|
493
|
-
}),
|
|
494
|
-
{
|
|
495
|
-
description: "List all indexed versions for a library"
|
|
496
|
-
},
|
|
497
|
-
async (uri, { library }) => {
|
|
498
|
-
const result = await tools.listLibraries.execute();
|
|
499
|
-
const lib = result.libraries.find((l) => l.name === library);
|
|
500
|
-
if (!lib) {
|
|
501
|
-
return { contents: [] };
|
|
502
|
-
}
|
|
503
|
-
return {
|
|
504
|
-
contents: lib.versions.map((v) => ({
|
|
505
|
-
uri: new URL(v.version, uri).href,
|
|
506
|
-
text: v.version
|
|
507
|
-
}))
|
|
508
|
-
};
|
|
509
|
-
}
|
|
510
|
-
);
|
|
511
|
-
server.resource(
|
|
512
|
-
"jobs",
|
|
513
|
-
"docs://jobs",
|
|
514
|
-
{
|
|
515
|
-
description: "List pipeline jobs, optionally filtering by status.",
|
|
516
|
-
mimeType: "application/json"
|
|
517
|
-
},
|
|
518
|
-
async (uri) => {
|
|
519
|
-
const statusParam = uri.searchParams.get("status");
|
|
520
|
-
let statusFilter;
|
|
521
|
-
if (statusParam) {
|
|
522
|
-
const validation = z.nativeEnum(PipelineJobStatus).safeParse(statusParam);
|
|
523
|
-
if (validation.success) {
|
|
524
|
-
statusFilter = validation.data;
|
|
525
|
-
} else {
|
|
526
|
-
logger.warn(`Invalid status parameter received: ${statusParam}`);
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
const result = await tools.listJobs.execute({ status: statusFilter });
|
|
530
|
-
return {
|
|
531
|
-
contents: [
|
|
532
|
-
{
|
|
533
|
-
uri: uri.href,
|
|
534
|
-
mimeType: "application/json",
|
|
535
|
-
text: JSON.stringify(result.jobs, null, 2)
|
|
536
|
-
// Stringify the simplified jobs array
|
|
537
|
-
}
|
|
538
|
-
]
|
|
539
|
-
};
|
|
540
|
-
}
|
|
541
|
-
);
|
|
542
|
-
server.resource(
|
|
543
|
-
"job",
|
|
544
|
-
// A distinct name for this specific resource type
|
|
545
|
-
new ResourceTemplate("docs://jobs/{jobId}", { list: void 0 }),
|
|
546
|
-
{
|
|
547
|
-
description: "Get details for a specific pipeline job by ID.",
|
|
548
|
-
mimeType: "application/json"
|
|
549
|
-
},
|
|
550
|
-
async (uri, { jobId }) => {
|
|
551
|
-
if (typeof jobId !== "string" || jobId.length === 0) {
|
|
552
|
-
logger.warn(`Invalid jobId received in URI: ${jobId}`);
|
|
553
|
-
return { contents: [] };
|
|
554
|
-
}
|
|
555
|
-
const result = await tools.getJobInfo.execute({ jobId });
|
|
556
|
-
if (!result.job) {
|
|
557
|
-
return { contents: [] };
|
|
558
|
-
}
|
|
559
|
-
return {
|
|
560
|
-
contents: [
|
|
561
|
-
{
|
|
562
|
-
uri: uri.href,
|
|
563
|
-
mimeType: "application/json",
|
|
564
|
-
text: JSON.stringify(result.job, null, 2)
|
|
565
|
-
// Stringify the simplified job object
|
|
566
|
-
}
|
|
567
|
-
]
|
|
568
|
-
};
|
|
569
|
-
}
|
|
570
|
-
);
|
|
571
|
-
return server;
|
|
572
|
-
}
|
|
573
|
-
async function startHttpServer(tools, port) {
|
|
574
|
-
setLogLevel(LogLevel.INFO);
|
|
575
|
-
const server = createMcpServerInstance(tools);
|
|
576
|
-
const sseTransports = {};
|
|
577
|
-
const httpServer = http.createServer(async (req, res) => {
|
|
578
|
-
try {
|
|
579
|
-
const url = new URL(req.url || "/", `http://${req.headers.host}`);
|
|
580
|
-
if (req.method === "GET" && url.pathname === "/sse") {
|
|
581
|
-
const transport = new SSEServerTransport("/messages", res);
|
|
582
|
-
sseTransports[transport.sessionId] = transport;
|
|
583
|
-
res.on("close", () => {
|
|
584
|
-
delete sseTransports[transport.sessionId];
|
|
585
|
-
transport.close();
|
|
586
|
-
});
|
|
587
|
-
await server.connect(transport);
|
|
588
|
-
} else if (req.method === "POST" && url.pathname === "/messages") {
|
|
589
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
590
|
-
const transport = sessionId ? sseTransports[sessionId] : void 0;
|
|
591
|
-
if (transport) {
|
|
592
|
-
let body = "";
|
|
593
|
-
for await (const chunk of req) {
|
|
594
|
-
body += chunk;
|
|
595
|
-
}
|
|
596
|
-
const parsedBody = JSON.parse(body);
|
|
597
|
-
await transport.handlePostMessage(req, res, parsedBody);
|
|
598
|
-
} else {
|
|
599
|
-
res.writeHead(400, { "Content-Type": "application/json" });
|
|
600
|
-
res.end(JSON.stringify({ error: "No transport found for sessionId" }));
|
|
601
|
-
}
|
|
602
|
-
} else if (url.pathname === "/mcp") {
|
|
603
|
-
let body = "";
|
|
604
|
-
for await (const chunk of req) {
|
|
605
|
-
body += chunk;
|
|
606
|
-
}
|
|
607
|
-
const parsedBody = JSON.parse(body);
|
|
608
|
-
const requestServer = createMcpServerInstance(tools);
|
|
609
|
-
const requestTransport = new StreamableHTTPServerTransport({
|
|
610
|
-
sessionIdGenerator: void 0
|
|
611
|
-
});
|
|
612
|
-
res.on("close", () => {
|
|
613
|
-
logger.info("Streamable HTTP request closed");
|
|
614
|
-
requestTransport.close();
|
|
615
|
-
requestServer.close();
|
|
616
|
-
});
|
|
617
|
-
await requestServer.connect(requestTransport);
|
|
618
|
-
await requestTransport.handleRequest(req, res, parsedBody);
|
|
619
|
-
} else {
|
|
620
|
-
res.writeHead(404, { "Content-Type": "application/json" });
|
|
621
|
-
res.end(
|
|
622
|
-
JSON.stringify({
|
|
623
|
-
error: `Endpoint ${url.pathname} not found.`
|
|
624
|
-
})
|
|
625
|
-
);
|
|
626
|
-
}
|
|
627
|
-
} catch (error) {
|
|
628
|
-
logger.error(`Error handling HTTP request: ${error}`);
|
|
629
|
-
res.writeHead(500, { "Content-Type": "application/json" });
|
|
630
|
-
res.end(
|
|
631
|
-
JSON.stringify({
|
|
632
|
-
error: error instanceof Error ? error.message : String(error)
|
|
633
|
-
})
|
|
634
|
-
);
|
|
635
|
-
}
|
|
636
|
-
});
|
|
637
|
-
httpServer.listen(port, () => {
|
|
638
|
-
logger.info(`🤖 Docs MCP server listening at http://127.0.0.1:${port}`);
|
|
639
|
-
});
|
|
640
|
-
return server;
|
|
641
|
-
}
|
|
642
|
-
async function startStdioServer(tools) {
|
|
643
|
-
setLogLevel(LogLevel.ERROR);
|
|
644
|
-
const server = createMcpServerInstance(tools);
|
|
645
|
-
const transport = new StdioServerTransport();
|
|
646
|
-
await server.connect(transport);
|
|
647
|
-
logger.info("🤖 Docs MCP server listening on stdio");
|
|
648
|
-
return server;
|
|
649
|
-
}
|
|
650
|
-
async function initializeTools() {
|
|
651
|
-
const docService2 = getDocService();
|
|
652
|
-
const pipelineManager2 = getPipelineManager();
|
|
653
|
-
const tools = {
|
|
654
|
-
listLibraries: new ListLibrariesTool(docService2),
|
|
655
|
-
findVersion: new FindVersionTool(docService2),
|
|
656
|
-
scrape: new ScrapeTool(docService2, pipelineManager2),
|
|
657
|
-
search: new SearchTool(docService2),
|
|
658
|
-
listJobs: new ListJobsTool(pipelineManager2),
|
|
659
|
-
getJobInfo: new GetJobInfoTool(pipelineManager2),
|
|
660
|
-
cancelJob: new CancelJobTool(pipelineManager2),
|
|
661
|
-
remove: new RemoveTool(docService2),
|
|
662
|
-
// FetchUrlTool now uses middleware pipeline internally
|
|
663
|
-
fetchUrl: new FetchUrlTool(new HttpFetcher(), new FileFetcher())
|
|
664
|
-
};
|
|
665
|
-
return tools;
|
|
666
|
-
}
|
|
667
|
-
let runningServer = null;
|
|
668
|
-
let runningPipelineManager = null;
|
|
669
|
-
let runningDocService = null;
|
|
670
|
-
async function startServer(protocol, port) {
|
|
671
|
-
try {
|
|
672
|
-
setLogLevel(LogLevel.ERROR);
|
|
673
|
-
await initializeServices();
|
|
674
|
-
runningDocService = getDocService();
|
|
675
|
-
runningPipelineManager = getPipelineManager();
|
|
676
|
-
const tools = await initializeTools();
|
|
677
|
-
let serverInstance;
|
|
678
|
-
if (protocol === "stdio") {
|
|
679
|
-
serverInstance = await startStdioServer(tools);
|
|
680
|
-
} else if (protocol === "http") {
|
|
681
|
-
if (port === void 0) {
|
|
682
|
-
logger.error("HTTP protocol requires a port.");
|
|
683
|
-
process.exit(1);
|
|
684
|
-
}
|
|
685
|
-
serverInstance = await startHttpServer(tools, port);
|
|
686
|
-
} else {
|
|
687
|
-
logger.error(`Unknown protocol: ${protocol}`);
|
|
688
|
-
process.exit(1);
|
|
689
|
-
}
|
|
690
|
-
runningServer = serverInstance;
|
|
691
|
-
process.on("SIGINT", async () => {
|
|
692
|
-
logger.info("Received SIGINT. Shutting down gracefully...");
|
|
693
|
-
await stopServer();
|
|
694
|
-
process.exit(0);
|
|
695
|
-
});
|
|
696
|
-
} catch (error) {
|
|
697
|
-
logger.error(`❌ Fatal Error during server startup: ${error}`);
|
|
698
|
-
await stopServer();
|
|
699
|
-
process.exit(1);
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
async function stopServer() {
|
|
703
|
-
logger.info("Shutting down MCP server and services...");
|
|
704
|
-
let hadError = false;
|
|
705
|
-
try {
|
|
706
|
-
if (runningPipelineManager) {
|
|
707
|
-
logger.debug("Stopping Pipeline Manager...");
|
|
708
|
-
await runningPipelineManager.stop();
|
|
709
|
-
logger.info("Pipeline Manager stopped.");
|
|
710
|
-
}
|
|
711
|
-
} catch (e) {
|
|
712
|
-
logger.error(`Error stopping Pipeline Manager: ${e}`);
|
|
713
|
-
hadError = true;
|
|
714
|
-
}
|
|
715
|
-
try {
|
|
716
|
-
if (runningDocService) {
|
|
717
|
-
logger.debug("Shutting down Document Service...");
|
|
718
|
-
await runningDocService.shutdown();
|
|
719
|
-
logger.info("Document Service shut down.");
|
|
720
|
-
}
|
|
721
|
-
} catch (e) {
|
|
722
|
-
logger.error(`Error shutting down Document Service: ${e}`);
|
|
723
|
-
hadError = true;
|
|
724
|
-
}
|
|
725
|
-
try {
|
|
726
|
-
if (runningServer) {
|
|
727
|
-
logger.debug("Closing MCP Server connection...");
|
|
728
|
-
await runningServer.close();
|
|
729
|
-
logger.info("MCP Server connection closed.");
|
|
730
|
-
}
|
|
731
|
-
} catch (e) {
|
|
732
|
-
logger.error(`Error closing MCP Server: ${e}`);
|
|
733
|
-
hadError = true;
|
|
734
|
-
}
|
|
735
|
-
runningPipelineManager = null;
|
|
736
|
-
runningDocService = null;
|
|
737
|
-
runningServer = null;
|
|
738
|
-
if (hadError) {
|
|
739
|
-
logger.warn("Server shutdown completed with errors.");
|
|
740
|
-
} else {
|
|
741
|
-
logger.info("✅ Server shutdown complete.");
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
program.option("--protocol <type>", "Protocol to use (stdio or http)", DEFAULT_PROTOCOL).option(
|
|
745
|
-
"--port <number>",
|
|
746
|
-
"Port to listen on for http protocol",
|
|
747
|
-
`${DEFAULT_HTTP_PORT}`
|
|
748
|
-
).parse(process.argv);
|
|
749
|
-
const options = program.opts();
|
|
750
|
-
async function main() {
|
|
751
|
-
const protocol = options.protocol;
|
|
752
|
-
const port = process.env.MCP_PORT ? Number.parseInt(process.env.MCP_PORT, 10) : Number.parseInt(options.port, 10);
|
|
753
|
-
if (protocol !== "stdio" && protocol !== "http") {
|
|
754
|
-
console.error('Invalid protocol specified. Use "stdio" or "http".');
|
|
755
|
-
process.exit(1);
|
|
756
|
-
}
|
|
757
|
-
if (protocol === "http" && Number.isNaN(port)) {
|
|
758
|
-
console.error("Port must be a number when using http protocol.");
|
|
759
|
-
process.exit(1);
|
|
760
|
-
}
|
|
761
|
-
try {
|
|
762
|
-
await startServer(protocol, protocol === "http" ? port : void 0);
|
|
763
|
-
} catch (error) {
|
|
764
|
-
console.error(`Server failed to start: ${error}`);
|
|
765
|
-
process.exit(1);
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
main();
|
|
769
|
-
//# sourceMappingURL=server.js.map
|