Skip to content

MCP documentation tools: list_docs, get_doc (bounded chunks) and search_docs over the docs site #2601

Closed

Description

@propr-dev

Context

MCP clients have no way to read ProPR's own documentation. When a user asks "what can ProPR do?" or "how does ultrafix decide to stop?", the agent guesses from tool names. The published documentation site lives in the repository under docs/ (Docusaurus): pages in docs/docs/** (.md and .mdx), navigation in docs/sidebars.ts. Some operator-facing MCP guides also live at docs/mcp.md, docs/mcp-coverage.md, docs/mcp-operator-surface.md.

Requirements

  1. New read-only tools (scope read, no repository argument, no GitHub access):
    • list_docs — { section?: string, offset, limit ≤ 100 } → { docsVersion, pages: [{ path, title, section, summary, words }], nextOffset }. path is a stable slug like features/pr-commands (relative to docs/docs, no extension); extra MCP guides appear under mcp/… (mcp/guide, mcp/coverage, mcp/operator-surface). section is the first path segment (features, operations, architecture, tutorials, mcp, …). summary is the first paragraph after the title, max 240 chars.
    • get_doc — { path, offset = 0, maxChars = 8000 (1000..16000), section?: heading } → { path, title, docsVersion, outline: [{ level, heading, offset }], content, offset, nextOffset, totalChars }. section returns only the content under the given heading (case-insensitive exact heading match) so a client can jump to a subsection without paging. Chunks break at a paragraph boundary when possible.
    • search_docs — { query (2..200 chars), limit ≤ 20 } → { results: [{ path, title, heading, snippet, score }] }: case-insensitive term scoring over titles (×5), headings (×3) and body (×1), results grouped per (page, heading) so the caller can call get_doc with section. Snippets ≤ 300 chars around the first match.
  2. Content normalisation: strip front matter, strip MDX comments {/* ... */} (used for screenshot placeholders), strip import ... from lines, keep code fences and tables as-is. Docusaurus admonitions (:::warning[...]) are kept as text.
  3. Safety: only files discovered under the configured docs roots are served. path is looked up in the in-memory index; it is never joined onto a filesystem path, so traversal (../) is impossible by construction. Files over 512 KiB are skipped. Symlinks are not followed.
  4. Index: built lazily on first use and cached; rebuilt when the docs root's newest mtime changes (checked at most once per 60 s). Order pages by docs/sidebars.ts order when the manifest from the packaging issue is present; otherwise by sidebar_position front matter then path.
  5. Docs root resolution: PROPR_DOCS_DIR env → <cwd>/docs → /app/docs (the image path added in the packaging issue). If none exists, the tools fail with DOCS_UNAVAILABLE (stage internal, not retryable, message explains the operator must run an image that bundles docs or set PROPR_DOCS_DIR).
  6. docsVersion is the @propr/api package version unless a docs manifest supplies { version, sourceRevision } (next issue).
  7. Resource propr://instances/{instance_id}/docs/{path} serving the first chunk, and prompt text in operator_briefing mentions search_docs for "how does X work" questions.

Implementation Specification

  • New packages/api/mcp/docsIndex.ts (discovery, parsing, caching, chunking, search — no MCP types).
  • New packages/api/mcp/toolsDocs.ts registering the three tools; wire addDocsTools(tools, deps) in createToolCatalog.
  • Register the resource in packages/api/mcp/server.ts.
  • Tests packages/api/test/mcpDocs.test.ts using a temporary docs directory via PROPR_DOCS_DIR.

