okf-cli 0.6.1__tar.gz → 0.8.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. okf_cli-0.8.0/.agents/skills/wiki/SKILL.md +126 -0
  2. okf_cli-0.8.0/.last-update.json +1 -0
  3. {okf_cli-0.6.1 → okf_cli-0.8.0}/PKG-INFO +15 -1
  4. {okf_cli-0.6.1 → okf_cli-0.8.0}/README.md +12 -0
  5. {okf_cli-0.6.1 → okf_cli-0.8.0}/pyproject.toml +5 -2
  6. {okf_cli-0.6.1 → okf_cli-0.8.0}/src/okf/api.py +170 -70
  7. {okf_cli-0.6.1 → okf_cli-0.8.0}/src/okf/cli.py +2 -0
  8. {okf_cli-0.6.1 → okf_cli-0.8.0}/src/okf/commands/bundle.py +4 -1
  9. okf_cli-0.8.0/src/okf/commands/serve_mcp.py +70 -0
  10. {okf_cli-0.6.1 → okf_cli-0.8.0}/tests/test_api.py +177 -3
  11. {okf_cli-0.6.1 → okf_cli-0.8.0}/tests/test_cli.py +2 -2
  12. okf_cli-0.8.0/tests/test_mcp.py +109 -0
  13. okf_cli-0.8.0/uv.lock +1602 -0
  14. {okf_cli-0.6.1 → okf_cli-0.8.0}/wiki/architecture.md +23 -2
  15. {okf_cli-0.6.1 → okf_cli-0.8.0}/wiki/domain-model.md +28 -4
  16. {okf_cli-0.6.1 → okf_cli-0.8.0}/wiki/operations.md +3 -2
  17. {okf_cli-0.6.1 → okf_cli-0.8.0}/wiki/quickstart.md +18 -1
  18. {okf_cli-0.6.1 → okf_cli-0.8.0}/wiki/testing.md +5 -1
  19. {okf_cli-0.6.1 → okf_cli-0.8.0}/wiki/workflows.md +27 -2
  20. okf_cli-0.6.1/.last-update.json +0 -1
  21. okf_cli-0.6.1/uv.lock +0 -240
  22. {okf_cli-0.6.1 → okf_cli-0.8.0}/.github/workflows/test.yml +0 -0
  23. {okf_cli-0.6.1 → okf_cli-0.8.0}/.gitignore +0 -0
  24. {okf_cli-0.6.1 → okf_cli-0.8.0}/AGENTS.md +0 -0
  25. {okf_cli-0.6.1 → okf_cli-0.8.0}/LICENSE +0 -0
  26. {okf_cli-0.6.1 → okf_cli-0.8.0}/SPEC/OKF_SPEC_V0_1.md +0 -0
  27. {okf_cli-0.6.1 → okf_cli-0.8.0}/SPEC/OKF_SPEC_V0_2.md +0 -0
  28. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/.okfignore +0 -0
  29. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/README.md +0 -0
  30. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/blank-line/no-blank.md +0 -0
  31. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/blank-line/with-blank.md +0 -0
  32. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/computations/revenue.md +0 -0
  33. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/datasets/sales.md +0 -0
  34. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/domain.md +0 -0
  35. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/loose/deep/no-heading.md +0 -0
  36. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/loose/no-desc.md +0 -0
  37. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/loose/no-title.md +0 -0
  38. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/metrics/income-statement.md +0 -0
  39. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/playbooks/incident-response.md +0 -0
  40. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/playbooks/oncall-guide.md +0 -0
  41. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/references/revenue-recognition.md +0 -0
  42. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/smoke-ignore.md +0 -0
  43. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/tables/customers.md +0 -0
  44. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/tables/orders.md +0 -0
  45. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/tables/partitions/2026/q1/jan/january.md +0 -0
  46. {okf_cli-0.6.1 → okf_cli-0.8.0}/example/tables/partitions/daily.md +0 -0
  47. {okf_cli-0.6.1 → okf_cli-0.8.0}/skills/okf-cli/SKILL.md +0 -0
  48. {okf_cli-0.6.1 → okf_cli-0.8.0}/skills/writing-knowledge-base/SKILL.md +0 -0
  49. {okf_cli-0.6.1 → okf_cli-0.8.0}/src/okf/__init__.py +0 -0
  50. {okf_cli-0.6.1 → okf_cli-0.8.0}/src/okf/commands/__init__.py +0 -0
  51. {okf_cli-0.6.1 → okf_cli-0.8.0}/src/okf/commands/list.py +0 -0
  52. {okf_cli-0.6.1 → okf_cli-0.8.0}/src/okf/commands/read.py +0 -0
  53. {okf_cli-0.6.1 → okf_cli-0.8.0}/src/okf/commands/validate.py +0 -0
  54. {okf_cli-0.6.1 → okf_cli-0.8.0}/src/okf/core.py +0 -0
  55. {okf_cli-0.6.1 → okf_cli-0.8.0}/tests/test_core.py +0 -0
