@dikolab/kbdb 0.4.3 → 0.6.0

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 (224) hide show
  1. package/CLA.md +68 -0
  2. package/LICENSE +676 -12
  3. package/LICENSING.md +58 -0
  4. package/README.md +50 -27
  5. package/README.md.bak +320 -0
  6. package/dist/README.md +320 -0
  7. package/dist/{chunk-BJXEVALU.mjs → chunk-QLJ33C74.mjs} +44 -44
  8. package/dist/chunk-QLJ33C74.mjs.map +7 -0
  9. package/dist/cli.cjs +550 -232
  10. package/dist/cli.cjs.map +4 -4
  11. package/dist/cli.d.ts +0 -8
  12. package/dist/cli.mjs +483 -154
  13. package/dist/cli.mjs.map +4 -4
  14. package/dist/kbdb-worker.cjs +36 -5
  15. package/dist/kbdb-worker.cjs.map +3 -3
  16. package/dist/mod.cjs +89 -30
  17. package/dist/mod.cjs.map +4 -4
  18. package/dist/mod.mjs +88 -30
  19. package/dist/mod.mjs.map +4 -4
  20. package/dist/src/cli.d.ts +0 -8
  21. package/dist/src/shared/cli/constants/defaults.constant.d.ts +1 -1
  22. package/dist/src/shared/cli/constants/recfile-command-field-map.constant.d.ts +8 -0
  23. package/dist/src/shared/cli/constants/recfile-field-maps.constant.d.ts +21 -0
  24. package/dist/src/shared/cli/functions/compute-directory-level.function.d.ts +14 -0
  25. package/dist/src/shared/cli/functions/dispatch-command.function.d.ts +2 -28
  26. package/dist/src/shared/cli/functions/format-command-output.function.d.ts +14 -0
  27. package/dist/src/shared/cli/functions/format-db-not-found.function.d.ts +20 -0
  28. package/dist/src/shared/cli/functions/format-output.function.d.ts +1 -0
  29. package/dist/src/shared/cli/functions/format-recfile-output.function.d.ts +11 -0
  30. package/dist/src/shared/cli/functions/render-recfile-value.function.d.ts +11 -0
  31. package/dist/src/shared/cli/functions/resolve-db-dir.function.d.ts +24 -0
  32. package/dist/src/shared/cli/functions/resolve-recfile-key.function.d.ts +9 -0
  33. package/dist/src/shared/cli/functions/run-db-path.function.d.ts +10 -0
  34. package/dist/src/shared/cli/functions/run-export.function.d.ts +8 -4
  35. package/dist/src/shared/cli/functions/run-import.function.d.ts +4 -0
  36. package/dist/src/shared/cli/functions/run-learn.function.d.ts +12 -0
  37. package/dist/src/shared/cli/index.d.ts +4 -1
  38. package/dist/src/shared/cli/typings/cli-options.interface.d.ts +9 -2
  39. package/dist/src/shared/cli/typings/db-resolution.interface.d.ts +9 -0
  40. package/dist/src/shared/cli/typings/recfile-field-map.type.d.ts +10 -0
  41. package/dist/src/shared/version/constants/version.constant.d.ts +1 -1
  42. package/dist/src/shared/wasm-codec/functions/decode-option-u8.function.d.ts +9 -0
  43. package/dist/src/shared/wasm-codec/functions/decode-section-records.function.d.ts +4 -0
  44. package/dist/src/shared/wasm-codec/functions/encode-add-section-params.function.d.ts +2 -45
  45. package/dist/src/shared/wasm-codec/functions/encode-update-section-params.function.d.ts +10 -1
  46. package/dist/src/shared/wasm-codec/index.d.ts +1 -1
  47. package/dist/src/shared/wasm-codec/typings/add-section-input.model.d.ts +6 -0
  48. package/dist/src/shared/wasm-codec/typings/section-record-trailing.model.d.ts +5 -0
  49. package/dist/src/shared/wasm-codec/typings/section-record.model.d.ts +5 -0
  50. package/dist/src/shared/worker-client/functions/build-deno-permissions.function.d.ts +11 -0
  51. package/dist/src/shared/worker-client/functions/read-crash-reason.function.d.ts +9 -0
  52. package/dist/src/shared/worker-client/functions/resolve-spawn-script.function.d.ts +6 -0
  53. package/dist/src/shared/worker-client/functions/spawn-daemon.function.d.ts +1 -1
  54. package/dist/src/shared/worker-client/typings/section.model.d.ts +5 -0
  55. package/dist/src/shared/worker-client/typings/worker-client-options.interface.d.ts +0 -6
  56. package/dist/src/shared/worker-daemon/functions/count-files.function.d.ts +12 -0
  57. package/dist/src/shared/worker-daemon/functions/handle-import.function.d.ts +2 -0
  58. package/dist/src/shared/worker-daemon/functions/handle-read-ops.function.d.ts +8 -0
  59. package/dist/src/shared/worker-daemon/functions/validate-daemon-path.function.d.ts +15 -0
  60. package/dist/src/worker.d.ts +0 -7
  61. package/dist/wasm/default-embedding/kbdb_default_embedding_bg.wasm +0 -0
  62. package/dist/wasm/default-embedding/package.json +1 -1
  63. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  64. package/dist/wasm/fs-database/package.json +1 -1
  65. package/dist/wasm/fs-migration/kbdb_fs_migration_bg.wasm +0 -0
  66. package/dist/wasm/fs-migration/package.json +1 -1
  67. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  68. package/dist/wasm/kb-worker/package.json +1 -1
  69. package/dist/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
  70. package/dist/wasm/query-parser/package.json +1 -1
  71. package/dist/worker.d.ts +0 -7
  72. package/dist/worker.mjs +37 -6
  73. package/dist/worker.mjs.map +3 -3
  74. package/package.json +13 -12
  75. package/dist/chunk-BJXEVALU.mjs.map +0 -7
  76. package/dist/src/shared/cli/functions/resolve-raw-db-path.function.d.ts +0 -10
  77. package/docs/details/README.md +0 -30
  78. package/docs/details/agent-tooling.md +0 -132
  79. package/docs/details/cli.md +0 -777
  80. package/docs/details/knowledge-base.md +0 -180
  81. package/docs/details/library-api.md +0 -495
  82. package/docs/details/mcp-server.md +0 -482
  83. package/docs/details/search-and-ranking.md +0 -575
  84. package/docs/details/storage.md +0 -531
  85. package/docs/goals/agents.md +0 -751
  86. package/docs/goals/architecture.svg +0 -198
  87. package/docs/goals/auto-capture.md +0 -378
  88. package/docs/goals/benchmarking.md +0 -296
  89. package/docs/goals/cli.md +0 -2654
  90. package/docs/goals/concurrency.md +0 -259
  91. package/docs/goals/content-composer.md +0 -609
  92. package/docs/goals/content-parser.md +0 -279
  93. package/docs/goals/database.md +0 -1679
  94. package/docs/goals/document.md +0 -368
  95. package/docs/goals/hybrid-search.md +0 -465
  96. package/docs/goals/mcp.md +0 -1541
  97. package/docs/goals/overview.md +0 -124
  98. package/docs/goals/query-parser.md +0 -373
  99. package/docs/goals/query-result.md +0 -860
  100. package/docs/goals/semantic-dedup.md +0 -233
  101. package/docs/goals/skills.md +0 -810
  102. package/docs/goals/sync.md +0 -217
  103. package/docs/goals/worker-client.md +0 -1005
  104. package/docs/goals/worker-daemon.md +0 -1547
  105. package/docs/modules/overview.md +0 -319
  106. package/docs/modules/rust/embedding/module.md +0 -91
  107. package/docs/modules/rust/fs-database/functions/document.md +0 -48
  108. package/docs/modules/rust/fs-database/functions/integrity.md +0 -79
  109. package/docs/modules/rust/fs-database/functions/io.md +0 -87
  110. package/docs/modules/rust/fs-database/functions/module.md +0 -22
  111. package/docs/modules/rust/fs-database/functions/query-exec.md +0 -44
  112. package/docs/modules/rust/fs-database/functions/section.md +0 -76
  113. package/docs/modules/rust/fs-database/indexes/btree.md +0 -35
  114. package/docs/modules/rust/fs-database/indexes/corpus.md +0 -61
  115. package/docs/modules/rust/fs-database/indexes/inverted.md +0 -60
  116. package/docs/modules/rust/fs-database/indexes/module.md +0 -64
  117. package/docs/modules/rust/fs-database/indexes/positional.md +0 -39
  118. package/docs/modules/rust/fs-database/indexes/vectors.md +0 -110
  119. package/docs/modules/rust/fs-database/module.md +0 -150
  120. package/docs/modules/rust/fs-database/types/catalog.md +0 -53
  121. package/docs/modules/rust/fs-database/types/module.md +0 -12
  122. package/docs/modules/rust/fs-database/types/section.md +0 -127
  123. package/docs/modules/rust/kb-worker/functions/compose.md +0 -57
  124. package/docs/modules/rust/kb-worker/functions/module.md +0 -20
  125. package/docs/modules/rust/kb-worker/functions/retrieve.md +0 -194
  126. package/docs/modules/rust/kb-worker/functions/search.md +0 -173
  127. package/docs/modules/rust/kb-worker/functions/write.md +0 -172
  128. package/docs/modules/rust/kb-worker/module.md +0 -171
  129. package/docs/modules/rust/kb-worker/types/cache.md +0 -90
  130. package/docs/modules/rust/kb-worker/types/context.md +0 -26
  131. package/docs/modules/rust/kb-worker/types/module.md +0 -16
  132. package/docs/modules/rust/kb-worker/types/status.md +0 -29
  133. package/docs/modules/rust/kb-worker/types/token.md +0 -50
  134. package/docs/modules/rust/overview.md +0 -531
  135. package/docs/modules/rust/query-parser/functions/extract.md +0 -56
  136. package/docs/modules/rust/query-parser/functions/module.md +0 -18
  137. package/docs/modules/rust/query-parser/functions/parse.md +0 -33
  138. package/docs/modules/rust/query-parser/functions/pipeline.md +0 -9
  139. package/docs/modules/rust/query-parser/functions/rank.md +0 -85
  140. package/docs/modules/rust/query-parser/module.md +0 -131
  141. package/docs/modules/rust/query-parser/types/cache.md +0 -39
  142. package/docs/modules/rust/query-parser/types/keyphrase.md +0 -71
  143. package/docs/modules/rust/query-parser/types/module.md +0 -18
  144. package/docs/modules/rust/query-parser/types/token.md +0 -46
  145. package/docs/modules/rust/shared/content-composer/functions.md +0 -114
  146. package/docs/modules/rust/shared/content-composer/module.md +0 -147
  147. package/docs/modules/rust/shared/content-composer/types.md +0 -93
  148. package/docs/modules/rust/shared/content-parser/functions.md +0 -72
  149. package/docs/modules/rust/shared/content-parser/module.md +0 -99
  150. package/docs/modules/rust/shared/content-parser/types.md +0 -71
  151. package/docs/modules/rust/shared/corpus/module.md +0 -24
  152. package/docs/modules/rust/shared/corpus/types.md +0 -141
  153. package/docs/modules/rust/shared/document/module.md +0 -25
  154. package/docs/modules/rust/shared/document/types.md +0 -154
  155. package/docs/modules/rust/shared/encode/module.md +0 -22
  156. package/docs/modules/rust/shared/encode/traits.md +0 -304
  157. package/docs/modules/rust/shared/error/module.md +0 -28
  158. package/docs/modules/rust/shared/error/types.md +0 -302
  159. package/docs/modules/rust/shared/kbid/module.md +0 -24
  160. package/docs/modules/rust/shared/kbid/types.md +0 -147
  161. package/docs/modules/rust/shared/memory/functions.md +0 -209
  162. package/docs/modules/rust/shared/memory/module.md +0 -24
  163. package/docs/modules/rust/shared/module.md +0 -196
  164. package/docs/modules/rust/shared/pipeline/functions.md +0 -141
  165. package/docs/modules/rust/shared/pipeline/module.md +0 -62
  166. package/docs/modules/rust/shared/pipeline/types.md +0 -43
  167. package/docs/modules/rust/shared/query/module.md +0 -27
  168. package/docs/modules/rust/shared/query/types.md +0 -236
  169. package/docs/modules/rust/shared/section/module.md +0 -25
  170. package/docs/modules/rust/shared/section/types.md +0 -294
  171. package/docs/modules/rust/shared/term/module.md +0 -25
  172. package/docs/modules/rust/shared/term/types.md +0 -139
  173. package/docs/modules/typescript/cli.md +0 -131
  174. package/docs/modules/typescript/kbdb-worker.md +0 -150
  175. package/docs/modules/typescript/overview.md +0 -400
  176. package/docs/modules/typescript/shared/auto-capture/module.md +0 -73
  177. package/docs/modules/typescript/shared/cli/constants.md +0 -23
  178. package/docs/modules/typescript/shared/cli/functions.md +0 -809
  179. package/docs/modules/typescript/shared/cli/module.md +0 -138
  180. package/docs/modules/typescript/shared/cli/typings.md +0 -197
  181. package/docs/modules/typescript/shared/embedding/functions.md +0 -200
  182. package/docs/modules/typescript/shared/embedding/module.md +0 -77
  183. package/docs/modules/typescript/shared/embedding/typings.md +0 -124
  184. package/docs/modules/typescript/shared/hash/functions.md +0 -20
  185. package/docs/modules/typescript/shared/hash/module.md +0 -21
  186. package/docs/modules/typescript/shared/log/constants.md +0 -82
  187. package/docs/modules/typescript/shared/log/functions.md +0 -131
  188. package/docs/modules/typescript/shared/log/module.md +0 -153
  189. package/docs/modules/typescript/shared/log/typings.md +0 -82
  190. package/docs/modules/typescript/shared/mcp/classes.md +0 -179
  191. package/docs/modules/typescript/shared/mcp/functions.md +0 -386
  192. package/docs/modules/typescript/shared/mcp/module.md +0 -160
  193. package/docs/modules/typescript/shared/mcp/typings.md +0 -529
  194. package/docs/modules/typescript/shared/module.md +0 -110
  195. package/docs/modules/typescript/shared/platform/functions.md +0 -42
  196. package/docs/modules/typescript/shared/platform/module.md +0 -25
  197. package/docs/modules/typescript/shared/runtime/functions.md +0 -26
  198. package/docs/modules/typescript/shared/runtime/module.md +0 -27
  199. package/docs/modules/typescript/shared/runtime/typings.md +0 -13
  200. package/docs/modules/typescript/shared/version/module.md +0 -27
  201. package/docs/modules/typescript/shared/wasm-codec/functions.md +0 -391
  202. package/docs/modules/typescript/shared/wasm-codec/module.md +0 -98
  203. package/docs/modules/typescript/shared/worker-client/classes.md +0 -264
  204. package/docs/modules/typescript/shared/worker-client/functions.md +0 -175
  205. package/docs/modules/typescript/shared/worker-client/module.md +0 -92
  206. package/docs/modules/typescript/shared/worker-client/typings.md +0 -511
  207. package/docs/modules/typescript/shared/worker-daemon/classes.md +0 -239
  208. package/docs/modules/typescript/shared/worker-daemon/constants.md +0 -37
  209. package/docs/modules/typescript/shared/worker-daemon/functions.md +0 -234
  210. package/docs/modules/typescript/shared/worker-daemon/module.md +0 -118
  211. package/docs/modules/typescript/shared/worker-daemon/typings.md +0 -132
  212. package/docs/overview.md +0 -191
  213. package/docs/release-notes/0.1.0.md +0 -189
  214. package/docs/release-notes/0.1.1.md +0 -46
  215. package/docs/release-notes/0.1.2.md +0 -38
  216. package/docs/release-notes/0.1.3.md +0 -42
  217. package/docs/release-notes/0.2.0.md +0 -147
  218. package/docs/release-notes/0.3.0.md +0 -89
  219. package/docs/release-notes/0.3.1.md +0 -121
  220. package/docs/release-notes/0.3.2.md +0 -64
  221. package/docs/release-notes/0.4.0.md +0 -80
  222. package/docs/release-notes/0.4.1.md +0 -149
  223. package/docs/release-notes/0.4.3.md +0 -60
  224. package/docs/release-notes/README.md +0 -13
