okf-cli 0.7.0__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.7.0 → okf_cli-0.8.0}/PKG-INFO +15 -1
  4. {okf_cli-0.7.0 → okf_cli-0.8.0}/README.md +12 -0
  5. {okf_cli-0.7.0 → okf_cli-0.8.0}/pyproject.toml +5 -2
  6. {okf_cli-0.7.0 → okf_cli-0.8.0}/src/okf/api.py +126 -67
  7. {okf_cli-0.7.0 → okf_cli-0.8.0}/src/okf/cli.py +2 -0
  8. {okf_cli-0.7.0 → 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.7.0 → okf_cli-0.8.0}/tests/test_api.py +46 -3
  11. {okf_cli-0.7.0 → 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.7.0 → okf_cli-0.8.0}/wiki/architecture.md +23 -2
  15. {okf_cli-0.7.0 → okf_cli-0.8.0}/wiki/domain-model.md +28 -4
  16. {okf_cli-0.7.0 → okf_cli-0.8.0}/wiki/operations.md +3 -2
  17. {okf_cli-0.7.0 → okf_cli-0.8.0}/wiki/quickstart.md +18 -1
  18. {okf_cli-0.7.0 → okf_cli-0.8.0}/wiki/testing.md +5 -1
  19. {okf_cli-0.7.0 → okf_cli-0.8.0}/wiki/workflows.md +27 -2
  20. okf_cli-0.7.0/.last-update.json +0 -1
  21. okf_cli-0.7.0/uv.lock +0 -240
  22. {okf_cli-0.7.0 → okf_cli-0.8.0}/.github/workflows/test.yml +0 -0
  23. {okf_cli-0.7.0 → okf_cli-0.8.0}/.gitignore +0 -0
  24. {okf_cli-0.7.0 → okf_cli-0.8.0}/AGENTS.md +0 -0
  25. {okf_cli-0.7.0 → okf_cli-0.8.0}/LICENSE +0 -0
  26. {okf_cli-0.7.0 → okf_cli-0.8.0}/SPEC/OKF_SPEC_V0_1.md +0 -0
  27. {okf_cli-0.7.0 → okf_cli-0.8.0}/SPEC/OKF_SPEC_V0_2.md +0 -0
  28. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/.okfignore +0 -0
  29. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/README.md +0 -0
  30. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/blank-line/no-blank.md +0 -0
  31. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/blank-line/with-blank.md +0 -0
  32. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/computations/revenue.md +0 -0
  33. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/datasets/sales.md +0 -0
  34. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/domain.md +0 -0
  35. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/loose/deep/no-heading.md +0 -0
  36. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/loose/no-desc.md +0 -0
  37. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/loose/no-title.md +0 -0
  38. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/metrics/income-statement.md +0 -0
  39. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/playbooks/incident-response.md +0 -0
  40. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/playbooks/oncall-guide.md +0 -0
  41. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/references/revenue-recognition.md +0 -0
  42. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/smoke-ignore.md +0 -0
  43. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/tables/customers.md +0 -0
  44. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/tables/orders.md +0 -0
  45. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/tables/partitions/2026/q1/jan/january.md +0 -0
  46. {okf_cli-0.7.0 → okf_cli-0.8.0}/example/tables/partitions/daily.md +0 -0
  47. {okf_cli-0.7.0 → okf_cli-0.8.0}/skills/okf-cli/SKILL.md +0 -0
  48. {okf_cli-0.7.0 → okf_cli-0.8.0}/skills/writing-knowledge-base/SKILL.md +0 -0
  49. {okf_cli-0.7.0 → okf_cli-0.8.0}/src/okf/__init__.py +0 -0
  50. {okf_cli-0.7.0 → okf_cli-0.8.0}/src/okf/commands/__init__.py +0 -0
  51. {okf_cli-0.7.0 → okf_cli-0.8.0}/src/okf/commands/list.py +0 -0
  52. {okf_cli-0.7.0 → okf_cli-0.8.0}/src/okf/commands/read.py +0 -0
  53. {okf_cli-0.7.0 → okf_cli-0.8.0}/src/okf/commands/validate.py +0 -0
  54. {okf_cli-0.7.0 → okf_cli-0.8.0}/src/okf/core.py +0 -0
  55. {okf_cli-0.7.0 → 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.7.0
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.7.0"
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,6 +148,47 @@ 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
 
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
+
149
192
  def _generate_indexes(
150
193
  processed: list[tuple[Path, dict]], dst: Path, *, overwrite: bool = False
151
194
  ) -> int:
@@ -354,7 +397,7 @@ def bundle(
354
397
  input_dir: Source directory of plain markdown files.
355
398
  output_dir: Target directory. Defaults to ``<input-dir>_knowledge_base``.
356
399
  default_type: Concept type for root-level files.
357
- force: Overwrite output directory if it exists.
400
+ force: Replace an existing output only after a complete staged build.
358
401
  strict: Enforce strict OKF spec output: fail on broken local .md
359
402
  links and skip AGENTS.md generation.
360
403
  dry_run: Validate and report what would be written without creating
@@ -384,15 +427,13 @@ def bundle(
384
427
  else:
385
428
  raise ValueError("Output directory must not be inside input directory")
386
429
 
387
- if dst.exists():
388
- if not dry_run and not force:
389
- raise FileExistsError(
390
- f"Output directory '{dst}' exists. Use --force to overwrite."
391
- )
392
- if force:
393
- if not dry_run:
394
- shutil.rmtree(dst)
395
- 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}'")
396
437
 
397
438
  try:
398
439
  ignored = _load_okfignore(src)
@@ -470,72 +511,90 @@ def bundle(
470
511
  errors.append("strict link check failed")
471
512
  return BundleResult(0, dst, warnings, errors)
472
513
 
473
- # 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.
474
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
475
525
 
476
- for rel, fm, title, description, body, mtime in parsed:
477
- out_file = dst / rel
526
+ try:
527
+ for rel, fm, title, description, body, mtime in parsed:
528
+ out_file = build_dir / rel
478
529
 
479
- if rel.parent == Path("."):
480
- type_name = default_type or src.name
481
- else:
482
- type_name = rel.parent.name
530
+ if rel.parent == Path("."):
531
+ type_name = default_type or src.name
532
+ else:
533
+ type_name = rel.parent.name
483
534
 
484
- ts = datetime.fromtimestamp(mtime, tz=UTC).isoformat()
485
- generated = {"by": _okfcli_actor(), "at": ts}
535
+ ts = datetime.fromtimestamp(mtime, tz=UTC).isoformat()
536
+ generated = {"by": _okfcli_actor(), "at": ts}
486
537
 
487
- merged_title, merged_description, _ = _merge_input_frontmatter(
488
- fm, title, description
489
- )
538
+ merged_title, merged_description, _ = _merge_input_frontmatter(
539
+ fm, title, description
540
+ )
490
541
 
491
- if not dry_run:
492
- out_file.parent.mkdir(parents=True, exist_ok=True)
493
- try:
494
- _write_concept(
495
- title, description, body, out_file, type_name, generated, fm
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
+ },
496
559
  )
497
- except ValueError as e:
498
- errors.append(f"{rel}: {e}")
499
- return BundleResult(len(processed), dst, warnings, errors)
500
- processed.append(
501
- (
502
- rel,
503
- {
504
- "title": merged_title,
505
- "description": merged_description,
506
- "type": type_name,
507
- },
508
560
  )
509
- )
510
561
 
511
- if not dry_run:
512
- _generate_indexes(processed, dst)
513
-
514
- # Write AGENTS.md (skipped in strict mode)
515
- if not dry_run and not strict:
516
- (dst / "AGENTS.md").write_text(
517
- f"# Knowledge Base: {dst.name}\n\n"
518
- f"You are in an OKF (Open Knowledge Format) knowledge base called "
519
- f"**{dst.name}**. OKF is a structured markdown format where each "
520
- f"`.md` file is a concept with YAML frontmatter and cross-links "
521
- f"between related concepts.\n\n"
522
- "## Instructions\n\n"
523
- "- **Answer from this knowledge base only.** Use the concepts and "
524
- "links here as your source of truth.\n"
525
- "- **If the answer is not in the knowledge base, say so directly.** "
526
- "Do not fabricate, guess, or pull from external knowledge.\n\n"
527
- "## Getting Started\n\n"
528
- "Read [index.md](index.md) first — it lists all concepts "
529
- "and subdirectories.\n\n"
530
- "## Navigation\n\n"
531
- "- Follow markdown links between concepts.\n"
532
- "- Each `.md` file has YAML frontmatter with `type`, `title`, "
533
- "`description`, and other producer-defined metadata.\n"
534
- "- Subdirectories group related concepts by topic.\n"
535
- "- Cross-links (e.g. `[Customers](/tables/customers.md)`) "
536
- "express relationships.\n",
537
- encoding="utf-8",
538
- )
562
+ if not dry_run:
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",
589
+ )
590
+
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)
539
598
 