@@ -0,0 +1,126 @@
1
+ ---
2
+ description: Document a repository — explore codebase, architecture, workflows, data models, integrations, tests, ops, and generate structured documentation under /wiki/. Use when asked to document a repo, create a wiki, make wiki, initialize/update docs, or "wiki this".
3
+ metadata:
4
+ github-path: skills/wiki
5
+ github-ref: refs/heads/main
6
+ github-repo: https://github.com/dheerapat/skills
7
+ github-tree-sha: bccf99e1c83115e4ae5165bd65064aaf243d8d73
8
+ name: wiki
9
+ ---
10
+ # Wiki Skill
11
+
12
+ Turn into a documentation agent for any repository. Inspects the codebase and produces navigable Markdown docs under `wiki/` for humans and future agents.
13
+
14
+ ## Usage
15
+
16
+ ```
17
+ user: "wiki this repo"
18
+ user: "initialize wiki docs"
19
+ user: "update the wiki"
20
+ user: "/wiki init"
21
+ user: "/wiki update"
22
+ user: "wiki: add a page about the CLI"
23
+ ```
24
+
25
+ ## Mode of Operation
26
+
27
+ ### Init mode (first run)
28
+
29
+ Invoke by `/wiki init`
30
+
31
+ - Assume `wiki/` has no useful docs yet
32
+ - Build from scratch: repo inventory → quickstart → section pages
33
+ - Use git history to understand how important files/workflows evolved
34
+ - Target at most 8 documentation pages unless repo is very large
35
+ - Do not try to document every source file — document architecture, workflows, domains, data models, integrations, ops, and extension points at the right level
36
+
37
+ ### Update mode (incremental)
38
+
39
+ Invoke by `/wiki update`
40
+
41
+ - Read existing `wiki/` and `.last-update.json` (if exists)
42
+ - Use git to find what changed: `git log <lastHead>..HEAD --name-status --oneline` or `git diff --name-status HEAD`
43
+ - Build a docs impact plan: source change → which wiki page is affected → edit needed → why
44
+ - Be surgical: replace stale sentences over adding paragraphs, don't rewrite accurate sections
45
+ - Only edit pages directly affected by recent changes. Don't refresh every page
46
+ - No formatting-only edits. Don't normalize tables, blank lines, or reorder lists unless surrounding content is also being edited for accuracy
47
+ - If wiki is already current, say so — don't touch files
48
+ - Updates may be a no-op. If nothing relevant changed, don't edit.
49
+ - After update completes, write/update `.last-update.json` with `{"head": "<current HEAD SHA>", "timestamp": "<ISO 8601>"}` for next run
50
+
51
+ ## Workflow
52
+
53
+ ### 1. Discover the repository
54
+
55
+ Use tools to explore:
56
+
57
+ - `ls` top-level, key directories
58
+ - `bash` with `rg --files`, `find`, `git log`, `git status`
59
+ - `read` package.json, entrypoints, configs, READMEs
60
+
61
+ Do not exhaustively read every file. Target: package/config files, entrypoints, routing files, database/schema files, domain directories, tests, CI configs, and existing docs.
62
+
63
+ Ground every claim in source files, docs, or git evidence you've inspected. Do not invent files, modules, APIs, or behavior.
64
+
65
+ ### 2. Create documentation plan
66
+
67
+ After discovery, create a temp `wiki/_plan.md` listing intended pages, source evidence for each, and open questions. Use `write` to create it.
68
+
69
+ ### 3. Write documentation
70
+
71
+ Write the docs under `wiki/`. Structure:
72
+
73
+ ```
74
+ wiki/
75
+ ├── quickstart.md # Entrypoint — repo overview + links to sections
76
+ ├── architecture/ # Runtime shape, modules, execution flow
77
+ ├── workflows/ # Key workflows and processes
78
+ ├── domain/ # Business/product domain concepts
79
+ ├── operations/ # Setup, deployment, CI/CD, ops
80
+ └── ... # Repo-appropriate sections
81
+ ```
82
+
83
+ Rules:
84
+
85
+ - `quickstart.md` must exist and be the entrypoint with links to all sections
86
+ - Create section directories only when they have multiple substantive pages. Avoid one-file directories unless the page is substantial and likely to grow
87
+ - Merge thin pages and stubs into broader pages or quickstart itself
88
+ - Include inline source-file references where they help readers verify
89
+ - Keep docs concise — don't repeat same concept across pages, give each concept one canonical home
90
+ - For small repos (~10 primary source files), prefer quickstart + at most 1-2 supporting pages
91
+
92
+ ### 4. Update AGENTS.md / CLAUDE.md
93
+
94
+ Ensure repo root `/AGENTS.md` and/or `/CLAUDE.md` references the Wiki quickstart with this exact section:
95
+
96
+ ```markdown
97
+ ## Wiki
98
+
99
+ This repository has documentation located in the /wiki directory.
100
+
101
+ Start here:
102
+ - [Wiki quickstart](wiki/quickstart.md)
103
+
104
+ Wiki includes repository overview, architecture notes, workflows, domain concepts, operations, integrations, testing guidance, and source maps.
105
+
106
+ When working in this repository, read the Wiki quickstart first, then follow its links to the relevant architecture, workflow, domain, operation, and testing notes.
107
+ ```
108
+
109
+ - If file exists, add/update the section (preserve surrounding content, no duplicates)
110
+ - If both exist, update both
111
+ - If neither exists, create `/AGENTS.md` with only that section
112
+ - During updates, refresh only if section is missing or semantically stale
113
+ - Do not normalize formatting/whitespace if already correct
114
+
115
+ ### 5. Clean up
116
+
117
+ Delete `wiki/_plan.md`. Do not leave it in the final wiki.
118
+
119
+ ## Quality guidelines
120
+
121
+ - Document why code exists, not just what it does
122
+ - Include change-oriented guidance: where to start, what to watch for, relevant tests
123
+ - Avoid persistent commit hash lists unless a specific historical decision is important
124
+ - Capture business/product logic alongside technical details
125
+ - Docs should be useful to both humans (readable, navigable) and future agents (precise, grounded in source)
126
+ - Prefer stable Markdown links between pages
@@ -0,0 +1 @@
1
+ {"head": "7a548a8db805197813f0202d53834b8385909a42", "timestamp": "2026-10-24T09:05:55Z"}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: okf-cli
3
- Version: 0.6.1
3
+ Version: 0.8.0
4
4
  Summary: Open Knowledge Format tooling
