Skip to content

solidworks_mcp.doc_links.llms_txt

solidworks_mcp.doc_links.llms_txt

Build docs/llms.txt from the docs, and check a committed copy.

The file follows the llms.txt format: a # title, a > summary, then ## sections of - [title](url): summary entries. Every title and summary is copied word for word from the page it links to (see :func:.pages.opening), and the same content rules hold for the builder and the checker, so a hand edit can't match a bad build.

Attributes

BUILD_COMMAND module-attribute

BUILD_COMMAND = 'python -m solidworks_mcp.doc_links build'

LLMS_TXT module-attribute

LLMS_TXT = Path('docs/llms.txt')

_CODE_SPAN module-attribute

_CODE_SPAN = re.compile('(`+).+?\\1')

_ENTRY module-attribute

_ENTRY = re.compile('^- \\[(?P<title>[^\\]]+)\\]\\((?P<url>\\S+)\\): (?P<summary>\\S.*)$')

_HTML module-attribute

_HTML = re.compile('<(?:[A-Za-z/]|!--)')

_SHAPES module-attribute

_SHAPES = (re.compile('^# \\S.*$'), re.compile('^> \\S.*$'), re.compile('^## \\S.*$'), _ENTRY, re.compile('^$'))

_URL module-attribute

_URL = re.compile('[a-z][a-z0-9+.-]*://[^\\s)>\\]]+', re.IGNORECASE)

Classes

DocsError

Bases: Exception

A page can't give what llms.txt needs from it (names the page).

Entry dataclass

Entry(section: str, page: str, title: str, url: str, summary: str)

One page's line in llms.txt.

Attributes:

Name Type Description
section str

Its ## section.

page str

The page's path under docs/.

title str

The page's title.

url str

The page's published URL.

summary str

The page's opening paragraph.

Attributes
line property
line: str

The entry as it appears in the file.

Site dataclass

Site(name: str, description: str, url: str, repo_url: str, nav: list[Any])

The settings llms.txt and the link checks use.

Attributes:

Name Type Description
name str

site_name.

description str

site_description.

url str

site_url, without a trailing slash.

repo_url str

repo_url, without a trailing slash.

nav list[Any]

The nav as written in mkdocs.yml.

Functions:

_entry_differences

_entry_differences(committed: str, expected: list[Entry]) -> list[str]

Entries whose title or summary differs from the page, or are missing/extra.

Source code in src/solidworks_mcp/doc_links/llms_txt.py
def _entry_differences(committed: str, expected: list[Entry]) -> list[str]:
    """Entries whose title or summary differs from the page, or are missing/extra."""
    found: dict[str, tuple[int, str, str]] = {}
    for number, line in enumerate(committed.split("\n"), start=1):
        match = _ENTRY.match(line)
        if match:
            found[match["url"]] = (number, match["title"], match["summary"])
    problems: list[str] = []
    for entry in expected:
        if entry.url not in found:
            problems.append(
                f"{LLMS_TXT}: no entry for {entry.page}; run `{BUILD_COMMAND}`"
            )
            continue
        number, title, summary = found.pop(entry.url)
        for field, want, got in (
            ("title", entry.title, title),
            ("summary", entry.summary, summary),
        ):
            if want != got:
                problems.append(
                    f"{LLMS_TXT}:{number}: the {field} doesn't match {entry.page}\n"
                    f"  expected: {want}\n  found:    {got}"
                )
    for url, (number, _title, _summary) in found.items():
        problems.append(
            f"{LLMS_TXT}:{number}: {url} is not a page in the nav; "
            f"run `{BUILD_COMMAND}`"
        )
    return problems

_first_difference

_first_difference(committed: str, expected: str) -> str

The first line where the committed file and a fresh build differ.