540
599
  return BundleResult(
541
600
  files_written=len(processed),
@@ -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")
@@ -212,7 +212,7 @@ class TestBundle:
212
212
 
213
213
  assert result.files_written == 1
214
214
  assert not (dst / "old.txt").exists()
215
- assert any("Removed" in w for w in result.warnings)
215
+ assert any("Replaced existing" in w for w in result.warnings)
216
216
 
217
217
  def test_no_force_fails(self, tmp_path: Path):
218
218
  src = tmp_path / "src"
@@ -363,6 +363,49 @@ class TestBundle:
363
363
  assert result.files_written == 0
364
364
  assert any("strict link check failed" in e.lower() for e in result.errors)
365
365
 
366
+ def test_force_strict_failure_preserves_existing_output(self, tmp_path: Path):
367
+ src = tmp_path / "src"
368
+ dst = tmp_path / "out"
369
+ src.mkdir()
370
+ dst.mkdir()
371
+ (dst / "important.txt").write_text("keep this bundle")
372
+ _write(
373
+ src,
374
+ {
375
+ "tables/orders.md": (
376
+ "# Orders\n\n> One row.\n\nSee [C](customers.md)."
377
+ ),
378
+ },
379
+ )
380
+
381
+ result = bundle(src, dst, force=True, strict=True)
382
+
383
+ assert result.errors
384
+ assert (dst / "important.txt").read_text() == "keep this bundle"
385
+ assert not list(tmp_path.glob(".out.staging-*"))
386
+
387
+ def test_force_write_failure_preserves_existing_output(
388
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
389
+ ):
390
+ import okf.api as api
391
+
392
+ src = tmp_path / "src"
393
+ dst = tmp_path / "out"
394
+ src.mkdir()
395
+ dst.mkdir()
396
+ (dst / "important.txt").write_text("keep this bundle")
397
+ _write(src, {"tables/a.md": "# A\n\n> Desc.\n"})
398
+
399
+ def fail_write(*args, **kwargs):
400
+ raise ValueError("simulated write failure")
401
+
402
+ monkeypatch.setattr(api, "_write_concept", fail_write)
403
+ result = bundle(src, dst, force=True)
404
+
405
+ assert result.errors == ["tables/a.md: simulated write failure"]
406
+ assert (dst / "important.txt").read_text() == "keep this bundle"
407
+ assert not list(tmp_path.glob(".out.staging-*"))
408
+
366
409
  def test_strict_passes(self, tmp_path: Path):
367
410
  src = tmp_path / "src"
368
411
  dst = tmp_path / "out"
@@ -517,7 +560,7 @@ class TestBundle:
517
560
  result = bundle(src, dst, force=True, dry_run=True)
518
561
 
519
562
  assert result.files_written == 1
520
- assert any("Removed existing" in w for w in result.warnings)
563
+ assert any("Would replace existing" in w for w in result.warnings)
521
564
  assert (dst / "old.txt").exists()
522
565
  assert (dst / "old.txt").read_text() == "preserve me"
523
566
 
@@ -533,7 +576,7 @@ class TestBundle:
533
576
 
534
577
  assert result.files_written == 1
535
578
  assert result.errors == []
536
- assert not any("Removed existing" in w for w in result.warnings)
579
+ assert not any("Would replace existing" in w for w in result.warnings)
537
580
  assert (dst / "old.txt").exists()
538
581
 
539
582
  def test_dry_run_strict_still_fails(self, tmp_path: Path):
@@ -58,7 +58,7 @@ def test_bundle_empty_dir_shows_error(tmp_path: Path):
58
58
  assert "No markdown files" in result.output
59
59
 
60
60
 
61
- def test_bundle_force_shows_removed(tmp_path: Path):
61
+ def test_bundle_force_shows_replaced(tmp_path: Path):
62
62
  src = tmp_path / "src"
63
63
  dst = tmp_path / "out"
64
64
  src.mkdir()
@@ -67,7 +67,7 @@ def test_bundle_force_shows_removed(tmp_path: Path):
67
67
 
68
68
  result = runner.invoke(app, ["bundle", str(src), str(dst), "--force"])
69
69
  assert result.exit_code == 0
70
- assert "Removed existing" in result.output
70
+ assert "Replaced existing" in result.output
71
71
 
72
72
 
73
73
  def test_bundle_strict_shows_error(tmp_path: Path):