Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mcp-docs-fallback.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/mcp-search-paths.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/no-tests-in-tarball.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

The npm package no longer ships `src/styles/theme.test.ts`.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
```

Expand Down
2 changes: 1 addition & 1 deletion docs/guides/ai-assistants.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion packages/onu-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
83 changes: 66 additions & 17 deletions packages/onu-mcp/src/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>()
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) {
Expand Down Expand Up @@ -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)
}
Expand Down
72 changes: 70 additions & 2 deletions packages/onu-mcp/src/server.test.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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<typeof vi.spyOn>
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()
Expand Down
1 change: 1 addition & 0 deletions packages/onu/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"files": [
"dist",
"src/styles",
"!src/**/*.test.*",
"docs",
"llms.txt",
"llms-full.txt",
Expand Down
30 changes: 30 additions & 0 deletions scripts/check-pack.mjs
Original file line number Diff line number Diff line change
@@ -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.")
Loading