Source code in src/solidworks_mcp/doc_links/llms_txt.py
def _first_difference(committed: str, expected: str) -> str:
    """The first line where the committed file and a fresh build differ."""
    have, want = committed.split("\n"), expected.split("\n")
    for number, (got, line) in enumerate(zip(have, want, strict=False), start=1):
        if got != line:
            return (
                f"{LLMS_TXT}:{number}: out of date (expected {line!r}, found "
                f"{got!r}); run `{BUILD_COMMAND}`"
            )
    return (
        f"{LLMS_TXT}:{min(len(have), len(want)) + 1}: out of date (the file is "
        f"{'longer' if len(have) > len(want) else 'shorter'} than a fresh build); "
        f"run `{BUILD_COMMAND}`"
    )

_ours

_ours(url: str, site: Site) -> bool

Whether url is the docs site or this repository.

Source code in src/solidworks_mcp/doc_links/llms_txt.py
def _ours(url: str, site: Site) -> bool:
    """Whether ``url`` is the docs site or this repository."""
    return any(
        url == base or url.startswith(base + "/") for base in (site.url, site.repo_url)
    )

build

build(root: Path) -> str

The text of llms.txt for the docs under root.

Parameters:

Name Type Description Default
root Path

The repository root.

required

Returns:

Type Description
str

The file's text, ending in a newline.

Raises:

Type Description
DocsError

As :func:entries, or when the site name or description breaks a content rule.

Source code in src/solidworks_mcp/doc_links/llms_txt.py
def build(root: Path) -> str:
    """The text of ``llms.txt`` for the docs under ``root``.

    Args:
        root: The repository root.

    Returns:
        The file's text, ending in a newline.

    Raises:
        DocsError: As :func:`entries`, or when the site name or
            description breaks a content rule.
    """
    site = load_site(root)
    lines = [f"# {site.name}", "", f"> {site.description}"]
    section = None
    for entry in entries(root, site):
        if entry.section != section:
            section = entry.section
            lines += ["", f"## {section}", ""]
        lines.append(entry.line)
    for line in lines[:3]:
        problems = line_problems(line, site)
        if problems:
            raise DocsError(f"mkdocs.yml: {problems[0]}")
    return "\n".join(lines) + "\n"

check

check(root: Path, committed: str | None = None) -> list[str]

Problems with the committed llms.txt; empty when it is right.

Parameters:

Name Type Description Default
root Path

The repository root.

required
committed str | None

The file's text; read from docs/llms.txt when omitted.

None

Returns:

Type Description
list[str]

One message per problem: a content rule broken (with its line

list[str]

number), an entry whose title or summary differs from its page

list[str]

(with the expected and the found text), a page missing or extra,

list[str]

or else the first line that differs. Each ends by naming the

list[str]

rebuild command when the fix is a rebuild.

Source code in src/solidworks_mcp/doc_links/llms_txt.py
def check(root: Path, committed: str | None = None) -> list[str]:
    """Problems with the committed ``llms.txt``; empty when it is right.

    Args:
        root: The repository root.
        committed: The file's text; read from ``docs/llms.txt`` when omitted.

    Returns:
        One message per problem: a content rule broken (with its line
        number), an entry whose title or summary differs from its page
        (with the expected and the found text), a page missing or extra,
        or else the first line that differs. Each ends by naming the
        rebuild command when the fix is a rebuild.
    """
    site = load_site(root)
    if committed is None:
        path = root / LLMS_TXT
        if not path.is_file():
            return [f"{LLMS_TXT} is missing; run `{BUILD_COMMAND}`"]
        committed = path.read_text(encoding="utf-8")
    problems = [
        f"{LLMS_TXT}:{number}: {problem}"
        for number, line in enumerate(committed.split("\n"), start=1)
        for problem in line_problems(line, site)
    ]
    try:
        expected = build(root)
    except DocsError as error:
        return [*problems, str(error)]
    if committed == expected:
        return problems
    problems += _entry_differences(committed, entries(root, site))
    if not problems:
        problems.append(_first_difference(committed, expected))
    return problems

entries

entries(root: Path, site: Site | None = None) -> list[Entry]

Every nav page's entry, in nav order.

Parameters:

Name Type Description Default
root Path

