diff --git a/.changeset/mcp-docs-fallback.md b/.changeset/mcp-docs-fallback.md new file mode 100644 index 00000000..e4143d17 --- /dev/null +++ b/.changeset/mcp-docs-fallback.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu-mcp": patch +--- + +If the project's docs don't load (a wrong `ONU_DOCS_DIR`, a malformed `index.json`, a missing page), the server now warns on stderr and serves its bundled docs instead of crashing. An empty `ONU_DOCS_DIR` counts as unset. diff --git a/.changeset/mcp-search-paths.md b/.changeset/mcp-search-paths.md new file mode 100644 index 00000000..9f5501b8 --- /dev/null +++ b/.changeset/mcp-search-paths.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu-mcp": patch +--- + +`onu_search_docs` and the closest-match hint in `onu_get_doc` now match page paths and the words of CamelCase titles, so `date-picker` finds DatePicker and "Button props" puts Button above SubmitButton. diff --git a/.changeset/no-tests-in-tarball.md b/.changeset/no-tests-in-tarball.md new file mode 100644 index 00000000..4b515049 --- /dev/null +++ b/.changeset/no-tests-in-tarball.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +The npm package no longer ships `src/styles/theme.test.ts`. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f58390de..65b16ca4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,6 +54,8 @@ jobs: run: node scripts/check-docs.mjs - name: Boost guidelines, skills and llms.txt run: node scripts/boost.mjs --check + - name: No test files in the npm tarballs + run: node scripts/check-pack.mjs - name: Licences run: node scripts/check-licenses.mjs - name: Audit diff --git a/AGENTS.md b/AGENTS.md index da0f57b1..13969a95 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,6 +29,7 @@ pnpm --filter @javaabu/onu-mcp test # MCP server tests pnpm build && pnpm --filter @javaabu/onu size # build + bundle budgets pnpm build:web # docs site node scripts/check-docs.mjs # every component has a docs page with Props + Accessibility +node scripts/check-pack.mjs # no test files in the npm tarballs pnpm e2e:chromium # Playwright (a11y with axe, visual) ``` diff --git a/docs/guides/ai-assistants.md b/docs/guides/ai-assistants.md index 1fd6c10b..ed4a5f75 100644 --- a/docs/guides/ai-assistants.md +++ b/docs/guides/ai-assistants.md @@ -59,7 +59,7 @@ Other clients (Cursor's `.cursor/mcp.json`, VS Code's `.vscode/mcp.json`, Claude } ``` -Set `ONU_DOCS_DIR` to read the docs from another folder. +Set `ONU_DOCS_DIR` to read the docs from another folder. If they don't load, the server warns on stderr and uses the docs it was published with. # Laravel Boost diff --git a/packages/onu-mcp/README.md b/packages/onu-mcp/README.md index 528b7c3e..428bd2b8 100644 --- a/packages/onu-mcp/README.md +++ b/packages/onu-mcp/README.md @@ -2,7 +2,7 @@ A [Model Context Protocol](https://modelcontextprotocol.io) server that gives AI assistants the docs of [Onu](https://github.com/Javaabu/onu) (`@javaabu/onu`), Javaabu's React UI library, and the rules for writing Onu code. -It reads the docs of the `@javaabu/onu` installed in your project (`node_modules/@javaabu/onu/docs`, looked up from the folder the assistant runs in and its parents), so answers match your version. Without one, it uses the docs it was published with. `ONU_DOCS_DIR` points it at another folder. +It reads the docs of the `@javaabu/onu` installed in your project (`node_modules/@javaabu/onu/docs`, looked up from the folder the assistant runs in and its parents), so answers match your version. Without one, it uses the docs it was published with. `ONU_DOCS_DIR` points it at another folder. If those docs don't load (a wrong folder, a broken `index.json`, a missing page), it warns on stderr and uses the docs it was published with. ## Tools diff --git a/packages/onu-mcp/src/docs.ts b/packages/onu-mcp/src/docs.ts index c76f12a1..a95cc0a2 100644 --- a/packages/onu-mcp/src/docs.ts +++ b/packages/onu-mcp/src/docs.ts @@ -51,19 +51,49 @@ export function findProjectDocs(from: string): string | undefined { /** * Loads the docs, preferring those of the version the project has installed - * (`ONU_DOCS_DIR`, then `node_modules/@javaabu/onu/docs` from `cwd` up), and - * falling back to the copy bundled with this package. + * (`dir`, then `ONU_DOCS_DIR`, then `node_modules/@javaabu/onu/docs` from `cwd` + * up). If there are none, or they don't load (a missing folder, a malformed + * `index.json`, a missing page), it uses the copy bundled with this package, + * with a warning on stderr. */ -export function loadDocs({ cwd = process.cwd(), dir }: { cwd?: string; dir?: string } = {}): Docs { - const projectDir = dir ?? process.env.ONU_DOCS_DIR ?? findProjectDocs(cwd) - const docsDir = projectDir ?? bundledDir - const index = JSON.parse(readFileSync(path.join(docsDir, "index.json"), "utf8")) as DocsIndex +export function loadDocs({ + cwd = process.cwd(), + dir, + bundled = bundledDir, +}: { cwd?: string; dir?: string; bundled?: string } = {}): Docs { + const projectDir = dir || process.env.ONU_DOCS_DIR || findProjectDocs(cwd) + if (projectDir) { + try { + return openDocs(projectDir, "project") + } catch (error) { + // stdout carries the MCP protocol, so warn on stderr. + console.error( + `onu-mcp: can't load the docs in ${projectDir} (${error instanceof Error ? error.message : String(error)}); using the bundled docs instead`, + ) + } + } + return openDocs(bundled, "bundled") +} + +/** Reads `index.json` in `docsDir` and checks that every page it lists is there. */ +function openDocs(docsDir: string, source: Docs["source"]): Docs { + const indexPath = path.join(docsDir, "index.json") + let index: DocsIndex + try { + index = JSON.parse(readFileSync(indexPath, "utf8")) as DocsIndex + } catch (error) { + throw new Error(`${indexPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error }) + } + if (!Array.isArray(index?.sections)) throw new Error(`${indexPath} has no sections`) + const pages = index.sections.flatMap((s) => s.pages ?? []) + const missing = pages.map((p) => path.join(docsDir, `${p.path}.md`)).find((file) => !existsSync(file)) + if (missing) throw new Error(`${missing} is missing`) const cache = new Map() return { index, - source: projectDir ? "project" : "bundled", + source, dir: docsDir, - pages: index.sections.flatMap((s) => s.pages), + pages, read(page) { let content = cache.get(page.path) if (content === undefined) { @@ -101,31 +131,50 @@ export interface SearchHit { snippet: string } -/** Pages matching every word of `query`, best first: title, then description, then body. */ +/** The words of a title or path: `DateRangePicker`, `date-range-picker` and `Date range picker` give `date`, `range`, `picker`. */ +const words = (s: string) => + s + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/([A-Z])([A-Z][a-z])/g, "$1 $2") + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter(Boolean) + +/** + * Pages matching every word of `query`, best first: title and path, then + * description, then body. A whole title word counts more than part of one, and + * a page whose title words all appear in the query ranks above the rest. + */ export function searchDocs(docs: Docs, query: string, limit = 8): SearchHit[] { - const words = query + const queryWords = query .toLowerCase() .split(/\s+/) .filter((w) => w.length > 1) - if (!words.length) return [] + if (!queryWords.length) return [] + const queryTokens = new Set(words(query)) const hits: SearchHit[] = [] for (const page of docs.pages) { - const title = page.title.toLowerCase() + const titleWords = words(page.title) + const nameWords = new Set([...titleWords, ...words(page.path.split("/").pop()!)]) + const names = `${page.title.toLowerCase()} ${titleWords.join(" ")} ${page.path}` const description = page.description.toLowerCase() const body = docs.read(page).toLowerCase() let score = 0 let all = true - for (const word of words) { + for (const word of queryWords) { const inBody = body.split(word).length - 1 - if (!inBody && !title.includes(word) && !description.includes(word)) { + const inNames = names.includes(word) + if (!inBody && !inNames && !description.includes(word)) { all = false break } - score += (title.includes(word) ? 20 : 0) + (description.includes(word) ? 5 : 0) + Math.min(inBody, 10) + score += + (nameWords.has(word) ? 30 : inNames ? 20 : 0) + (description.includes(word) ? 5 : 0) + Math.min(inBody, 10) } if (!all) continue - if (key(page.title) === key(query)) score += 100 - hits.push({ page, score, snippet: snippet(docs.read(page), words[0]!) }) + if (titleWords.every((w) => queryTokens.has(w))) score += 50 + if (key(page.title) === key(query) || key(page.path.split("/").pop()!) === key(query)) score += 100 + hits.push({ page, score, snippet: snippet(docs.read(page), queryWords[0]!) }) } return hits.sort((a, b) => b.score - a.score).slice(0, limit) } diff --git a/packages/onu-mcp/src/server.test.ts b/packages/onu-mcp/src/server.test.ts index 4334e686..dd63d3cd 100644 --- a/packages/onu-mcp/src/server.test.ts +++ b/packages/onu-mcp/src/server.test.ts @@ -1,10 +1,10 @@ -import { mkdtempSync, rmSync } from "node:fs" +import { cpSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import path from "node:path" import { Client } from "@modelcontextprotocol/sdk/client/index.js" import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js" -import { afterAll, beforeAll, describe, expect, it } from "vitest" +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest" import { writeLlms } from "../../../scripts/llms.mjs" import { findDoc, findProjectDocs, loadDocs, searchDocs, type Docs } from "./docs.js" @@ -57,12 +57,80 @@ describe("searchDocs", () => { }) it("needs every word to match", () => expect(searchDocs(docs, "thaana xylophone")).toEqual([])) + + it("matches the page path", () => { + const top = searchDocs(docs, "date-picker", 5).map((h) => h.page.path) + expect(top[0]).toBe("date-and-time/date-picker") + }) + + it("matches the words of a CamelCase title", () => { + expect(searchDocs(docs, "password input")[0]?.page.path).toBe("text-inputs/password-input") + }) + + it("ranks an exact title word above a title that only contains it", () => { + expect(searchDocs(docs, "Button props")[0]?.page.path).toBe("form-scaffolding/button") + }) }) describe("findProjectDocs", () => { it("finds nothing outside a project that installs Onu", () => expect(findProjectDocs(tmpdir())).toBeUndefined()) }) +describe("loadDocs", () => { + const bundled = () => path.join(out, "docs") + const projectCopy = () => { + const dir = mkdtempSync(path.join(tmpdir(), "onu-mcp-project-")) + cpSync(bundled(), dir, { recursive: true }) + return dir + } + let stderr: ReturnType + beforeAll(() => { + stderr = vi.spyOn(console, "error").mockImplementation(() => {}) + }) + afterEach(() => { + stderr.mockClear() + vi.unstubAllEnvs() + }) + afterAll(() => stderr.mockRestore()) + + it("falls back to the bundled docs when the folder doesn't exist", () => { + const loaded = loadDocs({ dir: path.join(out, "no-such-folder"), bundled: bundled() }) + expect(loaded.source).toBe("bundled") + expect(loaded.pages.length).toBe(docs.pages.length) + expect(stderr).toHaveBeenCalledWith(expect.stringContaining("no-such-folder")) + }) + + it("falls back to the bundled docs when index.json is malformed", () => { + const dir = projectCopy() + writeFileSync(path.join(dir, "index.json"), "{ not json") + expect(loadDocs({ dir, bundled: bundled() }).source).toBe("bundled") + expect(stderr).toHaveBeenCalledWith(expect.stringContaining("index.json")) + rmSync(dir, { recursive: true, force: true }) + }) + + it("falls back to the bundled docs when a page is missing", () => { + const dir = projectCopy() + unlinkSync(path.join(dir, "text-inputs/password-input.md")) + const loaded = loadDocs({ dir, bundled: bundled() }) + expect(loaded.source).toBe("bundled") + expect(searchDocs(loaded, "password").length).toBeGreaterThan(0) + expect(stderr).toHaveBeenCalledWith(expect.stringContaining("password-input.md")) + rmSync(dir, { recursive: true, force: true }) + }) + + it("treats an empty ONU_DOCS_DIR as unset", () => { + vi.stubEnv("ONU_DOCS_DIR", "") + const loaded = loadDocs({ cwd: tmpdir(), bundled: bundled() }) + expect(loaded.source).toBe("bundled") + expect(loaded.dir).toBe(bundled()) + }) + + it("reports nothing when the project docs load", () => { + expect(loadDocs({ dir: bundled(), bundled: bundled() }).source).toBe("project") + expect(stderr).not.toHaveBeenCalled() + }) +}) + describe("server", () => { it("lists the tools", async () => { const { tools } = await client.listTools() diff --git a/packages/onu/package.json b/packages/onu/package.json index 9eac9e8d..63216221 100644 --- a/packages/onu/package.json +++ b/packages/onu/package.json @@ -33,6 +33,7 @@ "files": [ "dist", "src/styles", + "!src/**/*.test.*", "docs", "llms.txt", "llms-full.txt", diff --git a/scripts/check-pack.mjs b/scripts/check-pack.mjs new file mode 100644 index 00000000..2bd11df2 --- /dev/null +++ b/scripts/check-pack.mjs @@ -0,0 +1,30 @@ +#!/usr/bin/env node +/** + * Fails if a published package's npm tarball would ship test files (`*.test.ts`, + * `*.spec.tsx`, `__tests__/`), which a broad `files` entry such as `src/styles` + * picks up. Asks `pnpm pack --dry-run`, the same file list `pnpm publish` uses. + * + * node scripts/check-pack.mjs + */ +import { execFileSync } from "node:child_process" +import { readdirSync, readFileSync } from "node:fs" +import path from "node:path" + +const root = path.resolve(import.meta.dirname, "..") +const isTest = (file) => /(^|\/)__tests__\/|\.(test|spec)\.[cm]?[jt]sx?$/.test(file) + +const found = [] +for (const entry of readdirSync(path.join(root, "packages"), { withFileTypes: true })) { + if (!entry.isDirectory()) continue + const dir = path.join(root, "packages", entry.name) + const pkg = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")) + if (pkg.private) continue + const { files } = JSON.parse(execFileSync("pnpm", ["pack", "--dry-run", "--json"], { cwd: dir, encoding: "utf8" })) + for (const { path: file } of files) if (isTest(file)) found.push(`${pkg.name}: ${file}`) +} + +if (found.length) { + console.error(`These test files would ship in the npm tarball; exclude them in "files":\n${found.join("\n")}`) + process.exit(1) +} +console.log("No package ships test files.")