okf-cli 0.7.0__tar.gz → 0.8.1__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 (57) hide show
  1. okf_cli-0.8.1/.agents/skills/wiki/SKILL.md +126 -0
  2. okf_cli-0.8.1/.github/workflows/publish.yml +40 -0
  3. {okf_cli-0.7.0 → okf_cli-0.8.1}/.github/workflows/test.yml +2 -1
  4. okf_cli-0.8.1/.last-update.json +1 -0
  5. {okf_cli-0.7.0 → okf_cli-0.8.1}/PKG-INFO +39 -1
  6. okf_cli-0.8.1/README.md +79 -0
  7. {okf_cli-0.7.0 → okf_cli-0.8.1}/pyproject.toml +5 -2
  8. {okf_cli-0.7.0 → okf_cli-0.8.1}/src/okf/api.py +126 -67
  9. {okf_cli-0.7.0 → okf_cli-0.8.1}/src/okf/cli.py +2 -0
  10. {okf_cli-0.7.0 → okf_cli-0.8.1}/src/okf/commands/bundle.py +4 -1
  11. okf_cli-0.8.1/src/okf/commands/serve_mcp.py +97 -0
  12. {okf_cli-0.7.0 → okf_cli-0.8.1}/tests/test_api.py +46 -3
  13. {okf_cli-0.7.0 → okf_cli-0.8.1}/tests/test_cli.py +2 -2
  14. okf_cli-0.8.1/tests/test_mcp.py +133 -0
  15. okf_cli-0.8.1/uv.lock +1602 -0
  16. {okf_cli-0.7.0 → okf_cli-0.8.1}/wiki/architecture.md +23 -2
  17. {okf_cli-0.7.0 → okf_cli-0.8.1}/wiki/domain-model.md +28 -4
  18. {okf_cli-0.7.0 → okf_cli-0.8.1}/wiki/operations.md +15 -11
  19. {okf_cli-0.7.0 → okf_cli-0.8.1}/wiki/quickstart.md +18 -1
  20. {okf_cli-0.7.0 → okf_cli-0.8.1}/wiki/testing.md +5 -1
  21. {okf_cli-0.7.0 → okf_cli-0.8.1}/wiki/workflows.md +27 -2
  22. okf_cli-0.7.0/.last-update.json +0 -1
  23. okf_cli-0.7.0/README.md +0 -43
  24. okf_cli-0.7.0/uv.lock +0 -240
  25. {okf_cli-0.7.0 → okf_cli-0.8.1}/.gitignore +0 -0
  26. {okf_cli-0.7.0 → okf_cli-0.8.1}/AGENTS.md +0 -0
  27. {okf_cli-0.7.0 → okf_cli-0.8.1}/LICENSE +0 -0
  28. {okf_cli-0.7.0 → okf_cli-0.8.1}/SPEC/OKF_SPEC_V0_1.md +0 -0
  29. {okf_cli-0.7.0 → okf_cli-0.8.1}/SPEC/OKF_SPEC_V0_2.md +0 -0
  30. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/.okfignore +0 -0
  31. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/README.md +0 -0
  32. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/blank-line/no-blank.md +0 -0
  33. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/blank-line/with-blank.md +0 -0
  34. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/computations/revenue.md +0 -0
  35. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/datasets/sales.md +0 -0
  36. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/domain.md +0 -0
  37. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/loose/deep/no-heading.md +0 -0
  38. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/loose/no-desc.md +0 -0
  39. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/loose/no-title.md +0 -0
  40. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/metrics/income-statement.md +0 -0
  41. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/playbooks/incident-response.md +0 -0
  42. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/playbooks/oncall-guide.md +0 -0
  43. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/references/revenue-recognition.md +0 -0
  44. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/smoke-ignore.md +0 -0
  45. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/tables/customers.md +0 -0
  46. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/tables/orders.md +0 -0
  47. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/tables/partitions/2026/q1/jan/january.md +0 -0
  48. {okf_cli-0.7.0 → okf_cli-0.8.1}/example/tables/partitions/daily.md +0 -0
  49. {okf_cli-0.7.0 → okf_cli-0.8.1}/skills/okf-cli/SKILL.md +0 -0
  50. {okf_cli-0.7.0 → okf_cli-0.8.1}/skills/writing-knowledge-base/SKILL.md +0 -0
  51. {okf_cli-0.7.0 → okf_cli-0.8.1}/src/okf/__init__.py +0 -0
  52. {okf_cli-0.7.0 → okf_cli-0.8.1}/src/okf/commands/__init__.py +0 -0
  53. {okf_cli-0.7.0 → okf_cli-0.8.1}/src/okf/commands/list.py +0 -0
  54. {okf_cli-0.7.0 → okf_cli-0.8.1}/src/okf/commands/read.py +0 -0
  55. {okf_cli-0.7.0 → okf_cli-0.8.1}/src/okf/commands/validate.py +0 -0
  56. {okf_cli-0.7.0 → okf_cli-0.8.1}/src/okf/core.py +0 -0
  57. {okf_cli-0.7.0 → okf_cli-0.8.1}/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,40 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v0.*.*"
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ publish:
13
+ runs-on: ubuntu-latest
14
+ permissions:
15
+ contents: read
16
+ id-token: write
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+ - uses: actions/setup-python@v5
20
+ with:
21
+ python-version: "3.11"
22
+ - uses: astral-sh/setup-uv@v3
23
+ - name: Verify tag matches package version
24
+ run: |
25
+ tag="$GITHUB_REF_NAME"
26
+ if [[ ! "$tag" =~ ^v0\.[0-9]+\.[0-9]+$ ]]; then
27
+ echo "Tag $tag must have the form v0.x.x" >&2
28
+ exit 1
29
+ fi
30
+
31
+ tag_version="${tag#v}"
32
+ package_version="$(uv version --short)"
33
+ if [[ "$tag_version" != "$package_version" ]]; then
34
+ echo "Tag version $tag_version does not match pyproject.toml version $package_version" >&2
35
+ exit 1
36
+ fi
37
+ - name: Build distributions
38
+ run: uv build
39
+ - name: Publish distributions to PyPI
40
+ run: uv publish
@@ -10,9 +10,10 @@ jobs:
10
10
  python-version: ["3.11"]