The repository root.

required
site Site | None

The site settings, read from mkdocs.yml when omitted.

None

Returns:

Type Description
list[Entry]

The entries.

Raises:

Type Description
DocsError

When a page has no title or opening paragraph, or its title or opening breaks a content rule.

Source code in src/solidworks_mcp/doc_links/llms_txt.py
def entries(root: Path, site: Site | None = None) -> list[Entry]:
    """Every nav page's entry, in nav order.

    Args:
        root: The repository root.
        site: The site settings, read from ``mkdocs.yml`` when omitted.

    Returns:
        The entries.

    Raises:
        DocsError: When a page has no title or opening paragraph, or its
            title or opening breaks a content rule.
    """
    site = site or load_site(root)
    docs = root / "docs"
    found: list[Entry] = []
    for page in nav_pages(site.nav, docs):
        start = opening((docs / page.path).read_text(encoding="utf-8"), page.path)
        entry = Entry(
            page.section,
            page.path,
            start.title,
            page_url(site.url, page.path),
            start.summary,
        )
        problems = line_problems(entry.line, site)
        if problems:
            raise DocsError(f"{page.path}: {problems[0]}")
        found.append(entry)
    return found

line_problems

line_problems(line: str, site: Site) -> list[str]

What is wrong with one line of llms.txt, if anything.

The rules (spec docs/llms-txt): one of the allowed shapes; every URL under site_url or repo_url; no control or format characters (zero-width, byte-order mark, bidirectional controls); no HTML tag or comment outside code spans.

Parameters:

Name Type Description Default
line str

The line, without its line break.

required
site Site

The site settings (for the allowed URLs).

required

Returns:

Type Description
list[str]

A message per problem; empty when the line is fine.

Source code in src/solidworks_mcp/doc_links/llms_txt.py
def line_problems(line: str, site: Site) -> list[str]:
    """What is wrong with one line of ``llms.txt``, if anything.

    The rules (spec ``docs/llms-txt``): one of the allowed shapes; every URL
    under ``site_url`` or ``repo_url``; no control or format characters
    (zero-width, byte-order mark, bidirectional controls); no HTML tag or
    comment outside code spans.

    Args:
        line: The line, without its line break.
        site: The site settings (for the allowed URLs).

    Returns:
        A message per problem; empty when the line is fine.
    """
    problems: list[str] = []
    for char in line:
        if unicodedata.category(char) in ("Cc", "Cf"):
            problems.append(
                f"hidden character U+{ord(char):04X} "
                f"({unicodedata.name(char, 'unnamed')})"
            )
    if _HTML.search(_CODE_SPAN.sub("", line)):
        problems.append("HTML tag or comment")
    for url in _URL.findall(line):
        if not _ours(url, site):
            problems.append(f"link outside this project: {url}")
    if not any(shape.match(line) for shape in _SHAPES):
        problems.append("not a title, summary, section, entry or blank line")
    return problems

load_site

load_site(root: Path) -> Site

Read mkdocs.yml under root.

Parameters:

Name Type Description Default
root Path

The repository root.

required

Returns:

Type Description
Site

The site settings and nav.

Source code in src/solidworks_mcp/doc_links/pages.py
def load_site(root: Path) -> Site:
    """Read ``mkdocs.yml`` under ``root``.

    Args:
        root: The repository root.

    Returns:
        The site settings and nav.
    """
    text = (root / "mkdocs.yml").read_text(encoding="utf-8")
    config = yaml.safe_load(_PYTHON_TAG.sub("null", text))
    return Site(
        name=config["site_name"],
        description=config["site_description"],
        url=config["site_url"].rstrip("/"),
        repo_url=config["repo_url"].rstrip("/"),
        nav=config["nav"],
    )

nav_pages

nav_pages(nav: list[Any], docs_dir: Path) -> list[NavPage]

The nav's Markdown pages, in nav order.

Entries that are not .md files in docs_dir (the generated API reference, for one) are left out.

Parameters:

Name Type Description Default
nav list[Any]

