agent-knowledge 1.2.0 → 1.3.1

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 (78) hide show
  1. package/CHANGELOG.md +94 -13
  2. package/README.md +51 -34
  3. package/dist/dashboard.d.ts +1 -0
  4. package/dist/dashboard.d.ts.map +1 -1
  5. package/dist/dashboard.js +76 -23
  6. package/dist/dashboard.js.map +1 -1
  7. package/dist/embeddings/anthropic.d.ts.map +1 -1
  8. package/dist/embeddings/anthropic.js +2 -1
  9. package/dist/embeddings/anthropic.js.map +1 -1
  10. package/dist/embeddings/gemini.d.ts.map +1 -1
  11. package/dist/embeddings/gemini.js +2 -1
  12. package/dist/embeddings/gemini.js.map +1 -1
  13. package/dist/embeddings/local.d.ts.map +1 -1
  14. package/dist/embeddings/local.js +3 -0
  15. package/dist/embeddings/local.js.map +1 -1
  16. package/dist/knowledge/consolidate.d.ts +46 -0
  17. package/dist/knowledge/consolidate.d.ts.map +1 -0
  18. package/dist/knowledge/consolidate.js +164 -0
  19. package/dist/knowledge/consolidate.js.map +1 -0
  20. package/dist/knowledge/distill.d.ts.map +1 -1
  21. package/dist/knowledge/distill.js +4 -2
  22. package/dist/knowledge/distill.js.map +1 -1
  23. package/dist/knowledge/graph.d.ts.map +1 -1
  24. package/dist/knowledge/graph.js +2 -1
  25. package/dist/knowledge/graph.js.map +1 -1
  26. package/dist/knowledge/reflect.d.ts +33 -0
  27. package/dist/knowledge/reflect.d.ts.map +1 -0
  28. package/dist/knowledge/reflect.js +115 -0
  29. package/dist/knowledge/reflect.js.map +1 -0
  30. package/dist/knowledge/scoring.d.ts.map +1 -1
  31. package/dist/knowledge/scoring.js +2 -1
  32. package/dist/knowledge/scoring.js.map +1 -1
  33. package/dist/knowledge/search.d.ts.map +1 -1
  34. package/dist/knowledge/search.js +4 -7
  35. package/dist/knowledge/search.js.map +1 -1
  36. package/dist/knowledge/store.d.ts.map +1 -1
  37. package/dist/knowledge/store.js +4 -3
  38. package/dist/knowledge/store.js.map +1 -1
  39. package/dist/search/excerpt.d.ts.map +1 -1
  40. package/dist/search/excerpt.js +2 -1
  41. package/dist/search/excerpt.js.map +1 -1
  42. package/dist/search/tfidf.d.ts +1 -0
  43. package/dist/search/tfidf.d.ts.map +1 -1
  44. package/dist/search/tfidf.js +38 -3
  45. package/dist/search/tfidf.js.map +1 -1
  46. package/dist/server.d.ts.map +1 -1
  47. package/dist/server.js +103 -534
  48. package/dist/server.js.map +1 -1
  49. package/dist/sessions/parser.d.ts.map +1 -1
  50. package/dist/sessions/parser.js +33 -60
  51. package/dist/sessions/parser.js.map +1 -1
  52. package/dist/sessions/search.js +17 -3
  53. package/dist/sessions/search.js.map +1 -1
  54. package/dist/sessions/summary.d.ts.map +1 -1
  55. package/dist/sessions/summary.js +6 -3
  56. package/dist/sessions/summary.js.map +1 -1
  57. package/dist/tool-handlers.d.ts +41 -0
  58. package/dist/tool-handlers.d.ts.map +1 -0
  59. package/dist/tool-handlers.js +425 -0
  60. package/dist/tool-handlers.js.map +1 -0
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/types.js +6 -4
  63. package/dist/types.js.map +1 -1
  64. package/dist/ui/app.js +86 -847
  65. package/dist/ui/index.html +17 -0
  66. package/dist/ui/render-knowledge.js +233 -0
  67. package/dist/ui/render-panel.js +350 -0
  68. package/dist/ui/render-search.js +109 -0
  69. package/dist/ui/render-sessions.js +234 -0
  70. package/dist/ui/styles.css +91 -0
  71. package/dist/ui/ui-utils.js +196 -0
  72. package/dist/vectorstore/store.d.ts +25 -44
  73. package/dist/vectorstore/store.d.ts.map +1 -1
  74. package/dist/vectorstore/store.js +167 -167
  75. package/dist/vectorstore/store.js.map +1 -1
  76. package/docs/ARCHITECTURE.md +29 -1
  77. package/docs/DASHBOARD.md +7 -0
  78. package/package.json +1 -1