11
11
  steps:
12
12
  - uses: actions/checkout@v4
13
- - uses: astral-sh/setup-uv@v3
13
+ - uses: actions/setup-python@v5
14
14
  with:
15
15
  python-version: ${{ matrix.python-version }}
16
+ - uses: astral-sh/setup-uv@v3
16
17
  - run: uv sync
17
18
  - run: uvx ruff check .
18
19
  - run: uvx ruff format --check .
@@ -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.1
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,45 @@ 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; `--host 0.0.0.0` listens on all IPv4 interfaces. The server exposes read-only `list_concepts` and `read_concept` tools. Add `--token <secret>` to require the matching `Authorization: Bearer <secret>` header on MCP requests; without it, requests are unauthenticated. For example:
75
+
76
+ ```bash
77
+ uv run okf serve-mcp example_knowledge_base --token "$OKF_MCP_TOKEN"
78
+ ```
79
+
80
+ Use HTTPS (typically through a TLS-terminating proxy) when serving beyond localhost. The token is a command-line argument and may be visible in shell history or process listings; use this option only on a trusted network, and do not treat it as a replacement for TLS.
81
+
82
+ #### HTTPS with Caddy
83
+
84
+ When Caddy runs on the same machine, leave the MCP server bound to its default `127.0.0.1` address and let Caddy handle public HTTPS:
85
+
86
+ ```caddyfile
87
+ mcp.example.com {
88
+ reverse_proxy 127.0.0.1:8000
89
+ }
90
+ ```
91
+
92
+ Start the MCP server with authentication enabled:
93
+
94
+ ```bash
95
+ uv run okf serve-mcp example_knowledge_base --token "$OKF_MCP_TOKEN"
96
+ ```
97
+
98
+ Clients connect to `https://mcp.example.com/mcp` and send `Authorization: Bearer <token>`. Keep port `8000` private; Caddy should be the public entry point. Caddy can provision HTTPS automatically when the domain points to the server and is reachable on the required ports.
99
+
62
100
  ## Quick example