package/docs/goals/mcp.md DELETED
@@ -1,1541 +0,0 @@
1
- # MCP -- Model Context Protocol Server
2
-
3
- *An MCP server mode that exposes the knowledge base
4
- to AI agents -- search, retrieve, and manage knowledge
5
- programmatically over the Model Context Protocol.*
6
-
7
- ## Goal
8
-
9
- When invoked as `kbdb mcp`, the executable starts as a
10
- long-lived MCP server. It communicates with the AI
11
- agent host over **stdio** using **JSON-RPC 2.0** and
12
- delegates all knowledge base operations to the worker
13
- daemon via the worker client module (see
14
- [Worker Client](worker-client.md)).
15
-
16
- The MCP server exposes the knowledge base's search,
17
- retrieval, and content management capabilities as MCP
18
- tools and resources. AI agents -- Claude, LangChain
19
- agents, custom harnesses, or any MCP-compatible
20
- client -- interact with the knowledge base through
21
- these primitives.
22
-
23
- The MCP server has no knowledge of which AI agent is
24
- connected. It serves any MCP-compatible client
25
- identically.
26
-
27
- ## Invocation
28
-
29
- ```
30
- kbdb mcp [--db <path>] [--timeout-ms <ms>]
31
- [--retry <n>] [--non-interactive]
32
- ```
33
-
34
- All flags are optional. `--db` specifies the path
35
- to the `.kbdb` database directory. If omitted, the
36
- server reads the `KBDB_DB_DIR` environment variable,
37
- then falls back to the current working directory.
38
-
39
- Resolution order:
40
-
41
- 1. `--db <path>` command-line flag.
42
- 2. `KBDB_DB_DIR` environment variable.
43
- 3. Current working directory.
44
-
45
- ### Environment Variables
46
-
47
- | Variable | Description |
48
- |-----------------------|-------------------------|
49
- | `KBDB_DB_DIR` | Fallback database directory when `--db` is not specified |
50
- | `KBDB_DAEMON_TIMEOUT` | Request timeout fallback (ms); default 30 000 |
51
- | `KBDB_RETRY` | Retry count fallback; default 5 |
52
- | `KBDB_LOG_LEVEL` | Log verbosity: `debug`, `info`, `warning`, `error` |
53
- | `KBDB_NON_INTERACTIVE`| Suppress prompts (`1` or `true`) |
54
-
55
- See [CLI -- Run Modes](cli.md#run-modes) for how
56
- the `kbdb` executable dispatches to MCP mode.
57
-
58
- ## Startup Health Check
59
-
60
- When the MCP server starts, it runs
61
- `client.integrityCheck()` automatically after the
62
- worker daemon connection is established. If the
63
- check returns `ok: false`, the server emits a
64
- `notifications/message` log with level `warning`
65
- listing the error summary. The server continues to
66
- operate -- health issues are not fatal. This ensures
67
- corruption surfaces before it produces wrong answers.
68
-
69
- ## Installation and Wiring
70
-
71
- Installation is the same as the CLI:
72
-
73
- - **Node.js**: `npm install -g @dikolab/kbdb`
74
- - **Deno**: `deno install` or `deno add @dikolab/kbdb`
75
- (via [jsr.io](https://jsr.io))
76
-
77
- To wire the MCP server to an AI agent, add a server
78
- entry to the agent host's MCP configuration.
79
-
80
- ### Claude Desktop
81
-
82
- Add to `claude_desktop_config.json`:
83
-
84
- ```json
85
- {
86
- "mcpServers": {
87
- "kbdb": {
88
- "command": "npx",
89
- "args": [
90
- "@dikolab/kbdb", "mcp",
91
- "--db", "/path/to/.kbdb"
92
- ]
93
- }
94
- }
95
- }
96
- ```
97
-
98
- ### Claude Code
99
-
100
- Add to `.claude/settings.json` or project settings:
101
-
102
- ```json
103
- {
104
- "mcpServers": {
105
- "kbdb": {
106
- "command": "npx",
107
- "args": [
108
- "@dikolab/kbdb", "mcp",
109
- "--db", "/path/to/.kbdb"
110
- ]
111
- }
112
- }
113
- }
114
- ```
115
-
116
- ### Deno
117
-
118
- ```json
119
- {
120
- "mcpServers": {
121
- "kbdb": {
122
- "command": "deno",
123
- "args": [
124
- "run", "--allow-all",
125
- "jsr:@dikolab/kbdb", "mcp",
126
- "--db", "/path/to/.kbdb"
127
- ]
128
- }
129
- }
130
- }
131
- ```
132
-
133
- ### Environment Variable
134
-
135
- The `--db` flag can be replaced by `KBDB_DB_DIR`:
136
-
137
- ```json
138
- {
139
- "mcpServers": {
140
- "kbdb": {
141
- "command": "npx",
142
- "args": ["@dikolab/kbdb", "mcp"],
143
- "env": {
144
- "KBDB_DB_DIR": "/path/to/.kbdb"
145
- }
146
- }
147
- }
148
- }
149
- ```
150
-
151
- ### Multiple Knowledge Bases
152
-
153
- Register multiple server instances pointing to
154
- different databases:
155
-
156
- ```json
157
- {
158
- "mcpServers": {
159
- "kbdb-docs": {
160
- "command": "npx",
161
- "args": [
162
- "@dikolab/kbdb", "mcp",
163
- "--db", "/home/user/docs/.kbdb"
164
- ]
165
- },
166
- "kbdb-project": {
167
- "command": "npx",
168
- "args": [
169
- "@dikolab/kbdb", "mcp",
170
- "--db", "/home/user/project/.kbdb"
171
- ]
172
- }
173
- }
174
- }
175
- ```
176
-
177
- Each registration spawns a separate `kbdb mcp`
178
- process with its own worker client connection. The
179
- worker daemon disambiguates by context ID (SHA-256
180
- of the database path), so multiple MCP instances
181
- hitting different databases work without conflict.
182
-
183
- ## Transport
184
-
185
- The MCP server uses **stdio** transport:
186
-
187
- - Reads JSON-RPC 2.0 requests from **stdin**.
188
- - Writes JSON-RPC 2.0 responses to **stdout**.
189
- - Diagnostic messages go to **stderr**.
190
-
191
- The AI agent host (Claude Desktop, Claude Code, or
192
- any MCP-compatible client) spawns `kbdb mcp` as a
193
- child process and communicates over its stdin/stdout
194
- streams.
195
-
196
- ## Protocol
197
-
198
- The MCP server implements the **Model Context Protocol
199
- version 2025-11-25** over **JSON-RPC 2.0**. This is
200
- the same wire format the worker daemon uses for IPC
201
- (see [Worker Daemon](worker-daemon.md)), but with
202
- MCP-defined method names and semantics.
203
-
204
- Every MCP-compatible AI agent host -- Claude Desktop,
205
- Claude Code, Cursor, Windsurf, or any custom harness
206
- -- uses this same protocol. The server has no knowledge
207
- of which host is connected.
208
-
209
- ### Lifecycle
210
-
211
- Three methods form the mandatory startup handshake.
212
- Nothing else may be called before `initialize`
213
- completes.
214
-
215
- #### 1. `initialize` (request)
216
-
217
- The host sends its identity and supported capabilities.
218
- The server responds with its own identity, the
219
- protocol version it speaks, and which capability
220
- groups it supports.
221
-
222
- **Host request:**
223
-
224
- ```json
225
- {
226
- "jsonrpc": "2.0",
227
- "id": 1,
228
- "method": "initialize",
229
- "params": {
230
- "protocolVersion": "2025-11-25",
231
- "capabilities": {},
232
- "clientInfo": {
233
- "name": "ExampleHost",
234
- "version": "1.0.0"
235
- }
236
- }
237
- }
238
- ```
239
-
240
- **Server response:**
241
-
242
- ```json
243
- {
244
- "jsonrpc": "2.0",
245
- "id": 1,
246
- "result": {
247
- "protocolVersion": "2025-11-25",
248
- "serverInfo": {
249
- "name": "kbdb",
250
- "version": "0.1.0"
251
- },
252
- "capabilities": {
253
- "tools": {},
254
- "resources": {}
255
- }
256
- }
257
- }
258
- ```
259
-
260
- **Version negotiation:** the host sends the latest
261
- version it supports. If the server supports it, it
262
- responds with the same version. Otherwise, the server
263
- responds with another version it supports. If the
264
- host does not support the server's version, it should
265
- disconnect.
266
-
267
- #### 2. `notifications/initialized` (notification)
268
-
269
- The host sends this notification (no `id`, no
270
- response) to confirm that the handshake is complete.
271
- The server flips its internal ready state and begins
272
- accepting tool and resource requests.
273
-
274
- ```json
275
- {
276
- "jsonrpc": "2.0",
277
- "method": "notifications/initialized"
278
- }
279
- ```
280
-
281
- #### 3. `ping` (request)
282
-
283
- Either party can send a `ping` to check liveness.
284
- The receiver must respond promptly with an empty
285
- result.
286
-
287
- ```json
288
- {
289
- "jsonrpc": "2.0",
290
- "id": 99,
291
- "method": "ping"
292
- }
293
- ```
294
-
295
- Response:
296
-
297
- ```json
298
- {
299
- "jsonrpc": "2.0",
300
- "id": 99,
301
- "result": {}
302
- }
303
- ```
304
-
305
- ### Capability Negotiation
306
-
307
- The `capabilities` object in the `initialize` response
308
- tells the host which method groups the server supports.
309
- The host must not call methods for capabilities the
310
- server did not advertise.
311
-
312
- kbdb advertises:
313
-
314
- ```json
315
- {
316
- "tools": {},
317
- "resources": {},
318
- "prompts": {},
319
- "logging": {},
320
- "completions": {}
321
- }
322
- ```
323
-
324
- This means the host can call `tools/list`,
325
- `tools/call`, `resources/list`, `resources/read`,
326
- `resources/templates/list`, `prompts/list`,
327
- `prompts/get`, `logging/setLevel`, and
328
- `completion/complete`.
329
-
330
- Optional capability flags:
331
-
332
- | Flag | Meaning |
333
- |------|---------|
334
- | `tools.listChanged` | Server emits `notifications/tools/list_changed` |
335
- | `resources.listChanged` | Server emits `notifications/resources/list_changed` |
336
- | `resources.subscribe` | Client can subscribe to resource changes |
337
- | `prompts` | Server supports `prompts/list` and `prompts/get` |
338
- | `logging` | Server supports `logging/setLevel` and emits log notifications |
339
- | `completions` | Server supports `completion/complete` |
340
-
341
- ## MCP Tools
342
-
343
- Tools are callable actions that the AI agent invokes.
344
- Each tool sends a JSON-RPC 2.0 request to the worker
345
- daemon via the worker client.
346
-
347
- ### search
348
-
349
- Search the knowledge base. Returns ranked results
350
- with headings and snippets for relevance evaluation.
351
- Use multiple short keyword queries for best coverage.
352
- Use `recall` to get full content of specific results.
353
-
354
- **Parameters:**
355
-
356
- | Name | Type | Required | Description |
357
- |-----------|---------|----------|----------------------------|
358
- | `query` | string | yes | Search query text |
359
- | `mode` | string | no | `"sections"` (default), `"documents"`, or `"stats"` |
360
- | `limit` | number | no | Max results (default: 20) |
361
- | `offset` | number | no | Zero-based result offset (default: 0) |
362
- | `content` | boolean | no | When `true`, include full section text in each result (default: `false`) |
363
-
364
- **Returns:** Paged JSON envelope containing ranked
365
- results. Each result includes contextual metadata
366
- the AI agent needs to judge relevance without
367
- additional calls:
368
-
369
- ```json
370
- {
371
- "items": [
372
- {
373
- "kbid": "a1b2c3d4e5f6g7h8j9k0l1m2n3",
374
- "heading": "Architecture Overview",
375
- "type": "text/markdown",
376
- "docids": ["doc-5678"],
377
- "snippet": "The system is organized...",
378
- "matched_terms": ["architecture", "system"],
379
- "matched_fields": ["heading", "body"],
380
- "created_at": "2026-06-20T14:30:00Z"
381
- }
382
- ],
383
- "total": 42,
384
- "offset": 0,
385
- "limit": 20,
386
- "has_more": true,
387
- "relaxed": false
388
- }
389
- ```
390
-
391
- - `heading` -- the section's title text, or `null`
392
- when the section has no title.
393
- - `type` -- section MIME type (e.g.
394
- `"text/markdown"`, `"text/typescript"`).
395
- - `docids` -- document identifiers this section
396
- belongs to (may be empty for standalone sections).
397
- - `snippet` -- KWIC (keyword-in-context) excerpt,
398
- ~150 characters centered on the highest-scoring
399
- matched term. Empty string for image sections.
400
- - `matched_terms` -- query terms that matched, as a
401
- flat `string[]`. No frequency counts.
402
- - `matched_fields` -- subset of `["heading", "body",
403
- "code"]` indicating which fields contained matches.
404
- - `created_at` -- ISO 8601 timestamp of when the
405
- section was first indexed.
406
- - `relaxed` -- `true` when the result came from an
407
- automatic AND-to-OR fallback (see
408
- [Query Result -- Relaxed-Match
409
- Fallback](query-result.md)). `false` for normal
410
- results.
411
-
412
- When `content` is `true`, each item also includes
413
- a `content` field with the full section text.
414
-
415
- Results are ordered by relevance (highest first).
416
- The ordering itself carries the ranking signal --
417
- no numeric score is exposed.
418
-
419
- Result is serialised with 2-space indentation.
420
-
421
- Maps to `client.search()`.
422
-
423
- ### learn
424
-
425
- Import content into the knowledge base. Use for
426
- durable facts, decisions, and corrections. Use
427
- `--replace` when updating existing knowledge. Attach
428
- tags for scoping. The daemon decomposes the content
429
- into sections, extracts keywords, builds indexes,
430
- and assigns ranking weights.
431
-
432
- **Parameters:**
433
-
434
- | Name | Type | Required | Description |
435
- |---------------|--------|----------|------------------|
436
- | `content` | string | yes | Text content or base64-encoded image data |
437
- | `type` | string | no | `"text/markdown"` (default), `text/*` MIME type, `"application/json"`, or `image/*` MIME type |
438
- | `title` | string | no* | Section title. ***Required** for `image/*` types.* Optional for text and code types. |
439
- | `description` | string | no | Optional section description |
440
- | `docid` | string | no | Group under this document ID |
441
- | `tags` | string[] | no | Tags for scoping and filtering |
442
- | `replace` | boolean | no | Enable supersession by source key. When `true` and a section with the same source key exists, the old section is replaced. |
443
-
444
- **Content type rules:**
445
-
446
- 1. **`type` is `text/*` or omitted** (default
447
- `text/markdown`) -- `title` and `description` are
448
- optional. `content` is the raw text.
449
- 2. **`type` is `image/*`** -- **`title` is required.**
450
- `content` must be base64-encoded binary image data.
451
- Omitting `title` returns a tool error
452
- (`isError: true`). `description` is optional.
453
- 3. **`description`** -- always optional for all types.
454
-
455
- Text and code content is preprocessed (BOM removal,
456
- line ending normalization, Unicode NFC, whitespace
457
- trimming) before the kbid hash is computed. Image
458
- content is stored verbatim. See
459
- [Database -- Content Preprocessing](database.md)
460
- for the full pipeline.
461
-
462
- For code sections (`text/*` or `application/json`),
463
- `content` is the raw source text. For image sections
464
- (`image/*`), `content` is the base64-encoded binary
465
- image data. See
466
- [Database -- Section Types](database.md).
467
-
468
- **Returns:** JSON (compact, no indentation) with the
469
- new section's `AddSectionResult` from the daemon.
470
- Fields include the assigned kbid, content type, title
471
- (if provided), description (if provided), indexed
472
- term count, elapsed time, and an `attached` flag.
473
- Text and code sections return a positive
474
- `indexed_terms_count`. Image sections return
475
- `indexed_terms_count: 0`.
476
-
477
- Additional result fields when applicable:
478
- - `superseded` -- kbid of the section this one
479
- replaced via `replace: true`, or `null`.
480
- - `warnings` -- string array of advisory warnings
481
- (e.g. `"heading_missing"` when a text section has
482
- no title).
483
- - `near_duplicates` -- array of
484
- `{ kbid, similarity }` objects for existing
485
- sections with Jaccard similarity >= 0.85.
486
-
487
- If the content already exists in the database (same
488
- kb-id) and `docid` is provided, the section is not
489
- duplicated. Instead, the docid is added to the
490
- existing section's `docids` list. The result reports
491
- `attached: true` and `indexed_terms_count: 0` (no
492
- re-indexing). If no `docid` is provided and the
493
- content already exists, the section is skipped. If
494
- the docid is already in the section's `docids` array,
495
- the operation is idempotent: `attached: false`.
496
-
497
- Maps to `client.addSection()`. Internally maps the
498
- `type` tool parameter to the `sectionType` field
499
- expected by `McpWorkerClient.addSection()`.
500
-
501
- ### unlearn
502
-
503
- Remove content from the knowledge base by kb-id.
504
- Cascades deletion to associated index entries and
505
- ranking data.
506
-
507
- **Parameters:**
508
-
509
- | Name | Type | Required | Description |
510
- |---------|--------|----------|-------------------|
511
- | `kbid` | string | yes | KB ID of section to remove |
512
-
513
- **Returns:** Compact JSON `{ "removed": bool,
514
- "elapsed_ms": number }` where `removed` is `true`
515
- when the section was found and removed.
516
-
517
- Maps to `client.removeSection()`.
518
-
519
- ### retrieve
520
-
521
- Low-level fetch of a section or document by
522
- identifier. For AI agent workflows, prefer `recall`
523
- which includes metadata, context, and
524
- back-references.
525
-
526
- **Parameters:**
527
-
528
- | Name | Type | Required | Description |
529
- |---------|--------|----------|------------------|
530
- | `kbid` | string | no | KB ID of section |
531
- | `docid` | string | no | Document ID |
532
-
533
- Neither field is marked required in the schema, but
534
- at least one must be provided. Omitting both returns
535
- `isError: true` with the message `Provide kbid or
536
- docid`.
537
-
538
- When `kbid` is provided, maps to
539
- `client.readSections([kbid])` and returns a JSON
540
- array of section objects: `[{ kbid, sectionType,
541
- content, size }]`. When `docid` is provided, maps to
542
- `client.retrieveDocument(docid)` and returns the raw
543
- document record from the daemon.
544
-
545
- Maps to `client.readSections()` or
546
- `client.retrieveDocument()`.
547
-
548
- ### recall
549
-
550
- Retrieve full content and context for one or more
551
- sections by identifier. Use after `search` to read
552
- relevant results. Returns section text, metadata,
553
- references, and back-references.
554
-
555
- **Parameters:**
556
-
557
- | Name | Type | Required | Description |
558
- |---------|----------|----------|--------------------------|
559
- | `kbid` | string | no* | Single section identifier |
560
- | `kbids` | string[] | no* | Batch section identifiers |
561
- | `depth` | number | no | Expansion depth (0--3, default: 0) |
562
-
563
- *At least one of `kbid` or `kbids` is required.
564
- Omitting both returns `isError: true`. When both
565
- are provided, `kbids` takes precedence and `kbid`
566
- is appended to the list.
567
-
568
- **Expansion levels:**
569
-
570
- | Depth | Returns |
571
- |-------|---------------------------------------|
572
- | 0 | Full section content with heading, |
573
- | | type, and docids. |
574
- | 1 | Depth-0 content, plus parent document |
575
- | | manifests (title, all section kbids |
576
- | | with headings and types) for each |
577
- | | docid, plus back-references (sections |
578
- | | that reference this section, from the |
579
- | | reference graph index, each with |
580
- | | marker_type and context_snippet). |
581
- | 2 | Depth-1 content, plus full text of |
582
- | | sibling sections (other sections in |
583
- | | the same documents), plus forward |
584
- | | references from the section's own |
585
- | | content markers. |
586
- | 3 | Depth-2 content, plus full text of |
587
- | | referenced sections (one level deep), |
588
- | | plus their back-references. |
589
-
590
- Depth values above 3 are clamped to 3.
591
-
592
- **Single result shape (depth 0):**
593
-
594
- ```json
595
- {
596
- "kbid": "a1b2c3d4e5f6g7h8j9k0l1m2n3",
597
- "heading": "Architecture Overview",
598
- "type": "text/markdown",
599
- "content": "Full section text...",
600
- "docids": ["doc-5678"]
601
- }
602
- ```
603
-
604
- **Single result shape (depth 1+):**
605
-
606
- ```json
607
- {
608
- "kbid": "a1b2c3d4e5f6g7h8j9k0l1m2n3",
609
- "heading": "Architecture Overview",
610
- "type": "text/markdown",
611
- "content": "Full section text...",
612
- "docids": ["doc-5678"],
613
- "documents": [
614
- {
615
- "docid": "doc-5678",
616
- "title": "System Architecture",
617
- "sections": [
618
- {
619
- "kbid": "...",
620
- "heading": "...",
621
- "type": "..."
622
- }
623
- ]
624
- }
625
- ],
626
- "back_references": [
627
- {
628
- "kbid": "ref-section-kbid",
629
- "heading": "Related Section",
630
- "type": "text/markdown",
631
- "marker_type": "link",
632
- "context_snippet": "For details, see ...",
633
- "direction": "back"
634
- }
635
- ],
636
- "siblings": [ ... ],
637
- "references": [ ... ]
638
- }
639
- ```
640
-
641
- Fields beyond `content` and `docids` are present
642
- only at the corresponding depth level. At depth 0,
643
- `documents`, `back_references`, `siblings`, and
644
- `references` are absent. At depth 1, `siblings`
645
- and `references` are absent. And so on.
646
-
647
- When batch `kbids` is used, the response is a JSON
648
- array of result objects (one per kbid). The depth
649
- parameter applies to all sections in the batch.
650
-
651
- Maps to `client.recall()`.
652
-
653
- ### content
654
-
655
- Compose a rendered Markdown document from one or
656
- more kbid or docid identifiers.
657
-
658
- **Parameters:**
659
-
660
- | Name | Type | Required | Description |
661
- |-------|----------|----------|-------------------|
662
- | `ids` | string[] | yes | One or more kbid or docid identifiers (mixed) |
663
-
664
- **Returns:** Tool result with text content containing
665
- JSON: `{ "type": "text/markdown", "data": "...",
666
- "total": <char count> }`. The `total` field is the
667
- character count of `data` (not byte count).
668
-
669
- Maps to `client.content()`.
670
-
671
- See [Content Composer](content-composer.md) for the
672
- full composition specification.
673
-
674
- ### status
675
-
676
- Return database status and cache statistics.
677
-
678
- **Parameters:** None.
679
-
680
- **Returns:** JSON with the following fields:
681
-
682
- | Field | Type | Description |
683
- |-------|------|-------------|
684
- | `initialized` | boolean | Whether the daemon has finished loading its WASM modules |
685
- | `contextPath` | string | Absolute path to the database directory the daemon serves |
686
- | `cacheStats.contentCount` | number | Number of content entries currently in the in-memory cache |
687
- | `cacheStats.indexCount` | number | Number of index entries currently in the in-memory cache |
688
-
689
- Maps to `client.dbStatus()`.
690
-
691
- ### check
692
-
693
- Verify the integrity of the knowledge base. Reports
694
- checksum mismatches, orphan sections and documents,
695
- broken marker references, type mismatches, and
696
- circular reference chains.
697
-
698
- **Parameters:** None.
699
-
700
- **Returns:** JSON with `ok` boolean, `errors` array
701
- (each with `type`, `entity`, `detail`),
702
- `sections_checked`, `documents_checked`,
703
- `references_checked`, and `elapsed_ms`. When all
704
- checks pass, `ok` is `true` and `errors` is empty.
705
-
706
- Error types: `checksum_mismatch`, `orphan_section`,
707
- `orphan_document`, `broken_reference`,
708
- `type_mismatch`, `circular_reference`,
709
- `divergent_content`. The `divergent_content` error
710
- flags sections sharing the same `source_key` that
711
- have different content -- indicates contradictory
712
- versions that should be resolved via supersession.
713
- See [Database -- Integrity and
714
- Maintenance](database.md).
715
-
716
- Maps to `client.integrityCheck()`.
717
-
718
- ### gc
719
-
720
- Remove unreferenced sections from the knowledge
721
- base. A section is eligible for removal when no
722
- document manifest references it.
723
-
724
- **Parameters:** None.
725
-
726
- **Returns:** JSON with `removed_sections` (count),
727
- `removed_bytes`, and `elapsed_ms`. When no sections
728
- are eligible, counts are `0`.
729
-
730
- Maps to `client.gc()`.
731
-
732
- ### rebuild
733
-
734
- Reconstruct all index files from section files and
735
- document manifests on disk. Text and code sections
736
- are re-tokenized; image sections are skipped. Use
737
- this to recover from index corruption.
738
-
739
- **Parameters:** None.
740
-
741
- **Returns:** JSON with `sections_reindexed`,
742
- `terms_indexed`, and `elapsed_ms`.
743
-
744
- Maps to `client.rebuildIndexes()`.
745
-
746
- ### export
747
-
748
- Export the knowledge base as a self-contained
749
- directory snapshot for backup or versioning. Copies
750
- sections, documents, and catalog (no indexes -- they
751
- are rebuildable via `rebuild`).
752
-
753
- **Parameters:**
754
-
755
- | Name | Type | Required | Description |
756
- |--------|--------|----------|---------------------------|
757
- | `path` | string | no | Export destination path (default: `./kbdb-export/`) |
758
-
759
- **Returns:** Compact JSON with export summary:
760
-
761
- ```json
762
- {
763
- "path": "/home/user/kbdb-export",
764
- "sections_exported": 142,
765
- "documents_exported": 23,
766
- "elapsed_ms": 350
767
- }
768
- ```
769
-
770
- Maps to `client.export()`.
771
-
772
- ### skill-learn
773
-
774
- Create a new skill definition and store it in the
775
- knowledge base as a section with `sectionType:
776
- 'skill'`.
777
-
778
- **Parameters:**
779
-
780
- | Name | Type | Required | Description |
781
- |---------------|--------|----------|------------------------------------------|
782
- | `name` | string | yes | Skill name (kebab-case identifier) |
783
- | `description` | string | yes | What the skill does |
784
- | `arguments` | array | no | Prompt argument definitions |
785
- | `body` | string | yes | Template body with `{{argName}}` placeholders |
786
-
787
- **Returns:** Compact JSON `AddSectionResult` with the
788
- assigned `kbid`, `name`, and auto-detected `arguments`
789
- array extracted from `{{...}}` placeholders in `body`.
790
-
791
- Maps to `client.addSection()` with
792
- `sectionType: 'skill'`.
793
-
794
- ### skill-list
795
-
796
- List all skill definitions stored in the knowledge
797
- base.
798
-
799
- **Parameters:** None.
800
-
801
- **Returns:** JSON array of skill summary objects:
802
- `[{ kbid, name, description, argumentCount }]`.
803
- Result is serialised with 2-space indentation.
804
-
805
- Maps to `client.listByType('skill')`.
806
-
807
- ### skill-get
808
-
809
- Retrieve a single skill definition by name or kb-id.
810
-
811
- **Parameters:**
812
-
813
- | Name | Type | Required | Description |
814
- |--------|--------|----------|-------------------------------------|
815
- | `name` | string | no* | Skill name to look up |
816
- | `kbid` | string | no* | Skill kb-id to look up |
817
-
818
- *At least one of `name` or `kbid` is required.
819
- Omitting both returns `isError: true`. When both are
820
- provided, `kbid` takes precedence.
821
-
822
- **Returns:** Full `SkillDefinition` JSON with `kbid`,
823
- `name`, `description`, `arguments`, and `body`.
824
- Result is serialised with 2-space indentation.
825
-
826
- Maps to `client.readSections([kbid])` (by kbid) or
827
- `client.listByType('skill')` filtered by name (by
828
- name).
829
-
830
- ### skill-delete
831
-
832
- Remove a skill definition by kb-id. The skill section
833
- is removed from the database. Agent documents that
834
- reference this kbid will have a dangling reference.
835
-
836
- **Parameters:**
837
-
838
- | Name | Type | Required | Description |
839
- |--------|--------|----------|-----------------------|
840
- | `kbid` | string | yes | Skill kb-id to remove |
841
-
842
- **Returns:** Compact JSON `{ "kbid": "...",
843
- "removed": true }`.
844
-
845
- Maps to `client.removeSection()`.
846
-
847
- ### agent-create
848
-
849
- Create a new agent document in the knowledge base.
850
- An agent is a document with `type: 'agent'` that
851
- holds a persona and an ordered list of skill kbid
852
- references.
853
-
854
- **Parameters:**
855
-
856
- | Name | Type | Required | Description |
857
- |---------------|----------|----------|--------------------------------------|
858
- | `name` | string | yes | Agent name (kebab-case identifier) |
859
- | `description` | string | yes | What the agent does |
860
- | `persona` | string | yes | System prompt text for the agent |
861
- | `skills` | string[] | yes | Ordered skill kbid list |
862
-
863
- **Returns:** Compact JSON `{ "docid": "agent-...",
864
- "name": "...", "skills": [...] }`.
865
-
866
- Maps to `client.groupSections()` with
867
- `type: 'agent'` and `[agent]` metadata.
868
-
869
- ### agent-list
870
-
871
- List all agent documents in the knowledge base.
872
-
873
- **Parameters:** None.
874
-
875
- **Returns:** JSON array of agent summary objects:
876
- `[{ docid, name, description, skillCount }]`.
877
- Result is serialised with 2-space indentation.
878
-
879
- Maps to `client.listDocumentsByType('agent')`.
880
-
881
- ### agent-get
882
-
883
- Retrieve a single agent document with its resolved
884
- skill definitions.
885
-
886
- **Parameters:**
887
-
888
- | Name | Type | Required | Description |
889
- |---------|--------|----------|--------------------------|
890
- | `docid` | string | yes | Agent document ID |
891
-
892
- **Returns:** Full `AgentDefinition` JSON with `docid`,
893
- `name`, `description`, `persona`, and `skills` array.
894
- Each skill entry includes `kbid`, `name`, and
895
- `position`. If a referenced skill has been deleted,
896
- its `name` is `null`. Result is serialised with
897
- 2-space indentation.
898
-
899
- Maps to `client.retrieveDocument(docid)` followed by
900
- `client.readSections(kbids)` for skill resolution.
901
-
902
- ### agent-delete
903
-
904
- Remove an agent document. Only the document manifest
905
- is deleted; the referenced skill sections remain.
906
-
907
- **Parameters:**
908
-
909
- | Name | Type | Required | Description |
910
- |---------|--------|----------|--------------------------|
911
- | `docid` | string | yes | Agent document ID |
912
-
913
- **Returns:** Compact JSON `{ "docid": "...",
914
- "removed": true }`.
915
-
916
- Maps to `client.removeGrouping()`.
917
-
918
- ## MCP Resources
919
-
920
- Resources are data items the AI agent can read by
921
- URI. They provide direct access to knowledge base
922
- contents without going through search.
923
-
924
- The MCP `2025-11-25` spec distinguishes two listing
925
- methods:
926
-
927
- ### `resources/list` -- Static Resources
928
-
929
- Returns resources with concrete URIs. kbdb has no
930
- static resources, so this returns an empty list:
931
-
932
- ```json
933
- { "resources": [] }
934
- ```
935
-
936
- ### `resources/templates/list` -- URI Templates
937
-
938
- Returns parameterized URI templates (RFC 6570) that
939
- the client can expand with arguments. kbdb exposes
940
- two templates:
941
-
942
- | URI Template | MIME Type | Description |
943
- |-------------|----------|-------------|
944
- | `kbdb://section/{kbid}` | `text/plain` | Section by kb-id |
945
- | `kbdb://document/{docid}` | `application/json` | Document + sections |
946
-
947
- ### `resources/read` -- Fetch Resource
948
-
949
- **URI:** `kbdb://section/{kbid}`
950
-
951
- Returns the content of a single section identified
952
- by kb-id. For text sections, returns the raw text
953
- content. For code sections (`text/*` or
954
- `application/json`), returns the raw source text
955
- with the MIME type. For image sections (`image/*`
956
- type), returns the base64-encoded content with the
957
- MIME type.
958
-
959
- **URI:** `kbdb://document/{docid}`
960
-
961
- Returns a document and all its sections. Sections
962
- are ordered by position within the document.
963
-
964
- ## MCP Prompts
965
-
966
- Prompts are reusable templates that the AI agent host
967
- can discover and render. kbdb exposes two categories
968
- of prompts: **skills** (stored as sections with
969
- `sectionType: 'skill'`) and **agents** (stored as
970
- documents with `type: 'agent'`, identified by an
971
- `agent:` name prefix).
972
-
973
- ### prompts/list
974
-
975
- Returns all available prompts. Skills appear as
976
- `McpPrompt` objects; agents appear with the `agent:`
977
- name prefix and no arguments.
978
-
979
- **Request:**
980
-
981
- ```json
982
- {
983
- "jsonrpc": "2.0",
984
- "id": 1,
985
- "method": "prompts/list"
986
- }
987
- ```
988
-
989
- **Response:**
990
-
991
- ```json
992
- {
993
- "jsonrpc": "2.0",
994
- "id": 1,
995
- "result": {
996
- "prompts": [
997
- {
998
- "name": "summarize-document",
999
- "description": "Summarize a document into
1000
- key points with configurable depth",
1001
- "arguments": [
1002
- {
1003
- "name": "docid",
1004
- "description": "Document identifier",
1005
- "required": true
1006
- },
1007
- {
1008
- "name": "max_points",
1009
- "description": "Max bullet points",
1010
- "required": false
1011
- }
1012
- ]
1013
- },
1014
- {
1015
- "name": "agent:code-reviewer",
1016
- "description": "Reviews code for bugs,
1017
- style, and best practices",
1018
- "arguments": []
1019
- }
1020
- ]
1021
- }
1022
- }
1023
- ```
1024
-
1025
- Maps to `client.listByType('skill')` and
1026
- `client.listDocumentsByType('agent')`.
1027
-
1028
- ### prompts/get
1029
-
1030
- Retrieves a single prompt rendered with the given
1031
- argument values.
1032
-
1033
- **Request params:**
1034
-
1035
- | Parameter | Type | Required | Description |
1036
- |-------------|--------|----------|--------------------------|
1037
- | `name` | string | yes | Prompt name |
1038
- | `arguments` | object | no | Key-value argument map |
1039
-
1040
- **Response for a skill prompt** (single user message
1041
- with the rendered template body):
1042
-
1043
- ```json
1044
- {
1045
- "jsonrpc": "2.0",
1046
- "id": 2,
1047
- "result": {
1048
- "messages": [
1049
- {
1050
- "role": "user",
1051
- "content": {
1052
- "type": "text",
1053
- "text": "Summarize the document
1054
- identified by DOC-001.\nExtract
1055
- at most 5 key points.\nReturn as
1056
- a bulleted markdown list."
1057
- }
1058
- }
1059
- ]
1060
- }
1061
- }
1062
- ```
1063
-
1064
- **Response for an agent prompt** (assistant message
1065
- with persona, then user message with skill listing):
1066
-
1067
- ```json
1068
- {
1069
- "jsonrpc": "2.0",
1070
- "id": 3,
1071
- "result": {
1072
- "messages": [
1073
- {
1074
- "role": "assistant",
1075
- "content": {
1076
- "type": "text",
1077
- "text": "You are an expert code
1078
- reviewer. You focus on
1079
- correctness, readability, and
1080
- maintainability."
1081
- }
1082
- },
1083
- {
1084
- "role": "user",
1085
- "content": {
1086
- "type": "text",
1087
- "text": "Available skills:\n- summarize-document: Summarize a document...\n- review-diff: Review a code diff..."
1088
- }
1089
- }
1090
- ]
1091
- }
1092
- }
1093
- ```
1094
-
1095
- Maps to `client.readSections([kbid])` (skill) or
1096
- `client.retrieveDocument(docid)` with
1097
- `client.readSections(skillKbids)` (agent).
1098
-
1099
- ### Prompt Discovery Flow
1100
-
1101
- How an AI agent discovers and invokes a skill using
1102
- the prompt protocol:
1103
-
1104
- 1. Agent calls `prompts/list` to enumerate all
1105
- available prompts (skills and agents).
1106
- 2. Agent selects a prompt by name based on its
1107
- description and argument list.
1108
- 3. Agent calls `prompts/get` with the prompt name
1109
- and a key-value map of argument values.
1110
- 4. Agent receives one or more rendered
1111
- `McpPromptMessage` objects with the substituted
1112
- template text.
1113
- 5. Agent uses the rendered message(s) in its
1114
- workflow (as a system prompt, user turn, or
1115
- context injection).
1116
-
1117
- ## Tool Annotations
1118
-
1119
- Tool annotations provide hints to the MCP host about
1120
- the nature of each tool. The `McpToolAnnotations`
1121
- type adds metadata to the tool definition:
1122
-
1123
- ```typescript
1124
- interface McpToolAnnotations {
1125
- readonly title?: string;
1126
- readonly readOnlyHint?: boolean;
1127
- readonly destructiveHint?: boolean;
1128
- readonly idempotentHint?: boolean;
1129
- readonly openWorldHint?: boolean;
1130
- }
1131
- ```
1132
-
1133
- Annotations for all 20 kbdb tools:
1134
-
1135
- | Tool | title | readOnly | destructive | idempotent | openWorld |
1136
- |----------------|-------------------|----------|-------------|------------|-----------|
1137
- | `search` | Search KB | true | false | true | false |
1138
- | `learn` | Import Content | false | false | true | false |
1139
- | `unlearn` | Remove Section | false | true | true | false |
1140
- | `retrieve` | Fetch Content | true | false | true | false |
1141
- | `recall` | Recall Context | true | false | true | false |
1142
- | `content` | Compose Content | true | false | true | false |
1143
- | `status` | DB Status | true | false | true | false |
1144
- | `check` | Integrity Check | true | false | true | false |
1145
- | `gc` | Garbage Collect | false | true | false | false |
1146
- | `rebuild` | Rebuild Indexes | false | false | false | false |
1147
- | `export` | Export Snapshot | false | false | true | false |
1148
- | `skill-learn` | Create Skill | false | false | true | false |
1149
- | `skill-list` | List Skills | true | false | true | false |
1150
- | `skill-get` | Get Skill | true | false | true | false |
1151
- | `skill-delete` | Delete Skill | false | true | true | false |
1152
- | `agent-create` | Create Agent | false | false | true | false |
1153
- | `agent-list` | List Agents | true | false | true | false |
1154
- | `agent-get` | Get Agent | true | false | true | false |
1155
- | `agent-delete` | Delete Agent | false | true | true | false |
1156
- | `auto-capture-review` | Review Captures | false | false | false | false |
1157
-
1158
- ## Completions
1159
-
1160
- The `completion/complete` handler provides
1161
- autocomplete suggestions for prompt names and
1162
- resource URIs. Clients use this to offer tab
1163
- completion in UI surfaces.
1164
-
1165
- **Request params:**
1166
-
1167
- | Parameter | Type | Required | Description |
1168
- |------------|--------|----------|-------------------------------------|
1169
- | `ref` | object | yes | Reference describing what to complete |
1170
- | `argument` | object | no | Argument being completed |
1171
-
1172
- **Ref types:**
1173
-
1174
- - `ref/prompt` with `name`: autocomplete skill and
1175
- agent prompt names that match the given prefix.
1176
- Returns all prompts whose name starts with the
1177
- prefix string.
1178
- - `ref/resource` with `uri`: autocomplete kbid or
1179
- docid in URI patterns (`kbdb://section/...` or
1180
- `kbdb://document/...`) that match the given prefix.
1181
-
1182
- **Response (`McpCompletionResult`):**
1183
-
1184
- ```json
1185
- {
1186
- "completion": {
1187
- "values": [
1188
- "summarize-document",
1189
- "search-and-report"
1190
- ],
1191
- "hasMore": false,
1192
- "total": 2
1193
- }
1194
- }
1195
- ```
1196
-
1197
- ## Sampling
1198
-
1199
- The sampling capability allows the kbdb MCP server
1200
- to request the AI agent host to generate text using
1201
- its own language model. The server sends a
1202
- `sampling/createMessage` request; the host runs the
1203
- LLM and returns the generated text.
1204
-
1205
- **Request params:**
1206
-
1207
- | Parameter | Type | Required | Description |
1208
- |-------------|--------|----------|----------------------------|
1209
- | `messages` | array | yes | Message array to send |
1210
- | `maxTokens` | number | yes | Maximum response tokens |
1211
-
1212
- Before using sampling, the server checks the host's
1213
- capabilities from the `initialize` response to
1214
- confirm `sampling` is supported.
1215
-
1216
- **Use cases:**
1217
-
1218
- 1. Auto-generate a skill body from a name and
1219
- description (used by `skill-learn` when `body`
1220
- is omitted).
1221
- 2. Extract keywords from content before indexing
1222
- (alternative to WASM keyword extraction).
1223
- 3. Summarise content for preview generation in
1224
- `skill-list` and `agent-list` responses.
1225
-
1226
- ## Roots
1227
-
1228
- The `roots/list` handler returns the filesystem roots
1229
- that the server considers relevant to its operation.
1230
- kbdb returns the `.kbdb` database directory as its
1231
- single root.
1232
-
1233
- **Response:**
1234
-
1235
- ```json
1236
- {
1237
- "roots": [
1238
- {
1239
- "uri": "file:///path/to/.kbdb",
1240
- "name": "kbdb database"
1241
- }
1242
- ]
1243
- }
1244
- ```
1245
-
1246
- The URI uses the `file://` scheme with the absolute
1247
- path to the context directory. The name is always
1248
- `"kbdb database"`.
1249
-
1250
- ## Logging
1251
-
1252
- The `logging/setLevel` handler controls the verbosity
1253
- of server-to-client log notifications. Clients set
1254
- the level once after initialization; the server
1255
- applies it for the lifetime of the connection.
1256
-
1257
- **Parameter:** `level` (one of the `McpLogLevel`
1258
- string values).
1259
-
1260
- **Log levels** (in ascending severity order):
1261
-
1262
- - `debug`
1263
- - `info`
1264
- - `notice`
1265
- - `warning`
1266
- - `error`
1267
- - `critical`
1268
- - `alert`
1269
- - `emergency`
1270
-
1271
- When the log level is set, the server emits
1272
- `notifications/message` for any event at or above
1273
- the configured level:
1274
-
1275
- ```json
1276
- {
1277
- "jsonrpc": "2.0",
1278
- "method": "notifications/message",
1279
- "params": {
1280
- "level": "info",
1281
- "logger": "kbdb",
1282
- "data": "Indexed 42 terms for section abc123"
1283
- }
1284
- }
1285
- ```
1286
-
1287
- ## Resource Subscriptions
1288
-
1289
- Clients can subscribe to individual resources to
1290
- receive change notifications without polling.
1291
-
1292
- - **`resources/subscribe`** -- client provides a
1293
- resource URI; the server adds it to the active
1294
- subscription set.
1295
- - **`resources/unsubscribe`** -- client provides a
1296
- URI; the server removes it from the subscription
1297
- set.
1298
-
1299
- When a subscribed resource changes (section added,
1300
- updated, or deleted; document manifest modified),
1301
- the server emits `notifications/resources/updated`
1302
- with the affected URI:
1303
-
1304
- ```json
1305
- {
1306
- "jsonrpc": "2.0",
1307
- "method": "notifications/resources/updated",
1308
- "params": {
1309
- "uri": "kbdb://section/a1b2c3d4e5f6g7h8j9k0"
1310
- }
1311
- }
1312
- ```
1313
-
1314
- ## Execution Model
1315
-
1316
- ```
1317
- AI agent host (Claude Desktop, Claude Code, etc.)
1318
-
1319
- │ spawns child process
1320
-
1321
- kbdb mcp --db /path/to/.kbdb
1322
-
1323
- │ stdio: JSON-RPC 2.0 (stdin/stdout)
1324
-
1325
- MCP Server (src/cli.ts -- MCP mode)
1326
-
1327
- │ imports src/shared/worker-client/
1328
-
1329
- Worker Client
1330
-
1331
- │ IPC: JSON-RPC 2.0 (Unix socket / named pipe)
1332
-
1333
- Worker Daemon (src/worker.ts)
1334
- ```
1335
-
1336
- The MCP server is a long-lived process. It creates a
1337
- worker client on startup, holds the IPC connection
1338
- open, and routes all incoming MCP requests through
1339
- it. The daemon handles concurrency, caching, and WASM
1340
- module orchestration.
1341
-
1342
- When the AI agent host terminates the connection
1343
- (closes stdin), the MCP server disconnects from the
1344
- worker daemon and exits. The daemon may continue
1345
- running for other clients or shut down on idle
1346
- timeout.
1347
-
1348
- ## Relationship to CLI Mode
1349
-
1350
- The MCP server and CLI mode share:
1351
-
1352
- - The same `kbdb` executable and installation.
1353
- - The same worker client module
1354
- (`src/shared/worker-client/`).
1355
- - The same worker daemon and WASM modules.
1356
- - The same `.kbdb` database directory.
1357
-
1358
- Changes made via CLI commands are visible to the MCP
1359
- server and vice versa -- both operate on the same
1360
- database through the same daemon.
1361
-
1362
- The difference is the interface:
1363
-
1364
- | Aspect | CLI Mode | MCP Mode |
1365
- |-----------|------------------------|------------------------|
1366
- | Lifecycle | Short-lived (one cmd) | Long-lived (persistent)|
1367
- | Interface | Command-line arguments | MCP protocol (stdio) |
1368
- | Consumer | Human / shell script | AI agent |
1369
- | Output | stdout (JSON/text/MCP) | MCP tool result format |
1370
- | DB path | CWD or `--db` flag | `--db` flag or `KBDB_DB_DIR` env |
1371
-
1372
- See [CLI](cli.md) for CLI mode details,
1373
- [Worker Client](worker-client.md) for the shared
1374
- client module, and [Database](database.md) for
1375
- storage details.
1376
-
1377
- ## Notifications
1378
-
1379
- Notifications are one-way JSON-RPC messages with no
1380
- `id` and no response expected.
1381
-
1382
- ### Client -> Server
1383
-
1384
- | Notification | When |
1385
- |-------------|------|
1386
- | `notifications/initialized` | After `initialize` response received (required) |
1387
- | `notifications/cancelled` | Client cancels an in-flight request |
1388
- | `notifications/roots/list_changed` | If `roots.listChanged` advertised |
1389
-
1390
- ### Server -> Client
1391
-
1392
- | Notification | When |
1393
- |-------------|------|
1394
- | `notifications/tools/list_changed` | Tool set changed (if `tools.listChanged`) |
1395
- | `notifications/resources/list_changed` | Resource set changed (if `resources.listChanged`) |
1396
- | `notifications/resources/updated` | Subscribed resource changed |
1397
- | `notifications/prompts/list_changed` | Prompt set changed (if `prompts.listChanged`) |
1398
- | `notifications/message` | Structured log message (if `logging` capability) |
1399
- | `notifications/progress` | Long-running request progress update |
1400
-
1401
- kbdb does not currently emit any server-to-client
1402
- notifications. It handles `notifications/initialized`
1403
- from the client and ignores unknown notifications.
1404
-
1405
- ## Error Handling
1406
-
1407
- ### Protocol Errors
1408
-
1409
- Protocol-level errors use JSON-RPC 2.0 error
1410
- responses:
1411
-
1412
- | Code | Meaning |
1413
- |------|---------|
1414
- | `-32700` | Parse error -- malformed JSON |
1415
- | `-32601` | Method not found |
1416
- | `-32602` | Invalid params |
1417
- | `-32603` | Internal error |
1418
- | `-32002` | Resource not found (MCP-specific) |
1419
-
1420
- ### Tool Execution Errors
1421
-
1422
- Tool-level failures are **not** protocol errors.
1423
- They are returned as successful JSON-RPC responses
1424
- with `isError: true` in the tool result:
1425
-
1426
- ```json
1427
- {
1428
- "jsonrpc": "2.0",
1429
- "id": 5,
1430
- "result": {
1431
- "content": [
1432
- {
1433
- "type": "text",
1434
- "text": "Section not found: abc123"
1435
- }
1436
- ],
1437
- "isError": true
1438
- }
1439
- }
1440
- ```
1441
-
1442
- `handleToolCall` wraps every tool dispatch in a
1443
- `try/catch`. When an error is thrown, the handler
1444
- returns `{ content: [{ type: 'text', text:
1445
- err.message }], isError: true }` where `err.message`
1446
- is the message string when `err` is an `Error`
1447
- instance, or `String(err)` otherwise. Validation
1448
- errors within a tool handler (e.g. missing `title`
1449
- for `image/*` types, unknown tool name, or `retrieve`
1450
- called without `kbid` or `docid`) follow the same
1451
- format but are returned directly rather than thrown.
1452
-
1453
- All successful tool results are wrapped as:
1454
- ```json
1455
- { "content": [{ "type": "text", "text": "<JSON>" }] }
1456
- ```
1457
- where `<JSON>` is the result serialised with
1458
- `JSON.stringify`. Most tools use 2-space indentation;
1459
- `learn`, `unlearn`, and `content` return compact JSON
1460
- (no indentation).
1461
-
1462
- Reserve JSON-RPC error responses for protocol
1463
- violations (bad JSON, unknown method, missing
1464
- required params). Application errors from tool
1465
- execution go in the result.
1466
-
1467
- ### Prompt and Skill Errors
1468
-
1469
- Additional error cases for the prompts and skill/agent
1470
- tools:
1471
-
1472
- | Condition | Response |
1473
- |-----------|----------|
1474
- | `prompts/get` with unknown prompt name | JSON-RPC error `-32002` (resource not found) |
1475
- | `skill-learn` with empty `body` | Tool result with `isError: true`, message: `"skill body must not be empty"` |
1476
- | `skill-get` called without `name` or `kbid` | Tool result with `isError: true`, message: `"Provide name or kbid"` |
1477
- | `skill-learn` with duplicate name | Not an error -- duplicate names are allowed, each gets a distinct kbid |
1478
- | `agent-get` with skill kbid that has been deleted | Not an error -- the skill entry appears with `"name": null` in the skills array |
1479
-
1480
- ## Required vs Optional Methods
1481
-
1482
- Methods are grouped by the capability that gates
1483
- them. A server must implement all methods for every
1484
- capability it advertises.
1485
-
1486
- | Method | Gate | kbdb Status |
1487
- |--------|------|-------------|
1488
- | `initialize` | required | implemented |
1489
- | `notifications/initialized` | required | implemented |
1490
- | `ping` | required | implemented |
1491
- | `tools/list` | `tools` capability | implemented |
1492
- | `tools/call` | `tools` capability | implemented |
1493
- | `resources/list` | `resources` capability | empty list |
1494
- | `resources/read` | `resources` capability | implemented |
1495
- | `resources/templates/list` | `resources` capability | implemented |
1496
- | `resources/subscribe` | `resources.subscribe` | planned |
1497
- | `resources/unsubscribe` | `resources.subscribe` | planned |
1498
- | `prompts/list` | `prompts` capability | implemented |
1499
- | `prompts/get` | `prompts` capability | implemented |
1500
- | `completion/complete` | `completions` capability | implemented |
1501
- | `sampling/createMessage` | `sampling` capability | planned |
1502
- | `roots/list` | `roots` capability | implemented |
1503
- | `logging/setLevel` | `logging` capability | planned |
1504
-
1505
- Methods listed as "planned" are documented for
1506
- future implementation. Until implemented, the server
1507
- returns `-32601` if they are called.
1508
-
1509
- ## Design Constraints
1510
-
1511
- - The MCP server conforms to the Model Context
1512
- Protocol specification version **2025-11-25**.
1513
- - Output follows MCP tool result conventions. The
1514
- CLI's output format flags do not apply in MCP mode.
1515
- - The server runs as a persistent process. It stays
1516
- alive and handles multiple requests from the
1517
- connected agent until the host terminates the
1518
- connection.
1519
- - The server works with both Deno and Node.js
1520
- runtimes, consistent with the project's
1521
- dual-runtime requirement.
1522
- - The database path is resolved from `--db`,
1523
- `KBDB_DB_DIR`, or the current working directory.
1524
- - The MCP server does not perform keyword extraction,
1525
- indexing, ranking, or database I/O itself. All
1526
- processing is delegated to the worker daemon via
1527
- the worker client.
1528
-
1529
- ### Wire Format Rules
1530
-
1531
- - **stdout is sacred** -- only JSON-RPC messages may
1532
- be written to stdout. Debug output, diagnostics,
1533
- and progress messages must go to stderr. Any
1534
- non-JSON-RPC output on stdout corrupts the stream.
1535
- - **One message per line** -- each JSON-RPC message
1536
- is serialized as a single line of JSON with no
1537
- embedded newlines, terminated by `\n`.
1538
- - **Request ID must not be null** -- unlike standard
1539
- JSON-RPC 2.0, MCP requires the `id` field to be a
1540
- non-null `string` or `number`. Notifications omit
1541
- `id` entirely.