package/dist/server.js CHANGED
@@ -1,187 +1,76 @@
1
1
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
2
  import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
3
- import { listEntries, readEntry, writeEntry, deleteEntry } from './knowledge/store.js';
4
- import { gitPull, gitPush, gitSync, ensureRepo } from './knowledge/git.js';
5
- import { getKnowledgeGraph, RELATIONSHIP_TYPES } from './knowledge/graph.js';
6
- import { getEntryScoring } from './knowledge/scoring.js';
7
- import { indexKnowledgeEntry } from './sessions/indexer.js';
8
- import { searchSessions } from './sessions/search.js';
9
- import { listSessions, getSessionSummary } from './sessions/summary.js';
10
- import { scopedSearch } from './sessions/scopes.js';
3
+ import { ensureRepo } from './knowledge/git.js';
4
+ import { RELATIONSHIP_TYPES } from './knowledge/graph.js';
11
5
  import { backgroundIndex } from './sessions/indexer.js';
12
- import { VectorStore } from './vectorstore/index.js';
13
- import { getProjectDirs, getSessionFiles, parseSessionFile, extractMessages, getSessionMeta, } from './sessions/parser.js';
14
- import { getConfig, loadPersistedConfig, savePersistedConfig, getConfigLocation } from './types.js';
6
+ import { getConfig } from './types.js';
15
7
  import { getVersion } from './version.js';