The nav from mkdocs.yml.

required
docs_dir Path

The docs/ directory.

required

Returns:

Type Description
list[NavPage]

One entry per page; top-level pages first, under Overview.

Source code in src/solidworks_mcp/doc_links/pages.py
def nav_pages(nav: list[Any], docs_dir: Path) -> list[NavPage]:
    """The nav's Markdown pages, in nav order.

    Entries that are not ``.md`` files in ``docs_dir`` (the generated API
    reference, for one) are left out.

    Args:
        nav: The nav from ``mkdocs.yml``.
        docs_dir: The ``docs/`` directory.

    Returns:
        One entry per page; top-level pages first, under ``Overview``.
    """
    top: list[NavPage] = []
    sections: list[NavPage] = []
    for item in nav:
        for title, value in _entries(item):
            if isinstance(value, list):
                sections.extend(NavPage(title, path) for path in _paths(value))
            elif isinstance(value, str):
                top.append(NavPage(OVERVIEW, value))
    return [p for p in top + sections if _is_page(p.path, docs_dir)]

opening

opening(text: str, page: str) -> Opening

The page's # title and its first prose paragraph.

Prose is a paragraph before the first lower heading that is not a blockquote, admonition, list, table, image, badge line, HTML, rule or code (fenced or indented).

Parameters:

Name Type Description Default
text str

The page's Markdown.

required
page str

The page's path, for the error message.

required

Returns:

Type Description
Opening

The title and summary.

Raises:

Type Description
DocsError

When the page has no # heading, or no prose paragraph before its next heading.

Source code in src/solidworks_mcp/doc_links/pages.py
def opening(text: str, page: str) -> Opening:
    """The page's ``# `` title and its first prose paragraph.

    Prose is a paragraph before the first lower heading that is not a
    blockquote, admonition, list, table, image, badge line, HTML, rule or
    code (fenced or indented).

    Args:
        text: The page's Markdown.
        page: The page's path, for the error message.

    Returns:
        The title and summary.

    Raises:
        DocsError: When the page has no ``# `` heading, or no prose
            paragraph before its next heading.
    """
    lines = source_lines(text)
    title: str | None = None
    block: list[str] = []
    for _number, line, code in lines:
        heading = None if code else _HEADING.match(line)
        if title is None:
            if heading and len(heading.group(1)) == 1:
                title = _split_attrs(heading.group(2))[0]
            continue
        if heading:
            break
        if code or line.strip() == "":
            if _is_prose(block):
                return Opening(title, _inline_text(" ".join(block)))
            block = []
            continue
        block.append(line.strip() if block else line)
    if title is None:
        raise DocsError(f"{page}: no `# ` heading to use as its title")
    if _is_prose(block):
        return Opening(title, _inline_text(" ".join(block)))
    raise DocsError(
        f"{page}: no opening paragraph after its `# ` heading (a blockquote, "
        "list, table, image or code doesn't count); give the page one"
    )

page_url

page_url(site_url: str, path: str) -> str

The published URL of the page at path (directory URLs).

Parameters:

Name Type Description Default
site_url str

site_url without a trailing slash.

required
path str

The page's path relative to docs/.

required

Returns:

Type Description
str

index.md -> <site_url>/; a/b.md -> <site_url>/a/b/;

str

a/index.md -> <site_url>/a/.

Source code in src/solidworks_mcp/doc_links/pages.py
def page_url(site_url: str, path: str) -> str:
    """The published URL of the page at ``path`` (directory URLs).

    Args:
        site_url: ``site_url`` without a trailing slash.
        path: The page's path relative to ``docs/``.

    Returns:
        ``index.md`` -> ``<site_url>/``; ``a/b.md`` -> ``<site_url>/a/b/``;
        ``a/index.md`` -> ``<site_url>/a/``.
    """
    stem = path.removesuffix(".md")
    if stem == "index":
        return f"{site_url}/"
    stem = stem.removesuffix("/index")
    return f"{site_url}/{stem}/"