docs MCP: index every doc and emit absolute docs.inference.coop links
The docs MCP served raw repo-relative markdown, so chat answers carried hrefs like guides/what-happens-with-your-data.md. The chat client resolved them against chat.inference.coop, which answers 200 with its SPA shell for any path — a link that looks live and is not the document. - list docs recursively (git trees API) instead of repo-root contents; the old call indexed only README.md and background.md (2 docs, 7 chunks) - rewrite repo-relative links to absolute published URLs, using MkDocs directory URLs (/guides/models/) - index only pages the published site serves, per its sitemap - name docs.inference.coop in the tool description
This commit is contained in:
1 parent
465469e8d4
commit
944410560c
1 file changed
+91
-5
+91
-5
@@ -10,17 +10,28 @@ Design notes:
|
||||
- No third-party dependencies: the corpus is fetched from the public Gitea
|
||||
raw API, chunked by heading, and ranked with a compact BM25.
|
||||
- The index refreshes lazily if older than DOCS_TTL seconds (default 30 min).
|
||||
- Every repo-relative markdown link is rewritten to its ABSOLUTE published URL
|
||||
on https://docs.inference.coop/ before it reaches the model. Raw source links
|
||||
(``guides/models.md``) leak into chat answers as relative hrefs, which the
|
||||
chat client then resolves against chat.inference.coop — a 200 that serves the
|
||||
chat app shell instead of the document.
|
||||
- Only documents the published site actually serves are indexed; the sitemap is
|
||||
the authority, so unpublished source files never become citations.
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
import posixpath
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
DOCS_REPO = "co-op/docs"
|
||||
DOCS_BRANCH = "main"
|
||||
DOCS_SITE = "https://docs.inference.coop"
|
||||
GITEA_API = "https://git.inference.coop/api/v1"
|
||||
DOCS_TTL = 30 * 60
|
||||
MAX_CHUNKS_RETURNED = 5
|
||||
@@ -50,14 +61,77 @@ def fetch_text(url):
|
||||
|
||||
|
||||
def list_doc_files():
|
||||
files = fetch_json(f"{GITEA_API}/repos/{DOCS_REPO}/contents")
|
||||
"""Every markdown file in the repo, at any depth (not just repo root)."""
|
||||
tree = fetch_json(
|
||||
f"{GITEA_API}/repos/{DOCS_REPO}/git/trees/{DOCS_BRANCH}"
|
||||
"?recursive=true&per_page=1000"
|
||||
)
|
||||
if tree.get("truncated"):
|
||||
log("warning: git tree truncated; some docs are missing from the index")
|
||||
return [
|
||||
{"path": f["path"], "name": f["name"]}
|
||||
for f in files
|
||||
if f["type"] == "file" and f["name"].endswith(".md")
|
||||
{"path": f["path"]}
|
||||
for f in tree.get("tree", [])
|
||||
if f.get("type") == "blob"
|
||||
and f["path"].endswith(".md")
|
||||
and not f["path"].startswith(("publishing/", "."))
|
||||
]
|
||||
|
||||
|
||||
def doc_url(path):
|
||||
"""Published URL for a source file, using MkDocs' directory URLs."""
|
||||
if path == "README.md":
|
||||
return DOCS_SITE + "/"
|
||||
stem = path[:-3] # strip ".md"
|
||||
if stem == "index":
|
||||
stem = ""
|
||||
elif stem.endswith("/index"):
|
||||
stem = stem[: -len("/index")]
|
||||
return f"{DOCS_SITE}/{stem}/" if stem else DOCS_SITE + "/"
|
||||
|
||||
|
||||
def published_paths():
|
||||
"""URL paths the docs site actually serves, according to its sitemap."""
|
||||
try:
|
||||
xml = fetch_text(f"{DOCS_SITE}/sitemap.xml")
|
||||
except Exception as exc: # noqa: BLE001 - fail open, log the gap
|
||||
log(f"sitemap unavailable ({exc}); indexing every source doc")
|
||||
return None
|
||||
locs = re.findall(r"<loc>\s*([^<\s]+)\s*</loc>", xml)
|
||||
return {urllib.parse.urlparse(u).path for u in locs}
|
||||
|
||||
|
||||
LINK_RE = re.compile(r"\]\(\s*([^)\s]+)\s*\)")
|
||||
|
||||
|
||||
def rewrite_links(text, path):
|
||||
"""Turn repo-relative links into absolute docs.inference.coop URLs.
|
||||
|
||||
A relative href survives into the model's answer and is resolved by the
|
||||
chat client against chat.inference.coop, which serves its SPA shell with
|
||||
status 200 for any path — a link that looks live and is not the document.
|
||||
"""
|
||||
base_dir = posixpath.dirname(path)
|
||||
|
||||
def repl(match):
|
||||
target = match.group(1)
|
||||
if "://" in target or target.startswith(("#", "//", "mailto:")):
|
||||
return match.group(0)
|
||||
fragment = ""
|
||||
if "#" in target:
|
||||
target, fragment = target.split("#", 1)
|
||||
fragment = "#" + fragment
|
||||
resolved = posixpath.normpath(posixpath.join(base_dir, target))
|
||||
if resolved in (".", "..") or resolved.startswith("../"):
|
||||
return match.group(0)
|
||||
if resolved.endswith(".md"):
|
||||
url = doc_url(resolved)
|
||||
else:
|
||||
url = f"{DOCS_SITE}/{resolved}"
|
||||
return f"]({url}{fragment})"
|
||||
|
||||
return LINK_RE.sub(repl, text)
|
||||
|
||||
|
||||
def chunk_markdown(path, text):
|
||||
"""Split a doc into section chunks keyed by its top title + heading."""
|
||||
lines = text.splitlines()
|
||||
@@ -90,11 +164,21 @@ def tokenize(text):
|
||||
def build_index():
|
||||
chunks = []
|
||||
docs = list_doc_files()
|
||||
published = published_paths()
|
||||
if published is not None:
|
||||
kept = []
|
||||
for doc in docs:
|
||||
url_path = urllib.parse.urlparse(doc_url(doc["path"])).path
|
||||
if url_path in published:
|
||||
kept.append(doc)
|
||||
else:
|
||||
log(f"skipping unpublished doc: {doc['path']}")
|
||||
docs = kept
|
||||
|
||||
def load(doc):
|
||||
try:
|
||||
raw = fetch_text(f"{GITEA_API}/repos/{DOCS_REPO}/raw/{doc['path']}")
|
||||
return chunk_markdown(doc["path"], raw)
|
||||
return chunk_markdown(doc["path"], rewrite_links(raw, doc["path"]))
|
||||
except Exception as exc: # noqa: BLE001 - one bad doc shouldn't kill the index
|
||||
log(f"skipping {doc['path']}: {exc}")
|
||||
return []
|
||||
@@ -168,6 +252,8 @@ TOOLS = [
|
||||
"description": (
|
||||
"Search the Inference Cooperative documentation (getting started, models, "
|
||||
"API access, charter, policies). Returns the most relevant doc sections. "
|
||||
"The docs are published at https://docs.inference.coop/ — cite links "
|
||||
"exactly as they appear in the results."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
|
||||
Reference in new issue
Block a user