63
101
 
64
102
  ```bash
@@ -0,0 +1,79 @@
1
+ # okf-cli — Open Knowledge Format tooling
2
+
3
+ Convert plain markdown directories into [OKF](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)-conformant knowledge bundles. `okf bundle` generates YAML frontmatter, concept types, provenance, and per-directory `index.md` files; `okf validate`, `okf list`, and `okf read` consume the resulting bundle.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ uv tool install okf-cli
9
+ ```
10
+
11
+ ### Dev quickstart
12
+
13
+ ```bash
14
+ uv sync
15
+ uv run okf --help
16
+ uv run okf --version
17
+ ```
18
+
19
+ ## Commands
20
+
21
+ | Command | Purpose |
22
+ | ------------------------------------- | -------------------------------------------- |
23
+ | `okf bundle <input-dir> [output-dir]` | Convert markdown into an OKF bundle |
24
+ | `okf validate <directory>` | Check OKF v0.2 §11 conformance |
25
+ | `okf list <directory>` | List concepts (ID, type, title, description) |
26
+ | `okf read <directory> <concept-id>` | Print a concept by ID |
27
+ | `okf serve-mcp <directory>` | Serve a conformant bundle over MCP HTTP |
28
+
29
+ Run `okf <command> --help` for options such as `--default-type`, `--force`, `--strict`, and `--dry-run`.
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; `--host 0.0.0.0` listens on all IPv4 interfaces. The server exposes read-only `list_concepts` and `read_concept` tools. Add `--token <secret>` to require the matching `Authorization: Bearer <secret>` header on MCP requests; without it, requests are unauthenticated. For example:
41
+
42
+ ```bash
43
+ uv run okf serve-mcp example_knowledge_base --token "$OKF_MCP_TOKEN"
44
+ ```
45
+
46
+ Use HTTPS (typically through a TLS-terminating proxy) when serving beyond localhost. The token is a command-line argument and may be visible in shell history or process listings; use this option only on a trusted network, and do not treat it as a replacement for TLS.
47
+
48
+ #### HTTPS with Caddy
49
+
50
+ When Caddy runs on the same machine, leave the MCP server bound to its default `127.0.0.1` address and let Caddy handle public HTTPS:
51
+
52
+ ```caddyfile
53
+ mcp.example.com {
54
+ reverse_proxy 127.0.0.1:8000
55
+ }
56
+ ```
57
+
58
+ Start the MCP server with authentication enabled:
59
+
60
+ ```bash
61
+ uv run okf serve-mcp example_knowledge_base --token "$OKF_MCP_TOKEN"
62
+ ```
63
+
64
+ Clients connect to `https://mcp.example.com/mcp` and send `Authorization: Bearer <token>`. Keep port `8000` private; Caddy should be the public entry point. Caddy can provision HTTPS automatically when the domain points to the server and is reachable on the required ports.
65
+
66
+ ## Quick example
67
+
68
+ ```bash
69
+ uv run okf bundle example --default-type reference --force
70
+ uv run okf validate example_knowledge_base
71
+ uv run okf list example_knowledge_base
72
+ uv run okf read example_knowledge_base tables/customers
73
+ ```
74
+
75
+ ## Documentation
76
+
77
+ - Detailed user and contributor docs: [wiki/quickstart.md](wiki/quickstart.md)
78
+ - Agent contributor context: [AGENTS.md](AGENTS.md)
79
+ - OKF v0.2 specification: [SPEC/OKF_SPEC_V0_2.md](SPEC/OKF_SPEC_V0_2.md)
@@ -1,12 +1,15 @@
1
1
  [project]
2
2
  name = "okf-cli"
3
- version = "0.7.0"
3
+ version = "0.8.1"
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,