kb0-mcp 0.1.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.
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .eggs/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ venv/
9
+ .pytest_cache/
10
+ .mypy_cache/
11
+ .ruff_cache/
kb0_mcp-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
kb0_mcp-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.4
2
+ Name: kb0-mcp
3
+ Version: 0.1.0
4
+ Summary: Python client for kb0 — the knowledge base layer for AI agents (MCP, markdown, git).
5
+ Project-URL: Homepage, https://kb0.dev
6
+ Project-URL: Repository, https://github.com/vitorchristoval/kb0
7
+ Project-URL: Documentation, https://github.com/vitorchristoval/kb0/tree/main/docs
8
+ Author: Vitor Christoval
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: ai-agents,knowledge-base,markdown,mcp,rag,vault
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Software Development :: Libraries
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: mcp>=1.0.0
21
+ Description-Content-Type: text/markdown
22
+
23
+ # kb0 (Python client)
24
+
25
+ Native Python client for [**kb0**](https://github.com/vitorchristoval/kb0) — the knowledge base layer for AI agents. Markdown-first, git-backed, MCP-native.
26
+
27
+ This package hides the MCP plumbing and gives you a clean async `VaultClient`.
28
+
29
+ ```bash
30
+ pip install kb0-mcp
31
+ ```
32
+
33
+ > The PyPI package is `kb0-mcp`; you still `import kb0` in code.
34
+ >
35
+ > **Requires the kb0 server.** This is a client — it spawns the `kb0` binary as a
36
+ > subprocess. Install it once with Node: `npm install -g kb0-mcp`, then `kb0 init my-vault`.
37
+
38
+ ## Quickstart
39
+
40
+ ```python
41
+ import asyncio
42
+ from kb0 import VaultClient
43
+
44
+ async def main():
45
+ async with VaultClient(vault="./my-vault", agent="my-bot") as kb:
46
+ # write a note (author, id, timestamps set by the server)
47
+ res = await kb.write(
48
+ "notes/auth.md",
49
+ title="Auth: we chose JWT",
50
+ content="Short-lived access + refresh tokens. See [[notes/security.md]].",
51
+ tags=["security"],
52
+ )
53
+ print("created", res["path"], "hash", res["hash"])
54
+
55
+ # search (hybrid by default)
56
+ hits = await kb.search("authentication design")
57
+ for r in hits["results"]:
58
+ print(r["score"], r["title"], r["path"])
59
+
60
+ # read + update with optimistic locking
61
+ note = await kb.read("notes/auth.md")
62
+ await kb.update(
63
+ "notes/auth.md",
64
+ content=note["content"] + "\n\nUpdate: rotating keys monthly.",
65
+ expected_hash=note["hash"],
66
+ )
67
+
68
+ asyncio.run(main())
69
+ ```
70
+
71
+ ## Configuration
72
+
73
+ `VaultClient` passes everything through to `kb0 serve`:
74
+
75
+ ```python
76
+ VaultClient(
77
+ vault="./my-vault", # vault directory
78
+ agent="my-bot", # agent identity (provenance + ACL)
79
+ openai_api_key="sk-...", # optional — enables semantic search
80
+ strict=False, # require .vault-policy.yaml if True
81
+ command="kb0", # override the binary path if needed
82
+ env={"KB0_EMBEDDING_MODEL": "text-embedding-3-large"},
83
+ )
84
+ ```
85
+
86
+ ## API
87
+
88
+ All methods are async and return plain dicts (the tool's structured output).
89
+
90
+ | Method | kb0 tool |
91
+ |---|---|
92
+ | `await kb.write(path, *, title, content, status="draft", tags=None)` | `vault.write` |
93
+ | `await kb.read(path)` | `vault.read` |
94
+ | `await kb.update(path, *, content, expected_hash, title=None, status=None, tags=None)` | `vault.update` |
95
+ | `await kb.delete(path)` | `vault.delete` |
96
+ | `await kb.search(query, *, mode="hybrid", ranking="rrf", limit=10, filters=None)` | `vault.search` |
97
+ | `await kb.list(*, prefix=None, tag=None, status=None, limit=50)` | `vault.list` |
98
+ | `await kb.recent(limit=10)` | `vault.recent` |
99
+ | `await kb.backlinks(path)` | `vault.backlinks` |
100
+ | `await kb.links(path)` | `vault.links` |
101
+ | `await kb.status()` | `vault.status` |
102
+
103
+ ## Errors
104
+
105
+ Failures raise typed exceptions you can catch:
106
+
107
+ ```python
108
+ from kb0 import KbConflictError, KbACLDeniedError, KbNotFoundError
109
+
110
+ try:
111
+ await kb.update("notes/x.md", content="...", expected_hash=stale_hash)
112
+ except KbConflictError:
113
+ note = await kb.read("notes/x.md") # re-read, get the current hash, retry
114
+ ```
115
+
116
+ `KbError` is the base class; `KbNotFoundError`, `KbConflictError`,
117
+ `KbValidationError`, and `KbACLDeniedError` are its subclasses.
118
+
119
+ ## Why a subprocess?
120
+
121
+ kb0 is an MCP server. The Python client launches `kb0 serve` over stdio and speaks
122
+ MCP to it — the same protocol Claude Desktop uses. Your vault stays a local folder
123
+ of markdown under git; this client is just an ergonomic way for Python agents to
124
+ talk to it. See the [main repo](https://github.com/vitorchristoval/kb0) for the
125
+ architecture.
126
+
127
+ ## License
128
+
129
+ Apache 2.0.
@@ -0,0 +1,107 @@
1
+ # kb0 (Python client)
2
+
3
+ Native Python client for [**kb0**](https://github.com/vitorchristoval/kb0) — the knowledge base layer for AI agents. Markdown-first, git-backed, MCP-native.
4
+
5
+ This package hides the MCP plumbing and gives you a clean async `VaultClient`.
6
+
7
+ ```bash
8
+ pip install kb0-mcp
9
+ ```
10
+
11
+ > The PyPI package is `kb0-mcp`; you still `import kb0` in code.
12
+ >
13
+ > **Requires the kb0 server.** This is a client — it spawns the `kb0` binary as a
14
+ > subprocess. Install it once with Node: `npm install -g kb0-mcp`, then `kb0 init my-vault`.
15
+
16
+ ## Quickstart
17
+
18
+ ```python
19
+ import asyncio
20
+ from kb0 import VaultClient
21
+
22
+ async def main():
23
+ async with VaultClient(vault="./my-vault", agent="my-bot") as kb:
24
+ # write a note (author, id, timestamps set by the server)
25
+ res = await kb.write(
26
+ "notes/auth.md",
27
+ title="Auth: we chose JWT",
28
+ content="Short-lived access + refresh tokens. See [[notes/security.md]].",
29
+ tags=["security"],
30
+ )
31
+ print("created", res["path"], "hash", res["hash"])
32
+
33
+ # search (hybrid by default)
34
+ hits = await kb.search("authentication design")
35
+ for r in hits["results"]:
36
+ print(r["score"], r["title"], r["path"])
37
+
38
+ # read + update with optimistic locking
39
+ note = await kb.read("notes/auth.md")
40
+ await kb.update(
41
+ "notes/auth.md",
42
+ content=note["content"] + "\n\nUpdate: rotating keys monthly.",
43
+ expected_hash=note["hash"],
44
+ )
45
+
46
+ asyncio.run(main())
47
+ ```
48
+
49
+ ## Configuration
50
+
51
+ `VaultClient` passes everything through to `kb0 serve`:
52
+
53
+ ```python
54
+ VaultClient(
55
+ vault="./my-vault", # vault directory
56
+ agent="my-bot", # agent identity (provenance + ACL)
57
+ openai_api_key="sk-...", # optional — enables semantic search
58
+ strict=False, # require .vault-policy.yaml if True
59
+ command="kb0", # override the binary path if needed
60
+ env={"KB0_EMBEDDING_MODEL": "text-embedding-3-large"},
61
+ )
62
+ ```
63
+
64
+ ## API
65
+
66
+ All methods are async and return plain dicts (the tool's structured output).
67
+
68
+ | Method | kb0 tool |
69
+ |---|---|
70
+ | `await kb.write(path, *, title, content, status="draft", tags=None)` | `vault.write` |
71
+ | `await kb.read(path)` | `vault.read` |
72
+ | `await kb.update(path, *, content, expected_hash, title=None, status=None, tags=None)` | `vault.update` |
73
+ | `await kb.delete(path)` | `vault.delete` |
74
+ | `await kb.search(query, *, mode="hybrid", ranking="rrf", limit=10, filters=None)` | `vault.search` |
75
+ | `await kb.list(*, prefix=None, tag=None, status=None, limit=50)` | `vault.list` |
76
+ | `await kb.recent(limit=10)` | `vault.recent` |
77
+ | `await kb.backlinks(path)` | `vault.backlinks` |
78
+ | `await kb.links(path)` | `vault.links` |
79
+ | `await kb.status()` | `vault.status` |
80
+
81
+ ## Errors
82
+
83
+ Failures raise typed exceptions you can catch:
84
+
85
+ ```python
86
+ from kb0 import KbConflictError, KbACLDeniedError, KbNotFoundError
87
+
88
+ try:
89
+ await kb.update("notes/x.md", content="...", expected_hash=stale_hash)
90
+ except KbConflictError:
91
+ note = await kb.read("notes/x.md") # re-read, get the current hash, retry
92
+ ```
93
+
94
+ `KbError` is the base class; `KbNotFoundError`, `KbConflictError`,
95
+ `KbValidationError`, and `KbACLDeniedError` are its subclasses.
96
+
97
+ ## Why a subprocess?
98
+
99
+ kb0 is an MCP server. The Python client launches `kb0 serve` over stdio and speaks
100
+ MCP to it — the same protocol Claude Desktop uses. Your vault stays a local folder
101
+ of markdown under git; this client is just an ergonomic way for Python agents to
102
+ talk to it. See the [main repo](https://github.com/vitorchristoval/kb0) for the
103
+ architecture.
104
+
105
+ ## License
106
+
107
+ Apache 2.0.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "kb0-mcp"
7
+ version = "0.1.0"
8
+ description = "Python client for kb0 — the knowledge base layer for AI agents (MCP, markdown, git)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "Vitor Christoval" }]
13
+ keywords = ["mcp", "ai-agents", "knowledge-base", "rag", "markdown", "vault"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Topic :: Software Development :: Libraries",
22
+ ]
23
+ dependencies = ["mcp>=1.0.0"]
24
+
25
+ [project.urls]
26
+ Homepage = "https://kb0.dev"
27
+ Repository = "https://github.com/vitorchristoval/kb0"
28
+ Documentation = "https://github.com/vitorchristoval/kb0/tree/main/docs"
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/kb0"]
32
+
33
+ [tool.pytest.ini_options]
34
+ testpaths = ["tests"]
@@ -0,0 +1,21 @@
1
+ """kb0 — Python client for the kb0 knowledge base layer for AI agents."""
2
+
3
+ from .client import VaultClient
4
+ from .errors import (
5
+ KbACLDeniedError,
6
+ KbConflictError,
7
+ KbError,
8
+ KbNotFoundError,
9
+ KbValidationError,
10
+ )
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ __all__ = [
15
+ "VaultClient",
16
+ "KbError",
17
+ "KbNotFoundError",
18
+ "KbConflictError",
19
+ "KbValidationError",
20
+ "KbACLDeniedError",
21
+ ]
@@ -0,0 +1,188 @@
1
+ """Async Python client for a kb0 vault over MCP (stdio)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from typing import Any
8
+
9
+ from .errors import error_from_text
10
+
11
+
12
+ def _text_of(result: Any) -> str:
13
+ parts: list[str] = []
14
+ for block in getattr(result, "content", None) or []:
15
+ text = getattr(block, "text", None)
16
+ if text:
17
+ parts.append(text)
18
+ return "\n".join(parts)
19
+
20
+
21
+ def _unwrap(result: Any) -> Any:
22
+ """Turn an MCP CallToolResult into a plain dict, or raise a typed KbError."""
23
+ if getattr(result, "isError", False):
24
+ raise error_from_text(_text_of(result))
25
+
26
+ structured = getattr(result, "structuredContent", None)
27
+ if structured is not None:
28
+ return structured
29
+
30
+ text = _text_of(result)
31
+ try:
32
+ return json.loads(text)
33
+ except (ValueError, TypeError):
34
+ return {"text": text}
35
+
36
+
37
+ class VaultClient:
38
+ """A thin client over the kb0 MCP server.
39
+
40
+ Spawns ``kb0 serve`` as a subprocess and exposes the 10 vault tools as
41
+ native async methods. Use as an async context manager::
42
+
43
+ async with VaultClient(vault="./my-vault", agent="my-bot") as kb:
44
+ await kb.write("notes/idea.md", title="Idea", content="...")
45
+ hits = await kb.search("auth design")
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ vault: str,
51
+ agent: str,
52
+ *,
53
+ command: str = "kb0",
54
+ env: dict[str, str] | None = None,
55
+ openai_api_key: str | None = None,
56
+ strict: bool = False,
57
+ ) -> None:
58
+ self.vault = str(vault)
59
+ self.agent = agent
60
+ self.command = command
61
+ self._extra_env = env
62
+ self._openai_api_key = openai_api_key
63
+ self._strict = strict
64
+ self._session: Any = None
65
+ self._stack: Any = None
66
+
67
+ async def __aenter__(self) -> "VaultClient":
68
+ # Imported lazily so the package can be imported (and unit-tested with a
69
+ # mock session) without the mcp SDK installed.
70
+ from contextlib import AsyncExitStack
71
+
72
+ from mcp import ClientSession, StdioServerParameters
73
+ from mcp.client.stdio import stdio_client
74
+
75
+ env = dict(os.environ)
76
+ if self._extra_env:
77
+ env.update(self._extra_env)
78
+ if self._openai_api_key:
79
+ env["OPENAI_API_KEY"] = self._openai_api_key
80
+
81
+ args = ["serve", "--agent", self.agent, "--vault", self.vault]
82
+ if self._strict:
83
+ args.append("--strict")
84
+
85
+ params = StdioServerParameters(command=self.command, args=args, env=env)
86
+
87
+ self._stack = AsyncExitStack()
88
+ read, write = await self._stack.enter_async_context(stdio_client(params))
89
+ session = await self._stack.enter_async_context(ClientSession(read, write))
90
+ await session.initialize()
91
+ self._session = session
92
+ return self
93
+
94
+ async def __aexit__(self, *_exc: Any) -> None:
95
+ if self._stack is not None:
96
+ await self._stack.aclose()
97
+ self._stack = None
98
+ self._session = None
99
+
100
+ async def _call(self, name: str, arguments: dict[str, Any]) -> Any:
101
+ if self._session is None:
102
+ raise RuntimeError("VaultClient is not connected — use 'async with VaultClient(...)'")
103
+ result = await self._session.call_tool(name, arguments)
104
+ return _unwrap(result)
105
+
106
+ # ── tools ──────────────────────────────────────────────────────────────────
107
+
108
+ async def write(
109
+ self,
110
+ path: str,
111
+ *,
112
+ title: str,
113
+ content: str,
114
+ status: str = "draft",
115
+ tags: list[str] | None = None,
116
+ ) -> dict[str, Any]:
117
+ return await self._call(
118
+ "vault.write",
119
+ {"path": path, "title": title, "content": content, "status": status, "tags": tags or []},
120
+ )
121
+
122
+ async def read(self, path: str) -> dict[str, Any]:
123
+ return await self._call("vault.read", {"path": path})
124
+
125
+ async def update(
126
+ self,
127
+ path: str,
128
+ *,
129
+ content: str,
130
+ expected_hash: str,
131
+ title: str | None = None,
132
+ status: str | None = None,
133
+ tags: list[str] | None = None,
134
+ ) -> dict[str, Any]:
135
+ args: dict[str, Any] = {"path": path, "content": content, "expectedHash": expected_hash}
136
+ if title is not None:
137
+ args["title"] = title
138
+ if status is not None:
139
+ args["status"] = status
140
+ if tags is not None:
141
+ args["tags"] = tags
142
+ return await self._call("vault.update", args)
143
+
144
+ async def delete(self, path: str) -> dict[str, Any]:
145
+ return await self._call("vault.delete", {"path": path})
146
+
147
+ async def search(
148
+ self,
149
+ query: str,
150
+ *,
151
+ mode: str = "hybrid",
152
+ ranking: str = "rrf",
153
+ limit: int = 10,
154
+ filters: dict[str, Any] | None = None,
155
+ ) -> dict[str, Any]:
156
+ args: dict[str, Any] = {"query": query, "mode": mode, "ranking": ranking, "limit": limit}
157
+ if filters is not None:
158
+ args["filters"] = filters
159
+ return await self._call("vault.search", args)
160
+
161
+ async def list(
162
+ self,
163
+ *,
164
+ prefix: str | None = None,
165
+ tag: str | None = None,
166
+ status: str | None = None,
167
+ limit: int = 50,
168
+ ) -> dict[str, Any]:
169
+ args: dict[str, Any] = {"limit": limit}
170
+ if prefix is not None:
171
+ args["prefix"] = prefix
172
+ if tag is not None:
173
+ args["tag"] = tag
174
+ if status is not None:
175
+ args["status"] = status
176
+ return await self._call("vault.list", args)
177
+
178
+ async def recent(self, limit: int = 10) -> dict[str, Any]:
179
+ return await self._call("vault.recent", {"limit": limit})
180
+
181
+ async def backlinks(self, path: str) -> dict[str, Any]:
182
+ return await self._call("vault.backlinks", {"path": path})
183
+
184
+ async def links(self, path: str) -> dict[str, Any]:
185
+ return await self._call("vault.links", {"path": path})
186
+
187
+ async def status(self) -> dict[str, Any]:
188
+ return await self._call("vault.status", {})
@@ -0,0 +1,49 @@
1
+ """Typed errors mirroring kb0's structured error codes."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class KbError(Exception):
7
+ """Base class for all kb0 errors returned by the vault."""
8
+
9
+ code = "ERROR"
10
+
11
+ def __init__(self, message: str) -> None:
12
+ super().__init__(message)
13
+ self.message = message
14
+
15
+
16
+ class KbNotFoundError(KbError):
17
+ code = "NOT_FOUND"
18
+
19
+
20
+ class KbConflictError(KbError):
21
+ """Raised when vault.update is called with a stale expected_hash."""
22
+
23
+ code = "CONFLICT"
24
+
25
+
26
+ class KbValidationError(KbError):
27
+ code = "VALIDATION"
28
+
29
+
30
+ class KbACLDeniedError(KbError):
31
+ code = "ACL_DENIED"
32
+
33
+
34
+ def error_from_text(text: str) -> KbError:
35
+ """Map a kb0 error message back to a typed exception.
36
+
37
+ kb0 formats each error code with a stable prefix, so matching on it is
38
+ reliable (both sides live in the same project).
39
+ """
40
+ stripped = text.strip()
41
+ if stripped.startswith("Not found"):
42
+ return KbNotFoundError(text)
43
+ if stripped.startswith("Conflict"):
44
+ return KbConflictError(text)
45
+ if stripped.startswith("Permission denied"):
46
+ return KbACLDeniedError(text)
47
+ if stripped.startswith("Validation"):
48
+ return KbValidationError(text)
49
+ return KbError(text)
@@ -0,0 +1,141 @@
1
+ """Unit tests for VaultClient — uses a fake MCP session, no subprocess needed."""
2
+
3
+ import unittest
4
+ from types import SimpleNamespace
5
+
6
+ from kb0 import (
7
+ KbACLDeniedError,
8
+ KbConflictError,
9
+ KbNotFoundError,
10
+ VaultClient,
11
+ )
12
+ from kb0.errors import error_from_text
13
+
14
+
15
+ def fake_result(structured=None, text=None, is_error=False):
16
+ content = [SimpleNamespace(text=text)] if text is not None else []
17
+ return SimpleNamespace(structuredContent=structured, content=content, isError=is_error)
18
+
19
+
20
+ class FakeSession:
21
+ """Records tool calls and returns a queued result per call."""
22
+
23
+ def __init__(self):
24
+ self.calls = []
25
+ self.results = []
26
+
27
+ def queue(self, result):
28
+ self.results.append(result)
29
+
30
+ async def call_tool(self, name, arguments):
31
+ self.calls.append((name, arguments))
32
+ return self.results.pop(0)
33
+
34
+
35
+ def connected_client():
36
+ client = VaultClient(vault="/tmp/vault", agent="test-agent")
37
+ client._session = FakeSession()
38
+ return client
39
+
40
+
41
+ class WriteTests(unittest.IsolatedAsyncioTestCase):
42
+ async def test_write_sends_expected_arguments(self):
43
+ kb = connected_client()
44
+ kb._session.queue(fake_result(structured={"path": "n.md", "hash": "a" * 64, "id": "uuid"}))
45
+
46
+ out = await kb.write("n.md", title="N", content="body", tags=["x"])
47
+
48
+ name, args = kb._session.calls[0]
49
+ self.assertEqual(name, "vault.write")
50
+ self.assertEqual(args["path"], "n.md")
51
+ self.assertEqual(args["title"], "N")
52
+ self.assertEqual(args["tags"], ["x"])
53
+ self.assertEqual(out["id"], "uuid")
54
+
55
+ async def test_write_defaults_status_and_tags(self):
56
+ kb = connected_client()
57
+ kb._session.queue(fake_result(structured={}))
58
+ await kb.write("n.md", title="N", content="c")
59
+ _, args = kb._session.calls[0]
60
+ self.assertEqual(args["status"], "draft")
61
+ self.assertEqual(args["tags"], [])
62
+
63
+
64
+ class UpdateTests(unittest.IsolatedAsyncioTestCase):
65
+ async def test_update_maps_expected_hash_to_camelcase(self):
66
+ kb = connected_client()
67
+ kb._session.queue(fake_result(structured={"path": "n.md", "hash": "b" * 64}))
68
+ await kb.update("n.md", content="v2", expected_hash="a" * 64)
69
+ _, args = kb._session.calls[0]
70
+ self.assertEqual(args["expectedHash"], "a" * 64)
71
+ self.assertNotIn("expected_hash", args)
72
+
73
+ async def test_update_omits_unset_optional_fields(self):
74
+ kb = connected_client()
75
+ kb._session.queue(fake_result(structured={}))
76
+ await kb.update("n.md", content="v2", expected_hash="h")
77
+ _, args = kb._session.calls[0]
78
+ self.assertNotIn("title", args)
79
+ self.assertNotIn("status", args)
80
+
81
+
82
+ class SearchListTests(unittest.IsolatedAsyncioTestCase):
83
+ async def test_search_passes_mode_and_limit(self):
84
+ kb = connected_client()
85
+ kb._session.queue(fake_result(structured={"results": [], "warnings": []}))
86
+ await kb.search("query", mode="keyword", limit=5)
87
+ _, args = kb._session.calls[0]
88
+ self.assertEqual(args["mode"], "keyword")
89
+ self.assertEqual(args["limit"], 5)
90
+
91
+ async def test_list_omits_unset_filters(self):
92
+ kb = connected_client()
93
+ kb._session.queue(fake_result(structured={"notes": [], "total": 0}))
94
+ await kb.list(tag="work")
95
+ _, args = kb._session.calls[0]
96
+ self.assertEqual(args["tag"], "work")
97
+ self.assertNotIn("prefix", args)
98
+
99
+
100
+ class ErrorTests(unittest.IsolatedAsyncioTestCase):
101
+ async def test_not_found_raises_typed_error(self):
102
+ kb = connected_client()
103
+ kb._session.queue(fake_result(text="Not found: `ghost.md`", is_error=True))
104
+ with self.assertRaises(KbNotFoundError):
105
+ await kb.read("ghost.md")
106
+
107
+ async def test_conflict_raises_typed_error(self):
108
+ kb = connected_client()
109
+ kb._session.queue(fake_result(text="Conflict at `n.md`: ...", is_error=True))
110
+ with self.assertRaises(KbConflictError):
111
+ await kb.update("n.md", content="x", expected_hash="wrong")
112
+
113
+ async def test_acl_denied_raises_typed_error(self):
114
+ kb = connected_client()
115
+ kb._session.queue(fake_result(text="Permission denied: not allowed", is_error=True))
116
+ with self.assertRaises(KbACLDeniedError):
117
+ await kb.write("secret.md", title="T", content="c")
118
+
119
+ async def test_call_without_connection_raises(self):
120
+ kb = VaultClient(vault="/tmp/v", agent="a")
121
+ with self.assertRaises(RuntimeError):
122
+ await kb.read("x.md")
123
+
124
+
125
+ class UnwrapTests(unittest.IsolatedAsyncioTestCase):
126
+ async def test_falls_back_to_json_text_when_no_structured(self):
127
+ kb = connected_client()
128
+ kb._session.queue(fake_result(text='{"ok": true}'))
129
+ out = await kb.status()
130
+ self.assertEqual(out, {"ok": True})
131
+
132
+
133
+ class ErrorMappingTests(unittest.TestCase):
134
+ def test_prefixes_map_to_codes(self):
135
+ self.assertIsInstance(error_from_text("Not found: x"), KbNotFoundError)
136
+ self.assertIsInstance(error_from_text("Conflict at x"), KbConflictError)
137
+ self.assertIsInstance(error_from_text("Permission denied: x"), KbACLDeniedError)
138
+
139
+
140
+ if __name__ == "__main__":
141
+ unittest.main()