Acceptance Criteria

  • list_docs({ section: 'features' }) includes features/pr-commands with title "PR Comment Commands".
  • get_doc({ path: 'features/pr-commands', section: '/ultrafix' }) returns only that subsection.
  • Paging get_doc with nextOffset reconstructs the full normalised page exactly, and no chunk exceeds maxChars.
  • search_docs({ query: 'ultrafix goal' }) ranks features/pr-commands first.
  • get_doc({ path: '../../etc/passwd' }) returns DOC_NOT_FOUND.
  • MDX comments and front matter never appear in content.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The docs are plain Markdown already versioned with the code, so we serve them directly from disk via an in-memory index rather than scraping the rendered Docusaurus site (which would need the docs container running and HTML-to-text conversion) or embedding them in a vector store (heavy, and unnecessary for a few hundred pages — term scoring over headings is good enough to route a client to the right get_doc section).

    Lookups are by index key, never by joining user input onto a path, which makes traversal impossible by construction. Output is chunked with explicit nextOffset so a large page cannot flood a client's context.

    File: packages/api/mcp/docsIndex.ts (new file)

    Why this file: Pure docs indexing/search logic, testable without the MCP server.

    import { readdirSync, readFileSync, statSync, existsSync, lstatSync } from 'node:fs';
    import path from 'node:path';
    import packageInfo from '../package.json' with { type: 'json' };
    
    export interface DocHeading { level: number; heading: string; offset: number }
    export interface DocPage { path: string; title: string; section: string; summary: string; words: number; order: number; content: string; outline: DocHeading[] }
    export interface DocsIndex { root: string; version: string; sourceRevision: string | null; pages: DocPage[]; byPath: Map<string, DocPage>; builtAt: number; newestMtime: number }
    
    const MAX_FILE_BYTES = 512 * 1024;
    const REFRESH_CHECK_MS = 60_000;
    // Operator guides that live beside the Docusaurus tree.
    const EXTRA_PAGES: Record<string, string> = { 'mcp/guide': 'mcp.md', 'mcp/coverage': 'mcp-coverage.md', 'mcp/operator-surface': 'mcp-operator-surface.md' };
    
    export function resolveDocsRoot(): string | null {
      const candidates = [process.env.PROPR_DOCS_DIR, path.resolve(process.cwd(), 'docs'), '/app/docs'].filter(Boolean) as string[];
      return candidates.find(candidate => existsSync(path.join(candidate, 'docs'))) ?? null;
    }
    
    /** Strip Docusaurus/MDX-only syntax that is noise for an agent. */
    export function normalizeMarkdown(raw: string): { body: string; frontMatter: Record<string, string> } {
      const frontMatter: Record<string, string> = {};
      let body = raw.replace(/^---\n([\s\S]*?)\n---\n?/, (_, block: string) => {
        for (const line of block.split('\n')) {
          const match = /^([\w-]+):\s*(.*)$/.exec(line);
          if (match) frontMatter[match[1]] = match[2].replace(/^['"]|['"]$/g, '');
        }
        return '';
      });
      body = body.replace(/\{\/\*[\s\S]*?\*\/\}/g, '')          // MDX comments (screenshot placeholders)
        .replace(/^import\s.+from\s.+;?\s*$/gm, '')             // MDX imports
        .replace(/\n{3,}/g, '\n\n')
        .trim();
      return { body, frontMatter };
    }
    
    function outlineOf(body: string): DocHeading[] {
      const outline: DocHeading[] = [];
      let inFence = false;
      let offset = 0;
      for (const line of body.split('\n')) {
        if (line.startsWith('```') || line.startsWith('~~~')) inFence = !inFence;
        const match = !inFence && /^(#{1,4})\s+(.+?)\s*#*$/.exec(line);
        if (match) outline.push({ level: match[1].length, heading: match[2].replace(/`/g, ''), offset });
        offset += line.length + 1;
      }
      return outline;
    }
    
    function pageFrom(key: string, file: string, order: number): DocPage | null {
      const stat = lstatSync(file);
      if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return null; // no symlinks, bounded size
      const { body, frontMatter } = normalizeMarkdown(readFileSync(file, 'utf8'));
      const outline = outlineOf(body);
      const title = frontMatter.title || outline.find(h => h.level === 1)?.heading || key.split('/').pop()!;
      const firstParagraph = body.split(/\n\n/).find(block => block.trim() && !block.startsWith('#')) ?? '';
      return { path: key, title, section: key.split('/')[0], words: body.split(/\s+/).length, content: body, outline,
        summary: firstParagraph.replace(/\s+/g, ' ').slice(0, 240), order: Number(frontMatter.sidebar_position ?? order) };
    }
    
    function walk(directory: string, prefix: string, out: Array<[string, string]>): void {
      for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
        if (entry.isSymbolicLink()) continue;
        const full = path.join(directory, entry.name);
        if (entry.isDirectory()) walk(full, `${prefix}${entry.name}/`, out);
        else if (/\.mdx?$/.test(entry.name)) out.push([`${prefix}${entry.name.replace(/\.mdx?$/, '')}`, full]);
      }
    }
    
    function newestMtime(root: string): number {
      return statSync(path.join(root, 'docs')).mtimeMs; // directory mtime changes when pages are added/removed
    }
    
    let cached: DocsIndex | null = null;
    let lastCheck = 0;
    
    export function loadDocsIndex(now = Date.now()): DocsIndex | null {
      const root = resolveDocsRoot();
      if (!root) return null;
      if (cached && cached.root === root && now - lastCheck < REFRESH_CHECK_MS) return cached;
      lastCheck = now;
      const mtime = newestMtime(root);
      if (cached && cached.root === root && cached.newestMtime === mtime) return cached;
      const files: Array<[string, string]> = [];
      walk(path.join(root, 'docs'), '', files);
      for (const [key, file] of Object.entries(EXTRA_PAGES)) if (existsSync(path.join(root, file))) files.push([key, path.join(root, file)]);
      const manifest = readManifest(root);
      const pages = files.map(([key, file], index) => pageFrom(key, file, index)).filter((page): page is DocPage => !!page);
      const orderOf = (page: DocPage) => manifest?.order.indexOf(page.path) ?? -1;
      pages.sort((a, b) => (orderOf(a) === -1 ? 1e6 : orderOf(a)) - (orderOf(b) === -1 ? 1e6 : orderOf(b)) || a.section.localeCompare(b.section) || a.order - b.order || a.path.localeCompare(b.path));
      cached = { root, pages, byPath: new Map(pages.map(page => [page.path, page])), builtAt: now, newestMtime: mtime,
        version: manifest?.version ?? packageInfo.version, sourceRevision: manifest?.sourceRevision ?? null };
      return cached;
    }
    
    /** Optional build-time manifest (see the docs packaging issue). */
    function readManifest(root: string): { version: string; sourceRevision: string | null; order: string[] } | null {
      try { return JSON.parse(readFileSync(path.join(root, 'docs-manifest.json'), 'utf8')); } catch { return null; }
    }
    
    export function resetDocsIndexForTests(): void { cached = null; lastCheck = 0; }
    
    /** Restrict content to one heading's subtree. */
    export function sectionContent(page: DocPage, heading: string): string | null {
      const index = page.outline.findIndex(h => h.heading.toLowerCase() === heading.trim().toLowerCase());
      if (index === -1) return null;
      const start = page.outline[index];
      const next = page.outline.slice(index + 1).find(h => h.level <= start.level);
      return page.content.slice(start.offset, next?.offset ?? page.content.length).trim();
    }
    
    /** Chunk at a paragraph boundary when one exists in the last quarter of the window. */
    export function chunk(text: string, offset: number, maxChars: number): { content: string; nextOffset: number | null } {
      if (offset >= text.length) return { content: '', nextOffset: null };
      let end = Math.min(offset + maxChars, text.length);
      if (end < text.length) {
        const boundary = text.lastIndexOf('\n\n', end);
        if (boundary > offset + maxChars * 0.75) end = boundary + 2;
      }
      return { content: text.slice(offset, end), nextOffset: end < text.length ? end : null };
    }
    
    export function searchDocs(index: DocsIndex, query: string, limit: number) {
      const terms = query.toLowerCase().split(/\W+/).filter(term => term.length >= 2).slice(0, 10);
      const results: Array<{ path: string; title: string; heading: string | null; snippet: string; score: number }> = [];
      for (const page of index.pages) {
        // Score per heading section so the caller can open exactly that section.
        const sections = page.outline.length ? page.outline.map((h, i) => ({ heading: h.heading,
          text: page.content.slice(h.offset, page.outline[i + 1]?.offset ?? page.content.length) })) : [{ heading: null, text: page.content }];
        for (const section of sections) {
          const lowerText = section.text.toLowerCase();
          let score = 0;
          for (const term of terms) {
            if (page.title.toLowerCase().includes(term)) score += 5;
            if (section.heading?.toLowerCase().includes(term)) score += 3;
            score += Math.min(lowerText.split(term).length - 1, 5);
          }
          if (score === 0 || !terms.every(term => lowerText.includes(term) || page.title.toLowerCase().includes(term))) continue;
          const at = Math.max(0, lowerText.indexOf(terms[0]) - 80);
          results.push({ path: page.path, title: page.title, heading: section.heading, score,
            snippet: section.text.slice(at, at + 300).replace(/\s+/g, ' ').trim() });
        }
      }
      return results.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).slice(0, limit);
    }

    File: packages/api/mcp/toolsDocs.ts (new file)

    Why this file: MCP-facing wrappers (schemas, errors, bounds) around the pure index.

    import { z } from 'zod';
    import { McpError } from './config.js';
    import { chunk, loadDocsIndex, searchDocs, sectionContent } from './docsIndex.js';
    import { type McpTool, type ToolDeps, ok } from './tools.js';
    
    const pathSchema = z.string().regex(/^[a-z0-9][a-z0-9/_-]{0,200}$/i).describe('Page path from list_docs, e.g. features/pr-commands');
    
    function requireIndex() {
      const index = loadDocsIndex();
      if (!index) throw new McpError('DOCS_UNAVAILABLE', 'Documentation is not bundled with this instance. Run an image that includes docs or set PROPR_DOCS_DIR.', 503,
        { stage: 'internal', retryable: false });
      return index;
    }
    
    export function addDocsTools(tools: McpTool[], _deps: ToolDeps): void {
      tools.push({ name: 'list_docs', description: "List ProPR's documentation pages (the published docs site shipped with this instance) with titles and one-line summaries. Use search_docs to find a topic and get_doc to read it.", scope: 'read', readOnly: true,
        schema: z.object({ section: z.string().regex(/^[a-z0-9-]{1,40}$/).optional(), offset: z.number().int().min(0).max(5000).default(0),
          limit: z.number().int().min(1).max(100).default(50) }).strict(),
        run: async ({ args }) => {
          const index = requireIndex();
          const pages = index.pages.filter(page => !args.section || page.section === args.section);
          return ok({ docsVersion: index.version, sourceRevision: index.sourceRevision, sections: [...new Set(index.pages.map(p => p.section))],
            pages: pages.slice(args.offset, args.offset + args.limit).map(({ path, title, section, summary, words }) => ({ path, title, section, summary, words })),
            nextOffset: args.offset + args.limit < pages.length ? args.offset + args.limit : null });
        } });
      tools.push({ name: 'get_doc', description: 'Read one documentation page in bounded chunks. Pass section (a heading from outline) to read just that part; follow nextOffset for more.', scope: 'read', readOnly: true,
        schema: z.object({ path: pathSchema, section: z.string().min(1).max(200).optional(), offset: z.number().int().min(0).max(5_000_000).default(0),
          maxChars: z.number().int().min(1000).max(16000).default(8000) }).strict(),
        run: async ({ args }) => {
          const index = requireIndex();
          // Lookup by key only; the input never becomes a filesystem path.
          const page = index.byPath.get(args.path);
          if (!page) throw new McpError('DOC_NOT_FOUND', `No documentation page "${args.path}". Use list_docs or search_docs.`, 404, { stage: 'validation' });
          const text = args.section ? sectionContent(page, args.section) : page.content;
          if (text == null) throw new McpError('DOC_SECTION_NOT_FOUND', `Page ${page.path} has no heading "${args.section}".`, 404,
            { stage: 'validation', details: { headings: page.outline.map(h => h.heading).slice(0, 50) } });
          const { content, nextOffset } = chunk(text, args.offset, args.maxChars);
          return ok({ path: page.path, title: page.title, docsVersion: index.version, outline: args.offset === 0 ? page.outline : undefined,
            content, offset: args.offset, nextOffset, totalChars: text.length });
        } });
      tools.push({ name: 'search_docs', description: 'Search ProPR documentation by keywords. Results name the page and heading to open with get_doc (path + section).', scope: 'read', readOnly: true,
        schema: z.object({ query: z.string().min(2).max(200), limit: z.number().int().min(1).max(20).default(8) }).strict(),
        run: async ({ args }) => { const index = requireIndex(); return ok({ docsVersion: index.version, results: searchDocs(index, args.query, args.limit) }); } });
    }

    Register in packages/api/mcp/tools.ts:

    +import { addDocsTools } from './toolsDocs.js';
    @@
       addActivityTools(tools, deps);
    +  addDocsTools(tools, deps);

    File: packages/api/mcp/server.ts

    Why this file: Adds the docs/{path} resource next to existing resources, reading through get_doc so bounds and errors are identical.

    // propr://instances/{instance_id}/docs/{+path}  ->  executeTool('get_doc', { path }) and return content as text/markdown

    File: packages/api/test/mcpDocs.test.ts (new file)

    Why this file: Exercises discovery, normalisation, chunking, section selection, search ranking and traversal safety against a temp docs tree.

    import assert from 'node:assert/strict';
    import { test } from 'node:test';
    import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
    import { tmpdir } from 'node:os';
    import path from 'node:path';
    import { chunk, loadDocsIndex, resetDocsIndexForTests, searchDocs, sectionContent } from '../mcp/docsIndex.js';
    
    test('docs index normalises, chunks and searches', async () => {
      const root = await mkdtemp(path.join(tmpdir(), 'propr-docs-'));
      try {
        await mkdir(path.join(root, 'docs', 'features'), { recursive: true });
        await writeFile(path.join(root, 'docs', 'features', 'pr-commands.md'),
          `---\ntitle: PR Comment Commands\n---\n\n# PR Comment Commands\n\nIntro.\n\n{/* SCREENSHOT PLACEHOLDER */}\n\n### \`/ultrafix\`\n\nAlternates review and fix until the goal score.\n\n### \`/merge\`\n\nMerges base.\n`);
        process.env.PROPR_DOCS_DIR = root;
        resetDocsIndexForTests();
        const index = loadDocsIndex()!;
        const page = index.byPath.get('features/pr-commands')!;
        assert.equal(page.title, 'PR Comment Commands');
        assert.ok(!page.content.includes('SCREENSHOT') && !page.content.includes('---'));
        assert.match(sectionContent(page, '/ultrafix')!, /goal score/);
        assert.ok(!sectionContent(page, '/ultrafix')!.includes('Merges base'));
        let offset: number | null = 0; let rebuilt = '';
        while (offset !== null) { const part = chunk(page.content, offset, 40); assert.ok(part.content.length <= 40); rebuilt += part.content; offset = part.nextOffset; }
        assert.equal(rebuilt, page.content);
        assert.equal(searchDocs(index, 'ultrafix goal', 5)[0].path, 'features/pr-commands');
        assert.equal(index.byPath.get('../../etc/passwd'), undefined);
      } finally { delete process.env.PROPR_DOCS_DIR; await rm(root, { recursive: true, force: true }); }
    });
  2. propr-dev commented on Sep 29, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 2601/gpt-5.6-sol-mcp-documentation-tools-l-20260929-1902-7rp
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2601-20260929-1902-gpt-5.6-sol-7rp

    🔍 Track Task Execution

  3. added a commit that references this issue on Sep 29, 2026
  4. added a commit that references this issue on Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions