server.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. /**
  2. * QMD MCP Server - Model Context Protocol server for QMD
  3. *
  4. * Exposes QMD search and document retrieval as MCP tools and resources.
  5. * Documents are accessible via qmd:// URIs.
  6. *
  7. * Follows MCP spec 2025-06-18 for proper response types.
  8. */
  9. import { createServer } from "node:http";
  10. import { randomUUID } from "node:crypto";
  11. import { readFileSync } from "node:fs";
  12. import { join, dirname } from "node:path";
  13. import { fileURLToPath } from "url";
  14. import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
  15. import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
  16. import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
  17. import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
  18. import { z } from "zod";
  19. import { existsSync } from "fs";
  20. import { createStore, extractSnippet, addLineNumbers, getDefaultDbPath, DEFAULT_MULTI_GET_MAX_BYTES, } from "../index.js";
  21. import { getConfigPath } from "../collections.js";
  22. // =============================================================================
  23. // Helper functions
  24. // =============================================================================
  25. /**
  26. * Encode a path for use in qmd:// URIs.
  27. * Encodes special characters but preserves forward slashes for readability.
  28. */
  29. function encodeQmdPath(path) {
  30. // Encode each path segment separately to preserve slashes
  31. return path.split('/').map(segment => encodeURIComponent(segment)).join('/');
  32. }
  33. /**
  34. * Format search results as human-readable text summary
  35. */
  36. function formatSearchSummary(results, query) {
  37. if (results.length === 0) {
  38. return `No results found for "${query}"`;
  39. }
  40. const lines = [`Found ${results.length} result${results.length === 1 ? '' : 's'} for "${query}":\n`];
  41. for (const r of results) {
  42. lines.push(`${r.docid} ${Math.round(r.score * 100)}% ${r.file} - ${r.title}`);
  43. }
  44. return lines.join('\n');
  45. }
  46. function getPackageVersion() {
  47. try {
  48. const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "../../package.json");
  49. const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
  50. return pkg.version ?? "unknown";
  51. }
  52. catch {
  53. return "unknown";
  54. }
  55. }
  56. // =============================================================================
  57. // MCP Server
  58. // =============================================================================
  59. /**
  60. * Build dynamic server instructions from actual index state.
  61. * Injected into the LLM's system prompt via MCP initialize response —
  62. * gives the LLM immediate context about what's searchable without a tool call.
  63. */
  64. async function buildInstructions(store) {
  65. const status = await store.getStatus();
  66. const contexts = await store.listContexts();
  67. const globalCtx = await store.getGlobalContext();
  68. const lines = [];
  69. // --- What is this? ---
  70. lines.push(`QMD is your local search engine over ${status.totalDocuments} markdown documents.`);
  71. if (globalCtx)
  72. lines.push(`Context: ${globalCtx}`);
  73. // --- What's searchable? ---
  74. if (status.collections.length > 0) {
  75. lines.push("");
  76. lines.push("Collections (scope with `collection` parameter):");
  77. for (const col of status.collections) {
  78. // Find root context for this collection
  79. const rootCtx = contexts.find(c => c.collection === col.name && (c.path === "" || c.path === "/"));
  80. const desc = rootCtx ? ` — ${rootCtx.context}` : "";
  81. lines.push(` - "${col.name}" (${col.documents} docs)${desc}`);
  82. }
  83. }
  84. // --- Capability gaps ---
  85. if (!status.hasVectorIndex) {
  86. lines.push("");
  87. lines.push("Note: No vector embeddings yet. Run `qmd embed` to enable semantic search (vec/hyde).");
  88. }
  89. else if (status.needsEmbedding > 0) {
  90. lines.push("");
  91. lines.push(`Note: ${status.needsEmbedding} documents need embedding. Run \`qmd embed\` to update.`);
  92. }
  93. // --- Search tool ---
  94. lines.push("");
  95. lines.push("Search: Use `query` with sub-queries (lex/vec/hyde):");
  96. lines.push(" - type:'lex' — BM25 keyword search (exact terms, fast)");
  97. lines.push(" - type:'vec' — semantic vector search (meaning-based)");
  98. lines.push(" - type:'hyde' — hypothetical document (write what the answer looks like)");
  99. lines.push("");
  100. lines.push(" Always provide `intent` on every search call to disambiguate and improve snippets.");
  101. lines.push("");
  102. lines.push("Examples:");
  103. lines.push(" Quick keyword lookup: [{type:'lex', query:'error handling'}]");
  104. lines.push(" Semantic search: [{type:'vec', query:'how to handle errors gracefully'}]");
  105. lines.push(" Best results: [{type:'lex', query:'error'}, {type:'vec', query:'error handling best practices'}]");
  106. lines.push(" With intent: searches=[{type:'lex', query:'performance'}], intent='web page load times'");
  107. // --- Retrieval workflow ---
  108. lines.push("");
  109. lines.push("Retrieval:");
  110. lines.push(" - `get` — single document by path or docid (#abc123). Supports line offset (`file.md:100`).");
  111. lines.push(" - `multi_get` — batch retrieve by glob (`journals/2025-05*.md`) or comma-separated list.");
  112. // --- Non-obvious things that prevent mistakes ---
  113. lines.push("");
  114. lines.push("Tips:");
  115. lines.push(" - File paths in results are relative to their collection.");
  116. lines.push(" - Use `minScore: 0.5` to filter low-confidence results.");
  117. lines.push(" - Results include a `context` field describing the content type.");
  118. return lines.join("\n");
  119. }
  120. /**
  121. * Create an MCP server with all QMD tools, resources, and prompts registered.
  122. * Shared by both stdio and HTTP transports.
  123. */
  124. async function createMcpServer(store) {
  125. const server = new McpServer({ name: "qmd", version: getPackageVersion() }, { instructions: await buildInstructions(store) });
  126. // Pre-fetch default collection names for search tools
  127. const defaultCollectionNames = await store.getDefaultCollectionNames();
  128. // ---------------------------------------------------------------------------
  129. // Resource: qmd://{path} - read-only access to documents by path
  130. // Note: No list() - documents are discovered via search tools
  131. // ---------------------------------------------------------------------------
  132. server.registerResource("document", new ResourceTemplate("qmd://{+path}", { list: undefined }), {
  133. title: "QMD Document",
  134. description: "A markdown document from your QMD knowledge base. Use search tools to discover documents.",
  135. mimeType: "text/markdown",
  136. }, async (uri, { path }) => {
  137. // Decode URL-encoded path (MCP clients send encoded URIs)
  138. const pathStr = Array.isArray(path) ? path.join('/') : (path || '');
  139. const decodedPath = decodeURIComponent(pathStr);
  140. // Use SDK to find document — findDocument handles collection/path resolution
  141. const result = await store.get(decodedPath, { includeBody: true });
  142. if ("error" in result) {
  143. return { contents: [{ uri: uri.href, text: `Document not found: ${decodedPath}` }] };
  144. }
  145. let text = addLineNumbers(result.body || ""); // Default to line numbers
  146. if (result.context) {
  147. text = `<!-- Context: ${result.context} -->\n\n` + text;
  148. }
  149. return {
  150. contents: [{
  151. uri: uri.href,
  152. name: result.displayPath,
  153. title: result.title || result.displayPath,
  154. mimeType: "text/markdown",
  155. text,
  156. }],
  157. };
  158. });
  159. // ---------------------------------------------------------------------------
  160. // Tool: query (Primary search tool)
  161. // ---------------------------------------------------------------------------
  162. const subSearchSchema = z.object({
  163. type: z.enum(['lex', 'vec', 'hyde']).describe("lex = BM25 keywords (supports \"phrase\" and -negation); " +
  164. "vec = semantic question; hyde = hypothetical answer passage"),
  165. query: z.string().describe("The query text. For lex: use keywords, \"quoted phrases\", and -negation. " +
  166. "For vec: natural language question. For hyde: 50-100 word answer passage."),
  167. });
  168. server.registerTool("query", {
  169. title: "Query",
  170. description: `Search the knowledge base using a query document — one or more typed sub-queries combined for best recall.
  171. ## Query Types
  172. **lex** — BM25 keyword search. Fast, exact, no LLM needed.
  173. Full lex syntax:
  174. - \`term\` — prefix match ("perf" matches "performance")
  175. - \`"exact phrase"\` — phrase must appear verbatim
  176. - \`-term\` or \`-"phrase"\` — exclude documents containing this
  177. Good lex examples:
  178. - \`"connection pool" timeout -redis\`
  179. - \`"machine learning" -sports -athlete\`
  180. - \`handleError async typescript\`
  181. **vec** — Semantic vector search. Write a natural language question. Finds documents by meaning, not exact words.
  182. - \`how does the rate limiter handle burst traffic?\`
  183. - \`what is the tradeoff between consistency and availability?\`
  184. **hyde** — Hypothetical document. Write 50-100 words that look like the answer. Often the most powerful for nuanced topics.
  185. - \`The rate limiter uses a token bucket algorithm. When a client exceeds 100 req/min, subsequent requests return 429 until the window resets.\`
  186. ## Strategy
  187. Combine types for best results. First sub-query gets 2× weight — put your strongest signal first.
  188. | Goal | Approach |
  189. |------|----------|
  190. | Know exact term/name | \`lex\` only |
  191. | Concept search | \`vec\` only |
  192. | Best recall | \`lex\` + \`vec\` |
  193. | Complex/nuanced | \`lex\` + \`vec\` + \`hyde\` |
  194. | Unknown vocabulary | Use a standalone natural-language query (no typed lines) so the server can auto-expand it |
  195. ## Examples
  196. Simple lookup:
  197. \`\`\`json
  198. [{ "type": "lex", "query": "CAP theorem" }]
  199. \`\`\`
  200. Best recall on a technical topic:
  201. \`\`\`json
  202. [
  203. { "type": "lex", "query": "\\"connection pool\\" timeout -redis" },
  204. { "type": "vec", "query": "why do database connections time out under load" },
  205. { "type": "hyde", "query": "Connection pool exhaustion occurs when all connections are in use and new requests must wait. This typically happens under high concurrency when queries run longer than expected." }
  206. ]
  207. \`\`\`
  208. Intent-aware lex (C++ performance, not sports):
  209. \`\`\`json
  210. [
  211. { "type": "lex", "query": "\\"C++ performance\\" optimization -sports -athlete" },
  212. { "type": "vec", "query": "how to optimize C++ program performance" }
  213. ]
  214. \`\`\``,
  215. annotations: { readOnlyHint: true, openWorldHint: false },
  216. inputSchema: {
  217. searches: z.array(subSearchSchema).min(1).max(10).describe("Typed sub-queries to execute (lex/vec/hyde). First gets 2x weight."),
  218. limit: z.number().optional().default(10).describe("Max results (default: 10)"),
  219. minScore: z.number().optional().default(0).describe("Min relevance 0-1 (default: 0)"),
  220. candidateLimit: z.number().optional().describe("Maximum candidates to rerank (default: 40, lower = faster but may miss results)"),
  221. collections: z.array(z.string()).optional().describe("Filter to collections (OR match)"),
  222. intent: z.string().optional().describe("Background context to disambiguate the query. Example: query='performance', intent='web page load times and Core Web Vitals'. Does not search on its own."),
  223. rerank: z.boolean().optional().default(true).describe("Rerank results using LLM (default: true). Set to false for faster results on CPU-only machines."),
  224. },
  225. }, async ({ searches, limit, minScore, candidateLimit, collections, intent, rerank }) => {
  226. // Map to internal format
  227. const queries = searches.map(s => ({
  228. type: s.type,
  229. query: s.query,
  230. }));
  231. // Use default collections if none specified
  232. const effectiveCollections = collections ?? defaultCollectionNames;
  233. const results = await store.search({
  234. queries,
  235. collections: effectiveCollections.length > 0 ? effectiveCollections : undefined,
  236. limit,
  237. minScore,
  238. rerank,
  239. intent,
  240. });
  241. // Use first lex or vec query for snippet extraction
  242. const primaryQuery = searches.find(s => s.type === 'lex')?.query
  243. || searches.find(s => s.type === 'vec')?.query
  244. || searches[0]?.query || "";
  245. const filtered = results.map(r => {
  246. const { line, snippet } = extractSnippet(r.bestChunk, primaryQuery, 300, undefined, undefined, intent);
  247. return {
  248. docid: `#${r.docid}`,
  249. file: r.displayPath,
  250. title: r.title,
  251. score: Math.round(r.score * 100) / 100,
  252. context: r.context,
  253. snippet: addLineNumbers(snippet, line),
  254. };
  255. });
  256. return {
  257. content: [{ type: "text", text: formatSearchSummary(filtered, primaryQuery) }],
  258. structuredContent: { results: filtered },
  259. };
  260. });
  261. // ---------------------------------------------------------------------------
  262. // Tool: qmd_get (Retrieve document)
  263. // ---------------------------------------------------------------------------
  264. server.registerTool("get", {
  265. title: "Get Document",
  266. description: "Retrieve the full content of a document by its file path or docid. Use paths or docids (#abc123) from search results. Suggests similar files if not found.",
  267. annotations: { readOnlyHint: true, openWorldHint: false },
  268. inputSchema: {
  269. file: z.string().describe("File path or docid from search results (e.g., 'pages/meeting.md', '#abc123', or 'pages/meeting.md:100' to start at line 100)"),
  270. fromLine: z.number().optional().describe("Start from this line number (1-indexed)"),
  271. maxLines: z.number().optional().describe("Maximum number of lines to return"),
  272. lineNumbers: z.boolean().optional().default(false).describe("Add line numbers to output (format: 'N: content')"),
  273. },
  274. }, async ({ file, fromLine, maxLines, lineNumbers }) => {
  275. // Support :line suffix in `file` (e.g. "foo.md:120") when fromLine isn't provided
  276. let parsedFromLine = fromLine;
  277. let lookup = file;
  278. const colonMatch = lookup.match(/:(\d+)$/);
  279. if (colonMatch && colonMatch[1] && parsedFromLine === undefined) {
  280. parsedFromLine = parseInt(colonMatch[1], 10);
  281. lookup = lookup.slice(0, -colonMatch[0].length);
  282. }
  283. const result = await store.get(lookup, { includeBody: false });
  284. if ("error" in result) {
  285. let msg = `Document not found: ${file}`;
  286. if (result.similarFiles.length > 0) {
  287. msg += `\n\nDid you mean one of these?\n${result.similarFiles.map(s => ` - ${s}`).join('\n')}`;
  288. }
  289. return {
  290. content: [{ type: "text", text: msg }],
  291. isError: true,
  292. };
  293. }
  294. const body = await store.getDocumentBody(result.filepath, { fromLine: parsedFromLine, maxLines }) ?? "";
  295. let text = body;
  296. if (lineNumbers) {
  297. const startLine = parsedFromLine || 1;
  298. text = addLineNumbers(text, startLine);
  299. }
  300. if (result.context) {
  301. text = `<!-- Context: ${result.context} -->\n\n` + text;
  302. }
  303. return {
  304. content: [{
  305. type: "resource",
  306. resource: {
  307. uri: `qmd://${encodeQmdPath(result.displayPath)}`,
  308. name: result.displayPath,
  309. title: result.title,
  310. mimeType: "text/markdown",
  311. text,
  312. },
  313. }],
  314. };
  315. });
  316. // ---------------------------------------------------------------------------
  317. // Tool: qmd_multi_get (Retrieve multiple documents)
  318. // ---------------------------------------------------------------------------
  319. server.registerTool("multi_get", {
  320. title: "Multi-Get Documents",
  321. description: "Retrieve multiple documents by glob pattern (e.g., 'journals/2025-05*.md') or comma-separated list. Skips files larger than maxBytes.",
  322. annotations: { readOnlyHint: true, openWorldHint: false },
  323. inputSchema: {
  324. pattern: z.string().describe("Glob pattern or comma-separated list of file paths"),
  325. maxLines: z.number().optional().describe("Maximum lines per file"),
  326. maxBytes: z.number().optional().default(10240).describe("Skip files larger than this (default: 10240 = 10KB)"),
  327. lineNumbers: z.boolean().optional().default(false).describe("Add line numbers to output (format: 'N: content')"),
  328. },
  329. }, async ({ pattern, maxLines, maxBytes, lineNumbers }) => {
  330. const { docs, errors } = await store.multiGet(pattern, { includeBody: true, maxBytes: maxBytes || DEFAULT_MULTI_GET_MAX_BYTES });
  331. if (docs.length === 0 && errors.length === 0) {
  332. return {
  333. content: [{ type: "text", text: `No files matched pattern: ${pattern}` }],
  334. isError: true,
  335. };
  336. }
  337. const content = [];
  338. if (errors.length > 0) {
  339. content.push({ type: "text", text: `Errors:\n${errors.join('\n')}` });
  340. }
  341. for (const result of docs) {
  342. if (result.skipped) {
  343. content.push({
  344. type: "text",
  345. text: `[SKIPPED: ${result.doc.displayPath} - ${result.skipReason}. Use 'qmd_get' with file="${result.doc.displayPath}" to retrieve.]`,
  346. });
  347. continue;
  348. }
  349. let text = result.doc.body || "";
  350. if (maxLines !== undefined) {
  351. const lines = text.split("\n");
  352. text = lines.slice(0, maxLines).join("\n");
  353. if (lines.length > maxLines) {
  354. text += `\n\n[... truncated ${lines.length - maxLines} more lines]`;
  355. }
  356. }
  357. if (lineNumbers) {
  358. text = addLineNumbers(text);
  359. }
  360. if (result.doc.context) {
  361. text = `<!-- Context: ${result.doc.context} -->\n\n` + text;
  362. }
  363. content.push({
  364. type: "resource",
  365. resource: {
  366. uri: `qmd://${encodeQmdPath(result.doc.displayPath)}`,
  367. name: result.doc.displayPath,
  368. title: result.doc.title,
  369. mimeType: "text/markdown",
  370. text,
  371. },
  372. });
  373. }
  374. return { content };
  375. });
  376. // ---------------------------------------------------------------------------
  377. // Tool: qmd_status (Index status)
  378. // ---------------------------------------------------------------------------
  379. server.registerTool("status", {
  380. title: "Index Status",
  381. description: "Show the status of the QMD index: collections, document counts, and health information.",
  382. annotations: { readOnlyHint: true, openWorldHint: false },
  383. inputSchema: {},
  384. }, async () => {
  385. const status = await store.getStatus();
  386. const summary = [
  387. `QMD Index Status:`,
  388. ` Total documents: ${status.totalDocuments}`,
  389. ` Needs embedding: ${status.needsEmbedding}`,
  390. ` Vector index: ${status.hasVectorIndex ? 'yes' : 'no'}`,
  391. ` Collections: ${status.collections.length}`,
  392. ];
  393. for (const col of status.collections) {
  394. summary.push(` - ${col.name}: ${col.path} (${col.documents} docs)`);
  395. }
  396. return {
  397. content: [{ type: "text", text: summary.join('\n') }],
  398. structuredContent: status,
  399. };
  400. });
  401. return server;
  402. }
  403. // =============================================================================
  404. // Transport: stdio (default)
  405. // =============================================================================
  406. export async function startMcpServer() {
  407. const configPath = getConfigPath();
  408. const store = await createStore({
  409. dbPath: getDefaultDbPath(),
  410. ...(existsSync(configPath) ? { configPath } : {}),
  411. });
  412. const server = await createMcpServer(store);
  413. const transport = new StdioServerTransport();
  414. await server.connect(transport);
  415. }
  416. /**
  417. * Start MCP server over Streamable HTTP (JSON responses, no SSE).
  418. * Binds to localhost only. Returns a handle for shutdown and port discovery.
  419. */
  420. export async function startMcpHttpServer(port, options) {
  421. const configPath = getConfigPath();
  422. const store = await createStore({
  423. dbPath: getDefaultDbPath(),
  424. ...(existsSync(configPath) ? { configPath } : {}),
  425. });
  426. // Pre-fetch default collection names for REST endpoint
  427. const defaultCollectionNames = await store.getDefaultCollectionNames();
  428. // Session map: each client gets its own McpServer + Transport pair (MCP spec requirement).
  429. // The store is shared — it's stateless SQLite, safe for concurrent access.
  430. const sessions = new Map();
  431. async function createSession() {
  432. const transport = new WebStandardStreamableHTTPServerTransport({
  433. sessionIdGenerator: () => randomUUID(),
  434. enableJsonResponse: true,
  435. onsessioninitialized: (sessionId) => {
  436. sessions.set(sessionId, transport);
  437. log(`${ts()} New session ${sessionId} (${sessions.size} active)`);
  438. },
  439. });
  440. const server = await createMcpServer(store);
  441. await server.connect(transport);
  442. transport.onclose = () => {
  443. if (transport.sessionId) {
  444. sessions.delete(transport.sessionId);
  445. }
  446. };
  447. return transport;
  448. }
  449. const startTime = Date.now();
  450. const quiet = options?.quiet ?? false;
  451. /** Format timestamp for request logging */
  452. function ts() {
  453. return new Date().toISOString().slice(11, 23); // HH:mm:ss.SSS
  454. }
  455. /** Extract a human-readable label from a JSON-RPC body */
  456. function describeRequest(body) {
  457. const method = body?.method ?? "unknown";
  458. if (method === "tools/call") {
  459. const tool = body.params?.name ?? "?";
  460. const args = body.params?.arguments;
  461. // Show query string if present, truncated
  462. if (args?.query) {
  463. const q = String(args.query).slice(0, 80);
  464. return `tools/call ${tool} "${q}"`;
  465. }
  466. if (args?.path)
  467. return `tools/call ${tool} ${args.path}`;
  468. if (args?.pattern)
  469. return `tools/call ${tool} ${args.pattern}`;
  470. return `tools/call ${tool}`;
  471. }
  472. return method;
  473. }
  474. function log(msg) {
  475. if (!quiet)
  476. console.error(msg);
  477. }
  478. // Helper to collect request body
  479. async function collectBody(req) {
  480. const chunks = [];
  481. for await (const chunk of req)
  482. chunks.push(chunk);
  483. return Buffer.concat(chunks).toString();
  484. }
  485. const httpServer = createServer(async (nodeReq, nodeRes) => {
  486. const reqStart = Date.now();
  487. const pathname = nodeReq.url || "/";
  488. try {
  489. if (pathname === "/health" && nodeReq.method === "GET") {
  490. const body = JSON.stringify({ status: "ok", uptime: Math.floor((Date.now() - startTime) / 1000) });
  491. nodeRes.writeHead(200, { "Content-Type": "application/json" });
  492. nodeRes.end(body);
  493. log(`${ts()} GET /health (${Date.now() - reqStart}ms)`);
  494. return;
  495. }
  496. // REST endpoint: POST /search — structured search without MCP protocol
  497. // REST endpoint: POST /query (alias: /search) — structured search without MCP protocol
  498. if ((pathname === "/query" || pathname === "/search") && nodeReq.method === "POST") {
  499. const rawBody = await collectBody(nodeReq);
  500. const params = JSON.parse(rawBody);
  501. // Validate required fields
  502. if (!params.searches || !Array.isArray(params.searches)) {
  503. nodeRes.writeHead(400, { "Content-Type": "application/json" });
  504. nodeRes.end(JSON.stringify({ error: "Missing required field: searches (array)" }));
  505. return;
  506. }
  507. // Map to internal format
  508. const queries = params.searches.map((s) => ({
  509. type: s.type,
  510. query: String(s.query || ""),
  511. }));
  512. // Use default collections if none specified
  513. const effectiveCollections = params.collections ?? defaultCollectionNames;
  514. const results = await store.search({
  515. queries,
  516. collections: effectiveCollections.length > 0 ? effectiveCollections : undefined,
  517. limit: params.limit ?? 10,
  518. minScore: params.minScore ?? 0,
  519. intent: params.intent,
  520. });
  521. // Use first lex or vec query for snippet extraction
  522. const primaryQuery = params.searches.find((s) => s.type === 'lex')?.query
  523. || params.searches.find((s) => s.type === 'vec')?.query
  524. || params.searches[0]?.query || "";
  525. const formatted = results.map(r => {
  526. const { line, snippet } = extractSnippet(r.bestChunk, primaryQuery, 300);
  527. return {
  528. docid: `#${r.docid}`,
  529. file: r.displayPath,
  530. title: r.title,
  531. score: Math.round(r.score * 100) / 100,
  532. context: r.context,
  533. snippet: addLineNumbers(snippet, line),
  534. };
  535. });
  536. nodeRes.writeHead(200, { "Content-Type": "application/json" });
  537. nodeRes.end(JSON.stringify({ results: formatted }));
  538. log(`${ts()} POST /query ${params.searches.length} queries (${Date.now() - reqStart}ms)`);
  539. return;
  540. }
  541. if (pathname === "/mcp" && nodeReq.method === "POST") {
  542. const rawBody = await collectBody(nodeReq);
  543. const body = JSON.parse(rawBody);
  544. const label = describeRequest(body);
  545. const url = `http://localhost:${port}${pathname}`;
  546. const headers = {};
  547. for (const [k, v] of Object.entries(nodeReq.headers)) {
  548. if (typeof v === "string")
  549. headers[k] = v;
  550. }
  551. // Route to existing session or create new one on initialize
  552. const sessionId = headers["mcp-session-id"];
  553. let transport;
  554. if (sessionId) {
  555. const existing = sessions.get(sessionId);
  556. if (!existing) {
  557. nodeRes.writeHead(404, { "Content-Type": "application/json" });
  558. nodeRes.end(JSON.stringify({
  559. jsonrpc: "2.0",
  560. error: { code: -32001, message: "Session not found" },
  561. id: body?.id ?? null,
  562. }));
  563. return;
  564. }
  565. transport = existing;
  566. }
  567. else if (isInitializeRequest(body)) {
  568. transport = await createSession();
  569. }
  570. else {
  571. nodeRes.writeHead(400, { "Content-Type": "application/json" });
  572. nodeRes.end(JSON.stringify({
  573. jsonrpc: "2.0",
  574. error: { code: -32000, message: "Bad Request: Missing session ID" },
  575. id: body?.id ?? null,
  576. }));
  577. return;
  578. }
  579. const request = new Request(url, { method: "POST", headers, body: rawBody });
  580. const response = await transport.handleRequest(request, { parsedBody: body });
  581. nodeRes.writeHead(response.status, Object.fromEntries(response.headers));
  582. nodeRes.end(Buffer.from(await response.arrayBuffer()));
  583. log(`${ts()} POST /mcp ${label} (${Date.now() - reqStart}ms)`);
  584. return;
  585. }
  586. if (pathname === "/mcp") {
  587. const headers = {};
  588. for (const [k, v] of Object.entries(nodeReq.headers)) {
  589. if (typeof v === "string")
  590. headers[k] = v;
  591. }
  592. // GET/DELETE must have a valid session
  593. const sessionId = headers["mcp-session-id"];
  594. if (!sessionId) {
  595. nodeRes.writeHead(400, { "Content-Type": "application/json" });
  596. nodeRes.end(JSON.stringify({
  597. jsonrpc: "2.0",
  598. error: { code: -32000, message: "Bad Request: Missing session ID" },
  599. id: null,
  600. }));
  601. return;
  602. }
  603. const transport = sessions.get(sessionId);
  604. if (!transport) {
  605. nodeRes.writeHead(404, { "Content-Type": "application/json" });
  606. nodeRes.end(JSON.stringify({
  607. jsonrpc: "2.0",
  608. error: { code: -32001, message: "Session not found" },
  609. id: null,
  610. }));
  611. return;
  612. }
  613. const url = `http://localhost:${port}${pathname}`;
  614. const rawBody = nodeReq.method !== "GET" && nodeReq.method !== "HEAD" ? await collectBody(nodeReq) : undefined;
  615. const request = new Request(url, { method: nodeReq.method || "GET", headers, ...(rawBody ? { body: rawBody } : {}) });
  616. const response = await transport.handleRequest(request);
  617. nodeRes.writeHead(response.status, Object.fromEntries(response.headers));
  618. nodeRes.end(Buffer.from(await response.arrayBuffer()));
  619. return;
  620. }
  621. nodeRes.writeHead(404);
  622. nodeRes.end("Not Found");
  623. }
  624. catch (err) {
  625. console.error("HTTP handler error:", err);
  626. nodeRes.writeHead(500);
  627. nodeRes.end("Internal Server Error");
  628. }
  629. });
  630. await new Promise((resolve, reject) => {
  631. httpServer.on("error", reject);
  632. httpServer.listen(port, "localhost", () => resolve());
  633. });
  634. const actualPort = httpServer.address().port;
  635. let stopping = false;
  636. const stop = async () => {
  637. if (stopping)
  638. return;
  639. stopping = true;
  640. for (const transport of sessions.values()) {
  641. await transport.close();
  642. }
  643. sessions.clear();
  644. httpServer.close();
  645. await store.close();
  646. };
  647. process.on("SIGTERM", async () => {
  648. console.error("Shutting down (SIGTERM)...");
  649. await stop();
  650. process.exit(0);
  651. });
  652. process.on("SIGINT", async () => {
  653. console.error("Shutting down (SIGINT)...");
  654. await stop();
  655. process.exit(0);
  656. });
  657. log(`QMD MCP server listening on http://localhost:${actualPort}/mcp`);
  658. return { httpServer, port: actualPort, stop };
  659. }
  660. // Run if this is the main module
  661. if (fileURLToPath(import.meta.url) === process.argv[1] || process.argv[1]?.endsWith("/server.ts") || process.argv[1]?.endsWith("/server.js")) {
  662. startMcpServer().catch(console.error);
  663. }