16
- const CATEGORIES = ['projects', 'people', 'decisions', 'workflows', 'notes'];
17
- const SCOPES = ['errors', 'plans', 'configs', 'tools', 'files', 'decisions', 'all'];
18
- // ── Input validation helpers ─────────────────────────────────────────────────
19
- function requireString(args, key, label) {
20
- const val = args[key];
21
- if (val === undefined || val === null || typeof val !== 'string') {
22
- throw new Error(`Missing or invalid required parameter: ${label ?? key} (expected string)`);
23
- }
24
- if (val.length === 0) {
25
- throw new Error(`Parameter ${label ?? key} must not be empty`);
26
- }
27
- return val;
28
- }
29
- function optionalString(args, key) {
30
- const val = args[key];
31
- if (val === undefined || val === null)
32
- return undefined;
33
- if (typeof val !== 'string') {
34
- throw new Error(`Parameter ${key} must be a string`);
35
- }
36
- return val;
37
- }
38
- function optionalNumber(args, key, min, max) {
39
- const val = args[key];
40
- if (val === undefined || val === null)
41
- return undefined;
42
- const num = typeof val === 'number' ? val : Number(val);
43
- if (isNaN(num)) {
44
- throw new Error(`Parameter ${key} must be a number`);
45
- }
46
- if (min !== undefined && num < min) {
47
- throw new Error(`Parameter ${key} must be >= ${min}`);
48
- }
49
- if (max !== undefined && num > max) {
50
- throw new Error(`Parameter ${key} must be <= ${max}`);
51
- }
52
- return num;
53
- }
54
- function optionalBoolean(args, key) {
55
- const val = args[key];
56
- if (val === undefined || val === null)
57
- return undefined;
58
- if (typeof val === 'boolean')
59
- return val;
60
- if (val === 'true')
61
- return true;
62
- if (val === 'false')
63
- return false;
64
- throw new Error(`Parameter ${key} must be a boolean`);
65
- }
66
- function validateEnum(val, allowed, key) {
67
- if (val === undefined)
68
- return undefined;
69
- if (!allowed.includes(val)) {
70
- throw new Error(`Parameter ${key} must be one of: ${allowed.join(', ')}`);
71
- }
72
- return val;
73
- }
8
+ import { toolHandlers, validateArgs, err, SCOPES } from './tool-handlers.js';
9
+ import { CATEGORIES } from './knowledge/store.js';
74
10
  export function createServer(options) {
75
11
  const server = new Server({ name: 'agent-knowledge', version: getVersion() }, { capabilities: { tools: {} } });
76
12
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
77
13
  tools: [
78
14
  {
79
- name: 'knowledge_list',
80
- description: 'List knowledge base entries. Optionally filter by category or tag. ' +
81
- 'Returns an array of entry paths with their frontmatter metadata.',
15
+ name: 'knowledge',
16
+ description: 'Knowledge base CRUD and sync. Actions: ' +
17
+ '"list" (browse entries), "read" (get entry content), ' +
18
+ '"write" (create/update entry, auto git sync), ' +
19
+ '"delete" (remove entry, auto git sync), "sync" (manual git pull + push).',
82
20
  inputSchema: {
83
21
  type: 'object',
84
22
  properties: {
23
+ action: {
24
+ type: 'string',
25
+ enum: ['list', 'read', 'write', 'delete', 'sync'],
26
+ description: 'Action to perform',
27
+ },
85
28
  category: {
86
29
  type: 'string',
87
30
  enum: [...CATEGORIES],
88
- description: 'Filter by category (projects, people, decisions, workflows, notes)',
31
+ description: 'Category (action=list: filter; action=write: target directory). ' +
32
+ 'One of: projects, people, decisions, workflows, notes',
89
33
  },
90
34
  tag: {
91
35
  type: 'string',
92
- description: 'Filter by tag — matches entries whose frontmatter tags array contains this value',
36
+ description: 'Filter by tag (action=list)',
93
37
  },
94
- },
95
- },
96
- },
97
- {
98
- name: 'knowledge_read',
99
- description: 'Read the full content of a knowledge base entry by its path (relative to the memory dir). ' +
100
- 'Returns the raw markdown including frontmatter.',
101
- inputSchema: {
102
- type: 'object',
103
- properties: {
104
38
  path: {
105
39
  type: 'string',
106
- description: "Relative path to the entry, e.g. 'projects/my-project.md'",
107
- },
108
- },
109
- required: ['path'],
110
- },
111
- },
112
- {
113
- name: 'knowledge_write',
114
- description: 'Create or update a knowledge base entry. The file is written under the given category directory. ' +
115
- 'Content should be markdown (frontmatter is optional). ' +
116
- 'Automatically commits and pushes after writing.',
117
- inputSchema: {
118
- type: 'object',
119
- properties: {
120
- category: {
121
- type: 'string',
122
- enum: [...CATEGORIES],
123
- description: 'Category directory to write into',
40
+ description: "Relative path to the entry, e.g. 'projects/my-project.md' (action=read, delete)",
124
41
  },
125
42
  filename: {
126
43
  type: 'string',
127
- description: "Filename (with or without .md extension), e.g. 'my-project.md'",
44
+ description: "Filename with or without .md extension (action=write), e.g. 'my-project.md'",
128
45
  },
129
46
  content: {
130
47
  type: 'string',
131
- description: 'Full markdown content for the entry',
132
- },
133
- },
134
- required: ['category', 'filename', 'content'],
135
- },
136
- },
137
- {
138
- name: 'knowledge_delete',
139
- description: 'Delete a knowledge base entry by path. Automatically commits and pushes after deletion.',
140
- inputSchema: {
141
- type: 'object',
142
- properties: {
143
- path: {
144
- type: 'string',
145
- description: "Relative path to the entry to delete, e.g. 'notes/old-note.md'",
146
- },
147
- },
148
- required: ['path'],
149
- },
150
- },
151
- {
152
- name: 'knowledge_sync',
153
- description: 'Synchronize the knowledge base with the remote git repository (pull then push). ' +
154
- 'Use this to ensure you have the latest entries from other machines/sessions.',
155
- inputSchema: {
156
- type: 'object',
157
- properties: {},
158
- },
159
- },
160
- {
161
- name: 'knowledge_sessions',
162
- description: 'List sessions with metadata (timestamps, branch, message counts, preview). ' +
163
- 'Optionally filter to a specific project. Returns sessions sorted newest first.',
164
- inputSchema: {
165
- type: 'object',
166
- properties: {
167
- project: {
168
- type: 'string',
169
- description: 'Filter by project name (substring match)',
48
+ description: 'Full markdown content for the entry (action=write)',
170
49
  },
171
50
  },
51
+ required: ['action'],
172
52
  },
173
53
  },
174
54
  {
175
55
  name: 'knowledge_search',
176
56
  description: 'Hybrid semantic + TF-IDF search across session conversations. ' +
177
- 'Results are ranked by blended relevance (semantic similarity + keyword match) × recency. ' +
178
- 'Use this to find past discussions, decisions, code snippets, or error messages.',
57
+ 'Results ranked by blended relevance (semantic similarity + keyword match) x recency. ' +
58
+ 'When "scope" is provided, searches within a specific domain (errors, plans, configs, tools, files, decisions). ' +
59
+ 'Without scope, performs general search across all sessions.',
179
60
  inputSchema: {
180
61
  type: 'object',
181
62
  properties: {
182
63
  query: {
183
64
  type: 'string',
184
- description: 'Search query — supports keywords and phrases',
65
+ description: 'Search query -- supports keywords and phrases',
66
+ },
67
+ scope: {
68
+ type: 'string',
69
+ enum: [...SCOPES],
70
+ description: 'Search scope (optional): errors (stack traces), plans (architecture, TODOs), ' +
71
+ 'configs (settings, env vars), tools (MCP tool calls), ' +
72
+ 'files (file paths, code refs), decisions (trade-offs, choices), all (no filter). ' +
73
+ 'When provided, performs scoped recall instead of general search.',
185
74
  },
186
75
  project: {
187
76
  type: 'string',
@@ -190,7 +79,7 @@ export function createServer(options) {
190
79
  role: {
191
80
  type: 'string',
192
81
  enum: ['user', 'assistant', 'all'],
193
- description: 'Filter by message role (default: all)',
82
+ description: 'Filter by message role (default: all, ignored when scope is set)',
194
83
  },
195
84
  max_results: {
196
85
  type: 'number',
@@ -198,7 +87,7 @@ export function createServer(options) {
198
87
  },
199
88
  ranked: {
200
89
  type: 'boolean',
201
- description: 'Use TF-IDF ranking (default: true). Set false for regex mode.',
90
+ description: 'Use TF-IDF ranking (default: true, ignored when scope is set). Set false for regex mode.',
202
91
  },
203
92
  semantic: {
204
93
  type: 'boolean',
@@ -209,456 +98,147 @@ export function createServer(options) {
209
98
  },
210
99
  },
211
100
  {
212
- name: 'knowledge_get',
213
- description: 'Retrieve the full conversation from a specific session. ' +
214
- 'Optionally include tool-use messages and/or limit to the last N messages.',
101
+ name: 'knowledge_session',
102
+ description: 'Session operations: list sessions, get a full conversation, or get a summary. ' +
103
+ 'Use action "list" to browse sessions, "get" to retrieve messages, "summary" for a quick overview.',
215
104
  inputSchema: {
216
105
  type: 'object',
217
106
  properties: {
107
+ action: {
108
+ type: 'string',
109
+ enum: ['list', 'get', 'summary'],
110
+ description: 'Action to perform',
111
+ },
218
112
  session_id: {
219
113
  type: 'string',
220
- description: 'The session UUID to retrieve',
114
+ description: 'Session UUID (required for get, summary)',
221
115
  },
222
116
  project: {
223
117
  type: 'string',
224
- description: 'Project name to narrow lookup',
118
+ description: 'Filter by project name (substring match)',
225
119
  },
226
120
  include_tools: {
227
121
  type: 'boolean',
228
- description: 'Include tool_use and tool_result messages (default: false)',
122
+ description: 'Include tool_use and tool_result messages (action=get, default: false)',
229
123
  },
230
124
  tail: {
231
125
  type: 'number',
232
- description: 'Only return the last N messages from the conversation',
126
+ description: 'Only return the last N messages (action=get)',
233
127
  },
234
128
  },
235
- required: ['session_id'],
129
+ required: ['action'],
236
130
  },
237
131
  },
238
132
  {
239
- name: 'knowledge_summary',
240
- description: 'Get a concise summary of a session: topics discussed, tools used, files modified. ' +
241
- 'Useful for quickly understanding what happened in a past session.',
133
+ name: 'knowledge_admin',
134
+ description: 'Admin operations: view vector store stats or view/update configuration. ' +
135
+ 'Use action "status" for index stats, "config" to view or update settings.',
242
136
  inputSchema: {
243
137
  type: 'object',
244
138
  properties: {
245
- session_id: {
139
+ action: {
246
140
  type: 'string',
247
- description: 'The session UUID to summarize',
141
+ enum: ['status', 'config'],
142
+ description: 'Action: status (vector store stats), config (view/update settings)',
248
143
  },
249
- project: {
250
- type: 'string',
251
- description: 'Project name to narrow lookup',
252
- },
253
- },
254
- required: ['session_id'],
255
- },
256
- },
257
- {
258
- name: 'knowledge_recall',
259
- description: 'Scoped hybrid search — search within a specific domain like errors, ' +
260
- 'plans, configs, tool usage, file references, or decisions. ' +
261
- 'Results ranked by blended relevance (semantic + keyword) × recency. ' +
262
- 'More targeted than knowledge_search when you know what kind of information you need.',
263
- inputSchema: {
264
- type: 'object',
265
- properties: {
266
- scope: {
267
- type: 'string',
268
- enum: [...SCOPES],
269
- description: 'Search scope: errors (stack traces, exceptions), plans (architecture, TODOs), ' +
270
- 'configs (settings, env vars), tools (MCP tool calls), ' +
271
- 'files (file paths, code refs), decisions (trade-offs, choices), all (no filter)',
272
- },
273
- query: {
274
- type: 'string',
275
- description: 'Search query within the chosen scope',
276
- },
277
- project: {
278
- type: 'string',
279
- description: 'Restrict to sessions from this project',
280
- },
281
- max_results: {
282
- type: 'number',
283
- description: 'Maximum number of results (default: 20)',
284
- },
285
- semantic: {
286
- type: 'boolean',
287
- description: 'Blend semantic vector similarity with TF-IDF (default: true). Falls back to pure TF-IDF if embeddings unavailable.',
288
- },
289
- },
290
- required: ['scope', 'query'],
291
- },
292
- },
293
- {
294
- name: 'knowledge_index_status',
295
- description: 'Get vector store statistics: total entries, breakdown by source (knowledge vs session), ' +
296
- 'database size, active embedding provider, and vector dimensions.',
297
- inputSchema: {
298
- type: 'object',
299
- properties: {},
300
- },
301
- },
302
- {
303
- name: 'knowledge_config',
304
- description: 'View or update knowledge configuration. Without arguments, returns current config. ' +
305
- 'With arguments, persists settings to knowledge-config.json. ' +
306
- 'Set git_url to enable git sync for the knowledge base. ' +
307
- 'Settings are persisted across restarts. Env vars override persisted values.',
308
- inputSchema: {
309
- type: 'object',
310
- properties: {
311
144
  git_url: {
312
145
  type: 'string',
313
- description: "Git remote URL for the knowledge base (e.g. 'https://github.com/user/memory.git'). Set to empty string to remove.",
146
+ description: 'Git remote URL (action=config). Set to empty string to remove.',
314
147
  },
315
148
  memory_dir: {
316
149
  type: 'string',
317
- description: 'Local directory for the knowledge base. Set to empty string to reset to default.',
150
+ description: 'Local knowledge base directory (action=config). Empty to reset.',
318
151
  },
319
152
  auto_distill: {
320
153
  type: 'boolean',
321
- description: 'Enable/disable automatic session distillation into the knowledge base (default: true).',
154
+ description: 'Enable/disable session distillation (action=config)',
322
155
  },
323
156
  },
157
+ required: ['action'],
324
158
  },
325
159
  },
326
160
  {
327
- name: 'knowledge_link',
328
- description: 'Create or update an edge between two knowledge entries in the knowledge graph. ' +
329
- 'Valid relationship types: related_to, supersedes, depends_on, contradicts, specializes, part_of, alternative_to, builds_on.',
161
+ name: 'knowledge_graph',
162
+ description: 'Knowledge graph operations: create/remove edges, list edges, or traverse via BFS. ' +
163
+ 'Relationship types: related_to, supersedes, depends_on, contradicts, specializes, part_of, alternative_to, builds_on.',
330
164
  inputSchema: {
331
165
  type: 'object',
332
166
  properties: {
167
+ action: {
168
+ type: 'string',
169
+ enum: ['link', 'unlink', 'list', 'traverse'],
170
+ description: 'Action: link (create edge), unlink (remove edge), list (list edges), traverse (BFS)',
171
+ },
333
172
  source: {
334
173
  type: 'string',
335
- description: "Source entry path, e.g. 'projects/my-project.md'",
174
+ description: "Source entry path (action=link/unlink), e.g. 'projects/my-project.md'",
336
175
  },
337
176
  target: {
338
177
  type: 'string',
339
- description: "Target entry path, e.g. 'decisions/architecture.md'",
178
+ description: "Target entry path (action=link/unlink), e.g. 'decisions/architecture.md'",
179
+ },
180
+ entry: {
181
+ type: 'string',
182
+ description: 'Entry path for filtering (action=list) or BFS start (action=traverse)',
340
183
  },
341
184
  rel_type: {
342
185
  type: 'string',
343
186
  enum: [...RELATIONSHIP_TYPES],
344
- description: 'Relationship type',
187
+ description: 'Relationship type (required for link, optional filter for unlink/list)',
345
188
  },
346
189
  strength: {
347
190
  type: 'number',
348
- description: 'Edge strength between 0 and 1 (default: 0.5)',
191
+ description: 'Edge strength 0-1 (action=link, default: 0.5)',
349
192
  },
350
- },
351
- required: ['source', 'target', 'rel_type'],
352
- },
353
- },
354
- {
355
- name: 'knowledge_unlink',
356
- description: 'Remove edge(s) between two knowledge entries. ' +
357
- 'If rel_type is omitted, removes all edges between source and target.',
358
- inputSchema: {
359
- type: 'object',
360
- properties: {
361
- source: {
362
- type: 'string',
363
- description: 'Source entry path',
364
- },
365
- target: {
366
- type: 'string',
367
- description: 'Target entry path',
368
- },
369
- rel_type: {
370
- type: 'string',
371
- enum: [...RELATIONSHIP_TYPES],
372
- description: 'Relationship type to remove (omit to remove all)',
193
+ depth: {
194
+ type: 'number',
195
+ description: 'Max traversal depth in hops (action=traverse, default: 2)',
373
196
  },
374
197
  },
375
- required: ['source', 'target'],
198
+ required: ['action'],
376
199
  },
377
200
  },
378
201
  {
379
- name: 'knowledge_links',
380
- description: 'List edges in the knowledge graph, optionally filtered by entry path and/or relationship type.',
202
+ name: 'knowledge_analyze',
203
+ description: 'Analysis tools: find near-duplicate entries or unconnected entries. ' +
204
+ 'Use action "consolidate" to scan for duplicates (TF-IDF similarity), ' +
205
+ '"reflect" to find entries with no graph connections and get a structured prompt for linking them.',
381
206
  inputSchema: {
382
207
  type: 'object',
383
208
  properties: {
384
- entry: {
209
+ action: {
385
210
  type: 'string',
386
- description: 'Filter edges connected to this entry path',
211
+ enum: ['consolidate', 'reflect'],
212
+ description: 'Action: consolidate (find duplicates), reflect (find unconnected entries)',
387
213
  },
388
- rel_type: {
214
+ category: {
389
215
  type: 'string',
390
- enum: [...RELATIONSHIP_TYPES],
391
- description: 'Filter by relationship type',
216
+ enum: [...CATEGORIES],
217
+ description: 'Scan only this category (omit for all)',
392
218
  },
393
- },
394
- },
395
- },
396
- {
397
- name: 'knowledge_graph',
398
- description: 'Traverse the knowledge graph via BFS from a starting entry. ' +
399
- 'Returns all nodes and edges within the specified depth (default: 2 hops).',
400
- inputSchema: {
401
- type: 'object',
402
- properties: {
403
- entry: {
404
- type: 'string',
405
- description: 'Starting entry path for BFS traversal',
219
+ threshold: {
220
+ type: 'number',
221
+ description: 'Similarity threshold 0-1 (action=consolidate, default: 0.5)',
406
222
  },
407
- depth: {
223
+ max_entries: {
408
224
  type: 'number',
409
- description: 'Maximum traversal depth in hops (default: 2)',
225
+ description: 'Max unconnected entries to include (action=reflect, default: 20)',
410
226
  },
411
227
  },
412
- required: ['entry'],
228
+ required: ['action'],
413
229
  },
414
230
  },
415
231
  ],
416
232
  }));
417
233
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
418
234
  const { name, arguments: args = {} } = request.params;
419
- const a = args;
420
- const config = getConfig();
235
+ const handler = toolHandlers[name];
236
+ if (!handler) {
237
+ return err(`Unknown tool: ${name}`);
238
+ }
421
239
  try {
422
- switch (name) {
423
- case 'knowledge_list': {
424
- const category = validateEnum(optionalString(a, 'category'), CATEGORIES, 'category');
425
- const tag = optionalString(a, 'tag');
426
- await gitPull(config.memoryDir);
427
- const entries = listEntries(config.memoryDir, category, tag);
428
- return ok(entries);
429
- }
430
- case 'knowledge_read': {
431
- const entryPath = requireString(a, 'path');
432
- await gitPull(config.memoryDir);
433
- const result = readEntry(config.memoryDir, entryPath);
434
- // Record access for scoring
435
- const scoring = getEntryScoring();
436
- const scoreInfo = scoring.recordAccess(entryPath);
437
- // Get 1-hop related entries from graph
438
- const graph = getKnowledgeGraph();
439
- const related = graph.getRelated(entryPath);
440
- return ok({ ...result, score: scoreInfo, related });
441
- }
442
- case 'knowledge_write': {
443
- const category = requireString(a, 'category');
444
- const filename = requireString(a, 'filename');
445
- const writeContent = requireString(a, 'content');
446
- if (writeContent.length > 1_000_000) {
447
- return err('Content too large (max 1MB)');
448
- }
449
- await gitPull(config.memoryDir);
450
- const filePath = writeEntry(config.memoryDir, category, filename, writeContent);
451
- const pushResult = await gitPush(config.memoryDir);
452
- // Index the entry for embeddings
453
- const autoLinks = [];
454
- try {
455
- await indexKnowledgeEntry(filePath, writeContent);
456
- // Auto-link: find similar entries via vector search
457
- const { getEmbeddingProvider } = await import('./embeddings/index.js');
458
- const provider = await getEmbeddingProvider();
459
- if (provider) {
460
- const queryVector = await provider.embedOne(writeContent.slice(0, 2000));
461
- const vecStore = new VectorStore();
462
- const similar = vecStore.searchBySource(queryVector, 'knowledge', 4);
463
- const graphStore = getKnowledgeGraph();
464
- for (const hit of similar) {
465
- if (hit.sourceId === filePath)
466
- continue;
467
- if (hit.score > 0.7) {
468
- graphStore.link(filePath, hit.sourceId, 'related_to', hit.score);
469
- autoLinks.push({
470
- target: hit.sourceId,
471
- similarity: Math.round(hit.score * 100) / 100,
472
- });
473
- }
474
- if (autoLinks.length >= 3)
475
- break;
476
- }
477
- }
478
- }
479
- catch (linkErr) {
480
- console.error('[knowledge] Auto-link failed:', linkErr);
481
- }
482
- const response = { path: filePath, git: pushResult };
483
- if (autoLinks.length > 0) {
484
- response.autoLinked = autoLinks;
485
- response.autoLinkMessage =
486
- 'Auto-linked to: ' +
487
- autoLinks.map((l) => l.target + ' (' + l.similarity + ')').join(', ');
488
- }
489
- return ok(response);
490
- }
491
- case 'knowledge_delete': {
492
- const entryPath = requireString(a, 'path');
493
- await gitPull(config.memoryDir);
494
- const deleted = deleteEntry(config.memoryDir, entryPath);
495
- const pushResult = await gitPush(config.memoryDir);
496
- return ok({ deleted, git: pushResult });
497
- }
498
- case 'knowledge_sync': {
499
- const result = await gitSync(config.memoryDir);
500
- return ok(result);
501
- }
502
- case 'knowledge_sessions': {
503
- const project = optionalString(a, 'project');
504
- const sessions = listSessions(project);
505
- return ok(sessions);
506
- }
507
- case 'knowledge_search': {
508
- const query = requireString(a, 'query');
509
- const project = optionalString(a, 'project');
510
- const role = validateEnum(optionalString(a, 'role'), ['user', 'assistant', 'all'], 'role') ?? 'all';
511
- const maxResults = optionalNumber(a, 'max_results', 1, 500) ?? 20;
512
- const ranked = optionalBoolean(a, 'ranked') ?? true;
513
- const semantic = optionalBoolean(a, 'semantic') ?? true;
514
- const results = await searchSessions(query, {
515
- project,
516
- role,
517
- maxResults,
518
- ranked,
519
- semantic,
520
- });
521
- return ok(results);
522
- }
523
- case 'knowledge_get': {
524
- const sessionId = requireString(a, 'session_id');
525
- const projectFilter = optionalString(a, 'project');
526
- const includeTools = optionalBoolean(a, 'include_tools') ?? false;
527
- const tail = optionalNumber(a, 'tail', 1, 10000);
528
- const projects = getProjectDirs().filter((p) => !projectFilter || p.name.toLowerCase().includes(projectFilter.toLowerCase()));
529
- for (const proj of projects) {
530
- const sessions = getSessionFiles(proj.path);
531
- const match = sessions.find((s) => s.id === sessionId);
532
- if (match) {
533
- const entries = parseSessionFile(match.file);
534
- let messages = extractMessages(entries);
535
- if (!includeTools) {
536
- messages = messages.filter((m) => m.role === 'user' || m.role === 'assistant');
537
- }
538
- if (tail && tail > 0) {
539
- messages = messages.slice(-tail);
540
- }
541
- const meta = getSessionMeta(entries);
542
- return ok({ meta, messages });
543
- }
544
- }
545
- return err(`Session ${sessionId} not found.`);
546
- }
547
- case 'knowledge_summary': {
548
- const sessionId = requireString(a, 'session_id');
549
- const project = optionalString(a, 'project');
550
- const result = getSessionSummary(sessionId, project);
551
- if (!result) {
552
- return err(`Session ${sessionId} not found.`);
553
- }
554
- return ok(result);
555
- }
556
- case 'knowledge_recall': {
557
- const scope = requireString(a, 'scope');
558
- validateEnum(scope, SCOPES, 'scope');
559
- const query = requireString(a, 'query');
560
- const project = optionalString(a, 'project');
561
- const maxResults = optionalNumber(a, 'max_results', 1, 500) ?? 20;
562
- const semantic = optionalBoolean(a, 'semantic') ?? true;
563
- const results = await scopedSearch(scope, query, {
564
- project,
565
- maxResults,
566
- semantic,
567
- });
568
- return ok(results);
569
- }
570
- case 'knowledge_index_status': {
571
- const store = new VectorStore();
572
- const stats = store.stats();
573
- return ok(stats);
574
- }
575
- case 'knowledge_config': {
576
- const gitUrlArg = optionalString(a, 'git_url');
577
- const memoryDirArg = optionalString(a, 'memory_dir');
578
- const autoDistillArg = optionalBoolean(a, 'auto_distill');
579
- const hasUpdates = gitUrlArg !== undefined || memoryDirArg !== undefined || autoDistillArg !== undefined;
580
- if (hasUpdates) {
581
- const updates = {};
582
- if (gitUrlArg !== undefined)
583
- updates.gitUrl = gitUrlArg || undefined;
584
- if (memoryDirArg !== undefined)
585
- updates.memoryDir = memoryDirArg || undefined;
586
- if (autoDistillArg !== undefined)
587
- updates.autoDistill = autoDistillArg;
588
- savePersistedConfig(updates);
589
- const newConfig = getConfig();
590
- if (gitUrlArg && gitUrlArg.length > 0) {
591
- const repoResult = ensureRepo(newConfig.memoryDir, newConfig.gitUrl);
592
- return ok({
593
- message: 'Config saved',
594
- repoSetup: repoResult,
595
- config: {
596
- gitUrl: newConfig.gitUrl,
597
- memoryDir: newConfig.memoryDir,
598
- autoDistill: newConfig.autoDistill,
599
- embeddingProvider: newConfig.embeddingProvider,
600
- },
601
- });
602
- }
603
- return ok({
604
- message: 'Config saved',
605
- config: {
606
- gitUrl: newConfig.gitUrl,
607
- memoryDir: newConfig.memoryDir,
608
- autoDistill: newConfig.autoDistill,
609
- embeddingProvider: newConfig.embeddingProvider,
610
- },
611
- });
612
- }
613
- const persisted = loadPersistedConfig();
614
- return ok({
615
- active: {
616
- gitUrl: config.gitUrl ?? null,
617
- memoryDir: config.memoryDir,
618
- autoDistill: config.autoDistill,
619
- embeddingProvider: config.embeddingProvider,
620
- embeddingAlpha: config.embeddingAlpha,
621
- },
622
- persisted,
623
- configFile: getConfigLocation(),
624
- note: 'Config stored at a tool-agnostic location. Env vars override persisted config.',
625
- });
626
- }
627
- case 'knowledge_link': {
628
- const source = requireString(a, 'source');
629
- const target = requireString(a, 'target');
630
- const relType = requireString(a, 'rel_type');
631
- validateEnum(relType, RELATIONSHIP_TYPES, 'rel_type');
632
- const strength = optionalNumber(a, 'strength', 0, 1) ?? 0.5;
633
- const graphStore = getKnowledgeGraph();
634
- const edge = graphStore.link(source, target, relType, strength);
635
- return ok(edge);
636
- }
637
- case 'knowledge_unlink': {
638
- const source = requireString(a, 'source');
639
- const target = requireString(a, 'target');
640
- const relType = validateEnum(optionalString(a, 'rel_type'), RELATIONSHIP_TYPES, 'rel_type');
641
- const graphStore = getKnowledgeGraph();
642
- const removed = graphStore.unlink(source, target, relType);
643
- return ok({ removed });
644
- }
645
- case 'knowledge_links': {
646
- const entry = optionalString(a, 'entry');
647
- const relType = validateEnum(optionalString(a, 'rel_type'), RELATIONSHIP_TYPES, 'rel_type');
648
- const graphStore = getKnowledgeGraph();
649
- const edges = graphStore.links(entry, relType);
650
- return ok(edges);
651
- }
652
- case 'knowledge_graph': {
653
- const entry = requireString(a, 'entry');
654
- const depth = optionalNumber(a, 'depth', 1, 10) ?? 2;
655
- const graphStore = getKnowledgeGraph();
656
- const graphResult = graphStore.graph(entry, depth);
657
- return ok(graphResult);
658
- }
659
- default:
660
- return err(`Unknown tool: ${name}`);
661
- }
240
+ const validated = validateArgs(args);
241
+ return await handler(validated);
662
242
  }
663
243
  catch (error) {
664
244
  const message = error instanceof Error ? error.message : String(error);
@@ -669,22 +249,11 @@ export function createServer(options) {
669
249
  const repoResult = ensureRepo(startupConfig.memoryDir, startupConfig.gitUrl);
670
250
  console.error(`[knowledge] Repo init: ${repoResult.message}`);
671
251
  if (options?.isLeader !== false) {
672
- setTimeout(() => backgroundIndex().catch((err) => console.error('[knowledge] Background index failed:', err)), 5000);
252
+ setTimeout(() => backgroundIndex().catch((bgErr) => console.error('[knowledge] Background index failed:', bgErr)), 5000);
673
253
  }
674
254
  else {
675
- console.error('[knowledge] Follower instance — skipping background indexing');
255
+ console.error('[knowledge] Follower instance -- skipping background indexing');
676
256
  }
677
257
  return server;
678
258
  }
679
- function ok(result) {
680
- return {
681
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
682
- };
683
- }
684
- function err(message) {
685
- return {
686
- content: [{ type: 'text', text: JSON.stringify({ error: message }, null, 2) }],
687
- isError: true,
688
- };
689
- }
690
259
  //# sourceMappingURL=server.js.map