5
5
  License: MIT License
6
6
 
@@ -28,6 +28,8 @@ Requires-Python: >=3.11
28
28
  Requires-Dist: pyyaml>=6
29
29
  Requires-Dist: rich>=15.0.0
30
30
  Requires-Dist: typer>=0.15
31
+ Provides-Extra: mcp
32
+ Requires-Dist: fastmcp<5,>=4.1.4; extra == 'mcp'
31
33
  Description-Content-Type: text/markdown
32
34
 
33
35
  # okf-cli — Open Knowledge Format tooling
@@ -56,9 +58,21 @@ uv run okf --version
56
58
  | `okf validate <directory>` | Check OKF v0.2 §11 conformance |
57
59
  | `okf list <directory>` | List concepts (ID, type, title, description) |
58
60
  | `okf read <directory> <concept-id>` | Print a concept by ID |
61
+ | `okf serve-mcp <directory>` | Serve a conformant bundle over MCP HTTP |
59
62
 
60
63
  Run `okf <command> --help` for options such as `--default-type`, `--force`, `--strict`, and `--dry-run`.
61
64
 
65
+ ### MCP server
66
+
67
+ Install the optional MCP dependency, then serve a conformant bundle over Streamable HTTP:
68
+
69
+ ```bash
70
+ uv sync --extra mcp
71
+ uv run okf serve-mcp example_knowledge_base
72
+ ```
73
+
74
+ The server binds to `127.0.0.1:8000` by default and listens at `http://127.0.0.1:8000/mcp`. Use `--host` and `--port` to change the bind address. The server exposes read-only `list_concepts` and `read_concept` tools. Non-local binds have no built-in authentication; use them only on a trusted network or behind an authenticated proxy.
75
+
62
76
  ## Quick example
63
77
 
64
78
  ```bash
@@ -24,9 +24,21 @@ uv run okf --version
24
24
  | `okf validate <directory>` | Check OKF v0.2 §11 conformance |
25
25
  | `okf list <directory>` | List concepts (ID, type, title, description) |
26
26
  | `okf read <directory> <concept-id>` | Print a concept by ID |
27
+ | `okf serve-mcp <directory>` | Serve a conformant bundle over MCP HTTP |
27
28
 
28
29
  Run `okf <command> --help` for options such as `--default-type`, `--force`, `--strict`, and `--dry-run`.
29
30
 
31
+ ### MCP server
32
+
33
+ Install the optional MCP dependency, then serve a conformant bundle over Streamable HTTP:
34
+
35
+ ```bash
36
+ uv sync --extra mcp
37
+ uv run okf serve-mcp example_knowledge_base
38
+ ```
39
+
40
+ The server binds to `127.0.0.1:8000` by default and listens at `http://127.0.0.1:8000/mcp`. Use `--host` and `--port` to change the bind address. The server exposes read-only `list_concepts` and `read_concept` tools. Non-local binds have no built-in authentication; use them only on a trusted network or behind an authenticated proxy.
41
+
30
42
  ## Quick example
31
43
 
32
44
  ```bash
@@ -1,12 +1,15 @@
1
1
  [project]
2
2
  name = "okf-cli"
3
- version = "0.6.1"
3
+ version = "0.8.0"
4
4
  description = "Open Knowledge Format tooling"
5
5
  readme = "README.md"
6
6
  license = { file = "LICENSE" }
7
7
  requires-python = ">=3.11"
8
8
  dependencies = ["typer>=0.15", "pyyaml>=6", "rich>=15.0.0"]
9
9
 
10
+ [project.optional-dependencies]
11
+ mcp = ["fastmcp>=4.1.4,<5"]
12
+
10
13
  [project.scripts]
11
14
  okf = "okf.cli:app"
12
15
 
@@ -18,7 +21,7 @@ build-backend = "hatchling.build"
18
21
  packages = ["src/okf"]
19
22
 
20
23
  [dependency-groups]
21
- dev = ["pytest>=8", "ruff>=0.14"]
24
+ dev = ["pytest>=8", "ruff>=0.14", "fastmcp>=4.1.4,<5"]
22
25
 
23
26
  [tool.ruff]
24
27
  line-length = 88
@@ -2,9 +2,11 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import os
5
6
  import posixpath
6
7
  import re
7
8
  import shutil
9
+ import tempfile
8
10
  from dataclasses import dataclass, field
9
11
  from datetime import UTC, datetime
10
12
  from importlib.metadata import version as _package_version
@@ -146,10 +148,58 @@ def _is_ignored(rel_posix: str, ignored: set[str]) -> bool:
146
148
  return any(pat.endswith("/") and rel_posix.startswith(pat) for pat in ignored)
147
149
 
148
150
 
149
- def _generate_indexes(processed: list[tuple[Path, dict]], dst: Path) -> None:
150
- """Generate index.md for every directory with concept files or subdirs."""
151
+ def _path_exists(path: Path) -> bool:
152
+ """Return true for paths including dangling symlinks."""
153
+ return path.exists() or path.is_symlink()
154
+
155
+
156
+ def _remove_path(path: Path) -> None:
157
+ """Remove a file, symlink, or directory without following symlinks."""
158
+ if path.is_dir() and not path.is_symlink():
159
+ shutil.rmtree(path)
160
+ else:
161
+ path.unlink()
162
+
163
+
164
+ def _commit_staged_bundle(staged: Path, dst: Path) -> bool:
165
+ """Replace ``dst`` with a fully built staging directory.
166
+
167
+ The previous output is moved aside only at commit time and restored if
168
+ promoting the staged bundle fails. Returns whether an output was replaced.
169
+ """
170
+ backup: Path | None = None
171
+ if _path_exists(dst):
172
+ fd, backup_name = tempfile.mkstemp(
173
+ prefix=f".{dst.name or 'okf'}.backup-", dir=dst.parent
174
+ )
175
+ os.close(fd)
176
+ backup = Path(backup_name)
177
+ backup.unlink()
178
+ os.replace(dst, backup)
179
+
180
+ try:
181
+ os.replace(staged, dst)
182
+ except BaseException:
183
+ if backup is not None:
184
+ os.replace(backup, dst)
185
+ raise
186
+
187
+ if backup is not None:
188
+ _remove_path(backup)
189
+ return backup is not None
190
+
191
+
192
+ def _generate_indexes(
193
+ processed: list[tuple[Path, dict]], dst: Path, *, overwrite: bool = False
194
+ ) -> int:
195
+ """Generate index.md for every directory with concept files or subdirs.
196
+
197
+ Returns the number of index files written. Existing index files are kept
198
+ unless ``overwrite`` is true.
199
+ """
151
200
  dir_files: dict[Path, list[dict]] = {}
152
201
  dir_subdirs: dict[Path, set[str]] = {}
202
+ written = 0
153
203
 
154
204
  for rel, meta in processed:
155
205
  parent = rel.parent
@@ -167,7 +217,7 @@ def _generate_indexes(processed: list[tuple[Path, dict]], dst: Path) -> None:
167
217
 
168
218
  for dir_path in sorted(set(dir_files.keys()) | set(dir_subdirs.keys())):
169
219
  index_path = dst / dir_path / "index.md"
170
- if index_path.exists():
220
+ if index_path.exists() and not overwrite:
171
221
  continue
172
222
 
173
223
  lines: list[str] = []
@@ -199,6 +249,9 @@ def _generate_indexes(processed: list[tuple[Path, dict]], dst: Path) -> None:
199
249
  if lines:
200
250
  index_path.parent.mkdir(parents=True, exist_ok=True)
201
251
  index_path.write_text("\n".join(lines), encoding="utf-8")
252
+ written += 1
253
+
254
+ return written
202
255
 
203
256
 
204
257
  # ---------------------------------------------------------------------------
@@ -344,7 +397,7 @@ def bundle(
344
397
  input_dir: Source directory of plain markdown files.
345
398
  output_dir: Target directory. Defaults to ``<input-dir>_knowledge_base``.
346
399
  default_type: Concept type for root-level files.
347
- force: Overwrite output directory if it exists.
400
+ force: Replace an existing output only after a complete staged build.
348
401
  strict: Enforce strict OKF spec output: fail on broken local .md
349
402
  links and skip AGENTS.md generation.
350
403
  dry_run: Validate and report what would be written without creating
@@ -374,15 +427,13 @@ def bundle(
374
427
  else:
375
428
  raise ValueError("Output directory must not be inside input directory")
376
429
 
377
- if dst.exists():
378
- if not dry_run and not force:
379
- raise FileExistsError(
380
- f"Output directory '{dst}' exists. Use --force to overwrite."
381
- )
382
- if force:
383
- if not dry_run:
384
- shutil.rmtree(dst)
385
- warnings.append(f"Removed existing '{dst}'")
430
+ output_exists = _path_exists(dst)
431
+ if output_exists and not dry_run and not force:
432
+ raise FileExistsError(
433
+ f"Output directory '{dst}' exists. Use --force to overwrite."
434
+ )
435
+ if output_exists and force and dry_run:
436
+ warnings.append(f"Would replace existing '{dst}'")
386
437
 
387
438
  try:
388
439
  ignored = _load_okfignore(src)
@@ -460,72 +511,90 @@ def bundle(
460
511
  errors.append("strict link check failed")
461
512
  return BundleResult(0, dst, warnings, errors)
462
513
 
463
- # Process files
514
+ # Build in a temporary sibling directory so failures never destroy the
515
+ # existing output. Rename into place only after all bundle files are ready.
464
516
  processed: list[tuple[Path, dict]] = []
517
+ staging_dir: Path | None = None
518
+ build_dir = dst
519
+ if not dry_run:
520
+ dst.parent.mkdir(parents=True, exist_ok=True)
521
+ staging_dir = Path(
522
+ tempfile.mkdtemp(prefix=f".{dst.name or 'okf'}.staging-", dir=dst.parent)
523
+ )
524
+ build_dir = staging_dir
525
+
526
+ try:
527
+ for rel, fm, title, description, body, mtime in parsed:
528
+ out_file = build_dir / rel
465
529
 
466
- for rel, fm, title, description, body, mtime in parsed:
467
- out_file = dst / rel
530
+ if rel.parent == Path("."):
531
+ type_name = default_type or src.name
532
+ else:
533
+ type_name = rel.parent.name
468
534
 
469
- if rel.parent == Path("."):
470
- type_name = default_type or src.name
471
- else:
472
- type_name = rel.parent.name
535
+ ts = datetime.fromtimestamp(mtime, tz=UTC).isoformat()
536
+ generated = {"by": _okfcli_actor(), "at": ts}
473
537
 
474
- ts = datetime.fromtimestamp(mtime, tz=UTC).isoformat()
475
- generated = {"by": _okfcli_actor(), "at": ts}
538
+ merged_title, merged_description, _ = _merge_input_frontmatter(
539
+ fm, title, description
540
+ )
476
541
 
477
- merged_title, merged_description, _ = _merge_input_frontmatter(
478
- fm, title, description
479
- )
542
+ if not dry_run:
543
+ out_file.parent.mkdir(parents=True, exist_ok=True)
544
+ try:
545
+ _write_concept(
546
+ title, description, body, out_file, type_name, generated, fm
547
+ )
548
+ except ValueError as e:
549
+ errors.append(f"{rel}: {e}")
550
+ return BundleResult(len(processed), dst, warnings, errors)
551
+ processed.append(
552
+ (
553
+ rel,
554
+ {
555
+ "title": merged_title,
556
+ "description": merged_description,
557
+ "type": type_name,
558
+ },
559
+ )
560
+ )
480
561
 
481
562
  if not dry_run:
482
- out_file.parent.mkdir(parents=True, exist_ok=True)
483
- try:
484
- _write_concept(
485
- title, description, body, out_file, type_name, generated, fm
486
- )
487
- except ValueError as e:
488
- errors.append(f"{rel}: {e}")
489
- return BundleResult(len(processed), dst, warnings, errors)
490
- processed.append(
491
- (
492
- rel,
493
- {
494
- "title": merged_title,
495
- "description": merged_description,
496
- "type": type_name,
497
- },
563
+ _generate_indexes(processed, build_dir)
564
+
565
+ # Write AGENTS.md (skipped in strict mode)
566
+ if not dry_run and not strict:
567
+ (build_dir / "AGENTS.md").write_text(
568
+ f"# Knowledge Base: {dst.name}\n\n"
569
+ f"You are in an OKF (Open Knowledge Format) knowledge base called "
570
+ f"**{dst.name}**. OKF is a structured markdown format where each "
571
+ f"`.md` file is a concept with YAML frontmatter and cross-links "
572
+ f"between related concepts.\n\n"
573
+ "## Instructions\n\n"
574
+ "- **Answer from this knowledge base only.** Use the concepts and "
575
+ "links here as your source of truth.\n"
576
+ "- **If the answer is not in the knowledge base, say so directly.** "
577
+ "Do not fabricate, guess, or pull from external knowledge.\n\n"
578
+ "## Getting Started\n\n"
579
+ "Read [index.md](index.md) first — it lists all concepts "
580
+ "and subdirectories.\n\n"
581
+ "## Navigation\n\n"
582
+ "- Follow markdown links between concepts.\n"
583
+ "- Each `.md` file has YAML frontmatter with `type`, `title`, "
584
+ "`description`, and other producer-defined metadata.\n"
585
+ "- Subdirectories group related concepts by topic.\n"
586
+ "- Cross-links (e.g. `[Customers](/tables/customers.md)`) "
587
+ "express relationships.\n",
588
+ encoding="utf-8",
498
589
  )
499
- )
500
590
 
501
- if not dry_run:
502
- _generate_indexes(processed, dst)
503
-
504
- # Write AGENTS.md (skipped in strict mode)
505
- if not dry_run and not strict:
506
- (dst / "AGENTS.md").write_text(
507
- f"# Knowledge Base: {dst.name}\n\n"
508
- f"You are in an OKF (Open Knowledge Format) knowledge base called "
509
- f"**{dst.name}**. OKF is a structured markdown format where each "
510
- f"`.md` file is a concept with YAML frontmatter and cross-links "
511
- f"between related concepts.\n\n"
512
- "## Instructions\n\n"
513
- "- **Answer from this knowledge base only.** Use the concepts and "
514
- "links here as your source of truth.\n"
515
- "- **If the answer is not in the knowledge base, say so directly.** "
516
- "Do not fabricate, guess, or pull from external knowledge.\n\n"
517
- "## Getting Started\n\n"
518
- "Read [index.md](index.md) first — it lists all concepts "
519
- "and subdirectories.\n\n"
520
- "## Navigation\n\n"
521
- "- Follow markdown links between concepts.\n"
522
- "- Each `.md` file has YAML frontmatter with `type`, `title`, "
523
- "`description`, and other producer-defined metadata.\n"
524
- "- Subdirectories group related concepts by topic.\n"
525
- "- Cross-links (e.g. `[Customers](/tables/customers.md)`) "
526
- "express relationships.\n",
527
- encoding="utf-8",
528
- )
591
+ if not dry_run:
592
+ replaced = _commit_staged_bundle(staging_dir, dst)
593
+ if replaced:
594
+ warnings.append(f"Replaced existing '{dst}'")
595
+ finally:
596
+ if staging_dir is not None and _path_exists(staging_dir):
597
+ _remove_path(staging_dir)
529
598
 
530
599
  return BundleResult(
531
600
  files_written=len(processed),
@@ -535,6 +604,37 @@ def bundle(
535
604
  )
536
605
 
537
606
 
607
+ def reindex(bundle_dir: str | Path) -> BundleResult:
608
+ """Rebuild every index.md in a bundle from the concept files on disk.
609
+
610
+ Args:
611
+ bundle_dir: Path to an OKF bundle directory.
612
+
613
+ Returns:
614
+ BundleResult with ``files_written`` set to the number of index files
615
+ written and ``output_dir`` set to ``bundle_dir``.
616
+
617
+ Raises:
618
+ NotADirectoryError: If bundle_dir is not a directory.
619
+ ValueError: If the directory is not a conformant OKF bundle.
620
+ """
621
+ dst = Path(bundle_dir)
622
+ entries = list_entries(dst)
623
+ processed = [
624
+ (
625
+ Path(e["id"] + ".md"),
626
+ {
627
+ "title": e["title"],
628
+ "description": e["description"],
629
+ "type": e["type"],
630
+ },
631
+ )
632
+ for e in entries
633
+ ]
634
+ count = _generate_indexes(processed, dst, overwrite=True)
635
+ return BundleResult(files_written=count, output_dir=dst)
636
+
637
+
538
638
  def _iter_concept_files(dir_path: Path):
539
639
  """Yield (concept_id, file_path) for every concept in a bundle.
540
640
 
@@ -7,6 +7,7 @@ import typer
7
7
  from okf.commands.bundle import bundle
8
8
  from okf.commands.list import cmd_list
9
9
  from okf.commands.read import cmd_read
10
+ from okf.commands.serve_mcp import serve_mcp
10
11
  from okf.commands.validate import validate
11
12
  from okf.core import console
12
13
 
@@ -40,6 +41,7 @@ app.command()(bundle)
40
41
  app.command("list")(cmd_list)
41
42
  app.command("read")(cmd_read)
42
43
  app.command("validate")(validate)
44
+ app.command("serve-mcp")(serve_mcp)
43
45
 
44
46
 
45
47
  if __name__ == "__main__":
@@ -19,7 +19,10 @@ def bundle(
19
19
  None, help="Type for root-level files (default: input directory name)"
20
20
  ),
21
21
  force: bool = typer.Option(
22
- False, "--force", "-f", help="Overwrite output directory if it exists"
22
+ False,
23
+ "--force",
24
+ "-f",
25
+ help="Replace existing output after a successful build",
23
26
  ),
24
27
  strict: bool = typer.Option(
25
28
  False,
@@ -0,0 +1,70 @@
1
+ """Serve a conformant OKF bundle over MCP Streamable HTTP."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ import typer
7
+
8
+ from okf import api
9
+ from okf.core import err_console
10
+
11
+
12
+ def _create_server(bundle_dir: Path) -> Any:
13
+ """Create an MCP server exposing read-only bundle tools."""
14
+ try:
15
+ from fastmcp import FastMCP
16
+ except ImportError as exc:
17
+ raise RuntimeError(
18
+ "MCP support is not installed. Install okf-cli with the 'mcp' extra."
19
+ ) from exc
20
+
21
+ mcp = FastMCP(f"OKF bundle: {bundle_dir.name}")
22
+
23
+ @mcp.tool
24
+ def list_concepts() -> list[dict[str, str]]:
25
+ """List concept IDs and their type, title, and description."""
26
+ return api.list_entries(bundle_dir)
27
+
28
+ @mcp.tool
29
+ def read_concept(concept_id: str) -> dict[str, Any]:
30
+ """Read an OKF concept by its bundle-relative ID, e.g. tables/orders."""
31
+ concept = api.show_concept(bundle_dir, concept_id)
32
+ return {
33
+ "id": concept_id,
34
+ "frontmatter": concept.frontmatter,
35
+ "body": concept.body,
36
+ }
37
+
38
+ return mcp
39
+
40
+
41
+ def serve_mcp(
42
+ directory: Path = typer.Argument(..., help="Directory of the OKF bundle"),
43
+ host: str = typer.Option(
44
+ "127.0.0.1", "--host", help="Interface to bind (default: localhost only)"
45
+ ),
46
+ port: int = typer.Option(8000, "--port", help="HTTP port to bind"),
47
+ ) -> None:
48
+ """Serve an OKF bundle over MCP Streamable HTTP."""
49
+ bundle_dir = directory.resolve()
50
+ try:
51
+ report = api.validate(bundle_dir)
52
+ except (NotADirectoryError, OSError) as exc:
53
+ err_console.print(f"Error: {exc}", style="red")
54
+ raise typer.Exit(code=1) from exc
55
+
56
+ if not report.ok:
57
+ err_console.print(
58
+ "Error: directory is not an OKF-conformant bundle:", style="red"
59
+ )
60
+ for error in report.errors:
61
+ err_console.print(f" {error}", style="red")
62
+ raise typer.Exit(code=1)
63
+
64
+ try:
65
+ mcp = _create_server(bundle_dir)
66
+ except RuntimeError as exc:
67
+ err_console.print(f"Error: {exc}", style="red")
68
+ raise typer.Exit(code=1) from exc
69
+
70
+ mcp.run(transport="streamable-http", host=host, port=port, path="/mcp")