Repository navigation
Expand file tree
/
Copy pathserver.go
More file actions
702 lines (584 loc) · 35 KB
/
Copy pathserver.go
File metadata and controls
702 lines (584 loc) · 35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
package main
import (
"context"
"encoding/json"
"fmt"
"sync"
"sync/atomic"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/unbound-force/dewey/v3/backend"
"github.com/unbound-force/dewey/v3/embed"
"github.com/unbound-force/dewey/v3/llm"
"github.com/unbound-force/dewey/v3/store"
"github.com/unbound-force/dewey/v3/tools"
"github.com/unbound-force/dewey/v3/vault"
)
// serverConfig holds optional dependencies for the MCP server.
type serverConfig struct {
embedder embed.Embedder
store *store.Store
vaultPath string
indexReady *atomic.Bool
indexMutex *sync.Mutex
synth llm.Synthesizer
maxChunkChars int // max chars per embedding chunk; 0 uses embed.DefaultMaxChunkChars
}
// serverOption configures the MCP server.
type serverOption func(*serverConfig)
// WithEmbedder sets the embedding provider for semantic search tools.
func WithEmbedder(e embed.Embedder) serverOption {
return func(c *serverConfig) { c.embedder = e }
}
// WithPersistentStore sets the SQLite store for semantic search tools.
func WithPersistentStore(s *store.Store) serverOption {
return func(c *serverConfig) { c.store = s }
}
// WithVaultPath sets the vault root path for tools that need to locate
// configuration files (e.g., sources.yaml for indexing tools).
func WithVaultPath(p string) serverOption {
return func(c *serverConfig) { c.vaultPath = p }
}
// WithIndexReady sets the atomic flag that tracks background indexing status.
// When non-nil, the health tool reports whether indexing is still in progress.
func WithIndexReady(ready *atomic.Bool) serverOption {
return func(c *serverConfig) { c.indexReady = ready }
}
// WithIndexMutex sets the shared mutex for indexing mutual exclusion.
// This mutex is shared between the background startup indexing goroutine
// and the index/reindex MCP tools to prevent concurrent indexing operations.
func WithIndexMutex(mu *sync.Mutex) serverOption {
return func(c *serverConfig) { c.indexMutex = mu }
}
// WithSynthesizer sets the synthesis provider for compile and curate. When
// nil (the default), those tools return prompt-mode payloads for the calling
// agent to complete.
func WithSynthesizer(s llm.Synthesizer) serverOption {
return func(c *serverConfig) { c.synth = s }
}
// WithMaxChunkChars sets the maximum character count per embedding chunk.
// When set to a positive value, overrides embed.DefaultMaxChunkChars for
// all embedding generation in tools registered on this server.
func WithMaxChunkChars(n int) serverOption {
return func(c *serverConfig) { c.maxChunkChars = n }
}
// newServer creates and configures the MCP server with all tools registered.
// If readOnly is true, write tools are not registered.
// Tools requiring DataScript are only registered if the backend supports it.
// The embedder and persistent store are optional — semantic search tools
// are always registered but return clear error messages when unavailable.
// Returns the server and the total number of registered tools.
func newServer(b backend.Backend, readOnly bool, opts ...serverOption) (*mcp.Server, int) {
var cfg serverConfig
for _, opt := range opts {
opt(&cfg)
}
srv := mcp.NewServer(
&mcp.Implementation{
Name: "dewey",
Version: version,
},
nil,
)
_, hasDataScript := b.(backend.HasDataScript)
nav := tools.NewNavigate(b)
search := tools.NewSearch(b).WithStore(cfg.store)
analyze := tools.NewAnalyze(b)
journal := tools.NewJournal(b)
var toolCount int
toolCount += registerNavigateTools(srv, nav, hasDataScript)
toolCount += registerSearchTools(srv, search, hasDataScript)
toolCount += registerAnalyzeTools(srv, analyze)
if !readOnly {
write := tools.NewWrite(b)
decision := tools.NewDecision(b)
toolCount += registerWriteTools(srv, write)
toolCount += registerDecisionTools(srv, decision)
}
toolCount += registerJournalTools(srv, journal)
if hasDataScript {
flashcard := tools.NewFlashcard(b)
toolCount += registerFlashcardTools(srv, flashcard, readOnly)
whiteboard := tools.NewWhiteboard(b)
toolCount += registerWhiteboardTools(srv, whiteboard)
}
semantic := tools.NewSemantic(cfg.embedder, cfg.store)
toolCount += registerSemanticTools(srv, semantic)
if !readOnly {
learning := tools.NewLearning(cfg.embedder, cfg.store, cfg.vaultPath, cfg.maxChunkChars)
toolCount += registerLearningTools(srv, learning)
// Index-build provenance (IBP-FR-001, design D4): the index and
// reindex tools stamp the resolved binary version and index format
// into the store's metadata after each completed pass. Both values
// live in package main (tools/ cannot import it), so they are
// injected here as data.
indexing := tools.NewIndexing(cfg.store, cfg.embedder, cfg.vaultPath, cfg.indexMutex, cfg.maxChunkChars, tools.IndexBuildInfo{
DeweyVersion: resolveVersion(),
IndexFormat: IndexFormat,
})
toolCount += registerIndexingTools(srv, indexing)
// Knowledge compilation tools (013-knowledge-compile, T032/T033).
// The synthesizer is supplied by executeServe when a provider is
// configured; nil keeps the prompt-mode fallback.
compile := tools.NewCompile(cfg.store, cfg.embedder, cfg.synth, cfg.vaultPath, cfg.indexMutex, cfg.maxChunkChars)
toolCount += registerCompileTools(srv, compile)
// Knowledge curation tools (015-curated-knowledge-stores, T022).
// The synthesizer is supplied by executeServe when a provider is
// configured; nil keeps the prompt-mode fallback.
curateTool := tools.NewCurate(cfg.store, cfg.embedder, cfg.synth, cfg.vaultPath, cfg.indexMutex, cfg.maxChunkChars)
toolCount += registerCurateTools(srv, curateTool)
lint := tools.NewLint(cfg.store, cfg.embedder, cfg.vaultPath, cfg.maxChunkChars)
toolCount += registerLintTools(srv, lint)
promote := tools.NewPromote(cfg.store, cfg.vaultPath)
toolCount += registerPromoteTools(srv, promote)
// Candidate verification (dewey-distill-verify-step, issue #151):
// read-only queue check ahead of promote's human gate. The vault
// path anchors the local-git anchor checks; when empty they are
// skipped.
verify := tools.NewVerify(cfg.store, cfg.vaultPath)
toolCount += registerVerifyTools(srv, verify)
// Distill automation tools (018-weekly-distill-automation,
// T036): the unattended pipeline's server-side stages — scope,
// grouping, rolling PRs — named by the distiller agent's
// frontmatter allowlist. The embedder backs grouping's
// embedding assignments (nil degrades to tag centroids); the
// store backs the scope's SQLite learning union (nil degrades
// to the filesystem leg); the vault path anchors git, files,
// and artifacts.
distill := tools.NewDistill(cfg.store, cfg.embedder, cfg.vaultPath)
toolCount += registerDistillTools(srv, distill)
}
toolCount += registerHealthTool(srv, b, readOnly, &cfg)
// Vault management tools (Obsidian-specific).
if vaultClient, ok := b.(*vault.Client); ok && !readOnly {
srv.AddTool(&mcp.Tool{
Name: "reload",
Description: "Force a full vault re-index. Clears all cached pages and blocks, then re-reads all .md files. Use when external changes need to be refreshed.",
InputSchema: json.RawMessage(`{"type":"object","properties":{},"required":[],"additionalProperties":false}`),
}, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
if err := vaultClient.Reload(); err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf("Reload failed: %v", err)}},
IsError: true,
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: "Vault reloaded successfully"}},
}, nil
})
toolCount++
}
return srv, toolCount
}
// registerNavigateTools registers page, block, link, and traversal tools.
// Returns the number of tools registered.
func registerNavigateTools(srv *mcp.Server, nav *tools.Navigate, hasDataScript bool) int {
count := 5
mcp.AddTool(srv, &mcp.Tool{
Name: "get_page",
Description: "Get a Logseq page with its full recursive block tree, properties, tags, and parsed links. Every block includes extracted [[links]], ((references)), #tags, and key:: value properties. Use maxBlocks to limit output size for large pages. A bare name also finds compiled/<name> and learning/<name> when no vault page has that name.",
}, nav.GetPage)
mcp.AddTool(srv, &mcp.Tool{
Name: "get_block",
Description: "Get a specific block by UUID with its ancestor chain (path to root page), children, and optionally siblings. Provides full context for where a block sits in the knowledge hierarchy.",
}, nav.GetBlock)
mcp.AddTool(srv, &mcp.Tool{
Name: "list_pages",
Description: "List pages with filtering by namespace, property, or tag. Returns page summaries with block count and link count. Sort by name, modified, or created.",
}, nav.ListPages)
mcp.AddTool(srv, &mcp.Tool{
Name: "get_links",
Description: "Get forward links (pages this page links to) and backlinks (pages that link to this page) for any page. Each link includes the specific block containing it. In the forward direction, a bare name also finds compiled/<name> and learning/<name>.",
}, nav.GetLinks)
mcp.AddTool(srv, &mcp.Tool{
Name: "traverse",
Description: "Find paths between two pages through the link graph using BFS. Discovers how concepts are connected through intermediate pages. Returns all paths up to max_hops length. A bare start name also finds compiled/<name> and learning/<name>.",
}, nav.Traverse)
if hasDataScript {
mcp.AddTool(srv, &mcp.Tool{
Name: "get_references",
Description: "Get all blocks that reference a specific block via ((uuid)) block references. Returns the referencing blocks with their page context.",
}, nav.GetReferences)
count++
}
return count
}
// registerSearchTools registers full-text search, property query, tag, and DataScript tools.
// Returns the number of tools registered.
func registerSearchTools(srv *mcp.Server, search *tools.Search, hasDataScript bool) int {
count := 3
mcp.AddTool(srv, &mcp.Tool{
Name: "search",
Description: "Full-text search across all blocks in the knowledge graph. Returns matching blocks with surrounding context (parent chain and sibling blocks) so you understand where each match sits. Optional source_id and has_tag narrow results like semantic_search_filtered.",
}, search.Search)
mcp.AddTool(srv, &mcp.Tool{
Name: "query_properties",
Description: "Find blocks and pages by property values. Search for all content with a specific property key, or filter by property value with operators (eq, contains, gt, lt).",
}, search.QueryProperties)
mcp.AddTool(srv, &mcp.Tool{
Name: "find_by_tag",
Description: "Find all blocks and pages with a specific tag, including child tags in the tag hierarchy. Returns content grouped by page. Optional source_id keeps only pages of that source.",
}, search.FindByTag)
if hasDataScript {
mcp.AddTool(srv, &mcp.Tool{
Name: "query_datalog",
Description: "Execute raw DataScript/Datalog queries against the Logseq database. This is the most powerful query mechanism — can find anything. Example: [:find (pull ?b [*]) :where [?b :block/marker \"TODO\"]] finds all TODO blocks.",
}, search.QueryDatalog)
count++
}
return count
}
// registerAnalyzeTools registers graph overview, connections, gaps, orphans, and clusters tools.
// Returns the number of tools registered.
func registerAnalyzeTools(srv *mcp.Server, analyze *tools.Analyze) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "graph_overview",
Description: "Get a high-level overview of the entire knowledge graph: total pages, blocks, links, most connected pages, orphan count, namespace breakdown. Builds an in-memory graph for analysis.",
}, analyze.GraphOverview)
mcp.AddTool(srv, &mcp.Tool{
Name: "find_connections",
Description: "Discover how two pages are connected through the link graph. Returns whether they're directly linked, shortest paths between them, and shared connections (pages both link to or are linked from).",
}, analyze.FindConnections)
mcp.AddTool(srv, &mcp.Tool{
Name: "knowledge_gaps",
Description: "Find sparse areas in the knowledge graph: orphan pages (no links in or out), dead-end pages (linked to but link nowhere), and weakly-linked pages. Helps identify where to add connections.",
}, analyze.KnowledgeGaps)
mcp.AddTool(srv, &mcp.Tool{
Name: "list_orphans",
Description: "List orphan pages (no incoming or outgoing links). Returns page names with block counts and property status. Use for graph hygiene — find disconnected pages that need linking or cleanup.",
}, analyze.ListOrphans)
mcp.AddTool(srv, &mcp.Tool{
Name: "topic_clusters",
Description: "Discover topic clusters by finding connected components in the knowledge graph. Returns groups of densely connected pages with their hub (most connected page in each cluster).",
}, analyze.TopicClusters)
return 5
}
// registerWriteTools registers page and block write/mutation tools.
// Returns the number of tools registered.
func registerWriteTools(srv *mcp.Server, write *tools.Write) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "create_page",
Description: "Create a new Logseq page with optional properties and initial blocks. Use properties for metadata like type::, status::, etc.",
}, write.CreatePage)
mcp.AddTool(srv, &mcp.Tool{
Name: "append_blocks",
Description: "Append plain-text blocks to an existing page. Accepts an array of strings (same format as create_page blocks). Simpler than upsert_blocks when you just need to add content without nesting or properties.",
}, write.AppendBlocks)
mcp.AddTool(srv, &mcp.Tool{
Name: "update_block",
Description: "Update an existing block's content by UUID. Replaces the block's entire content with the new value. Use get_page or get_block first to find the UUID.",
}, write.UpdateBlock)
mcp.AddTool(srv, &mcp.Tool{
Name: "delete_block",
Description: "Delete a block by UUID. Removes the block and all its children from the graph. This is irreversible.",
}, write.DeleteBlock)
// upsert_blocks uses raw handler because BlockInput has recursive Children field
// which the schema generator can't handle.
srv.AddTool(&mcp.Tool{
Name: "upsert_blocks",
Description: "Batch create blocks on a page. Supports nested children for building block hierarchies. Append or prepend to existing content.",
InputSchema: json.RawMessage(`{"type":"object","properties":{"page":{"type":"string","description":"Page name to add blocks to"},"blocks":{"type":"array","description":"Blocks to create. Each block has content (string), optional properties (object of strings), and optional children (array of blocks).","items":{"type":"object"}},"position":{"type":"string","description":"Where to add: append or prepend. Default: append"}},"required":["page","blocks"],"additionalProperties":false}`),
}, write.UpsertBlocksRaw)
mcp.AddTool(srv, &mcp.Tool{
Name: "move_block",
Description: "Move a block to a new location — before, after, or as a child of another block.",
}, write.MoveBlock)
mcp.AddTool(srv, &mcp.Tool{
Name: "delete_page",
Description: "Delete a page entirely from the graph. Removes the page and all its blocks. This is irreversible.",
}, write.DeletePage)
mcp.AddTool(srv, &mcp.Tool{
Name: "rename_page",
Description: "Rename a page and update all [[links]] across the graph that reference the old name. Preserves content and connections.",
}, write.RenamePage)
mcp.AddTool(srv, &mcp.Tool{
Name: "bulk_update_properties",
Description: "Set a property (key:: value) on multiple pages at once. Useful for backfilling metadata like type::, status::, etc. across many pages in one call. Bare page names resolve compiled/<name> and learning/<name> on the read, but writes to store-only pages fail.",
}, write.BulkUpdateProperties)
mcp.AddTool(srv, &mcp.Tool{
Name: "link_pages",
Description: "Create a bidirectional connection between two pages by adding a link block to each. Optionally include context describing the relationship.",
}, write.LinkPages)
return 10
}
// registerDecisionTools registers decision tracking and analysis health tools.
// Returns the number of tools registered.
func registerDecisionTools(srv *mcp.Server, decision *tools.Decision) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "decision_check",
Description: "Surface all tracked decisions in the knowledge graph. Returns open, overdue, and optionally resolved decisions with deadline status. Use at session start to check what needs attention.",
}, decision.DecisionCheck)
mcp.AddTool(srv, &mcp.Tool{
Name: "decision_create",
Description: "Create a new DECIDE block on a page with #decision tag and deadline. Decisions live on the page where context is richest, not on a central backlog.",
}, decision.DecisionCreate)
mcp.AddTool(srv, &mcp.Tool{
Name: "decision_resolve",
Description: "Mark a decision as DONE with today's date and an optional outcome. Changes the DECIDE marker to DONE and adds resolved:: property.",
}, decision.DecisionResolve)
mcp.AddTool(srv, &mcp.Tool{
Name: "decision_defer",
Description: "Push a decision's deadline to a new date with a reason. Tracks deferral count and warns after 3+ deferrals.",
}, decision.DecisionDefer)
mcp.AddTool(srv, &mcp.Tool{
Name: "analysis_health",
Description: "Audit analysis, strategy, and assessment pages for graph connectivity. A page is healthy if it has 3+ outgoing links or contains a decision. Finds isolated analyses that don't connect back to the knowledge graph.",
}, decision.AnalysisHealth)
return 5
}
// registerJournalTools registers journal range and search tools.
// Returns the number of tools registered.
func registerJournalTools(srv *mcp.Server, journal *tools.Journal) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "journal_range",
Description: "Get journal entries across a date range. Returns journal pages with their full block trees. Dates in YYYY-MM-DD format.",
}, journal.JournalRange)
mcp.AddTool(srv, &mcp.Tool{
Name: "journal_search",
Description: "Search within journal entries specifically. Optionally filter by date range. Returns matching blocks with their journal date context.",
}, journal.JournalSearch)
return 2
}
// registerFlashcardTools registers flashcard overview, due, and create tools.
// Returns the number of tools registered.
func registerFlashcardTools(srv *mcp.Server, flashcard *tools.Flashcard, readOnly bool) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "flashcard_overview",
Description: "Get SRS (spaced repetition) statistics: total cards, cards due for review, new vs reviewed cards, average repetitions. Gives a snapshot of the flashcard collection health.",
}, flashcard.FlashcardOverview)
mcp.AddTool(srv, &mcp.Tool{
Name: "flashcard_due",
Description: "Get flashcards currently due for review. Returns card content, page, and SRS properties (ease factor, interval, repeats). Prioritizes new cards and overdue reviews.",
}, flashcard.FlashcardDue)
count := 2
if !readOnly {
mcp.AddTool(srv, &mcp.Tool{
Name: "flashcard_create",
Description: "Create a new flashcard on a page. Adds a block with #card tag (front/question) and a child block (back/answer). The card will appear in Logseq's flashcard review system.",
}, flashcard.FlashcardCreate)
count++
}
return count
}
// registerWhiteboardTools registers whiteboard list and detail tools.
// Returns the number of tools registered.
func registerWhiteboardTools(srv *mcp.Server, whiteboard *tools.Whiteboard) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "list_whiteboards",
Description: "List all Logseq whiteboards in the graph. Whiteboards are infinite canvas spaces where concepts are visually arranged and connected.",
}, whiteboard.ListWhiteboards)
mcp.AddTool(srv, &mcp.Tool{
Name: "get_whiteboard",
Description: "Get a whiteboard's content including embedded pages, block references, visual connections between elements, and any text content. Reveals how concepts are spatially organized. A bare name also finds compiled/<name> and learning/<name>.",
}, whiteboard.GetWhiteboard)
return 2
}
// registerSemanticTools registers vector-based semantic search tools.
// Returns the number of tools registered.
func registerSemanticTools(srv *mcp.Server, semantic *tools.Semantic) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "semantic_search",
Description: "Find documents semantically similar to a natural language query, ranked by cosine similarity. Returns results with provenance metadata. Optional source_id and has_tag narrow results like semantic_search_filtered.",
}, semantic.SemanticSearch)
mcp.AddTool(srv, &mcp.Tool{
Name: "similar",
Description: "Given a document (by page name or block UUID), find the most similar documents in the index. Optional source_id and has_tag narrow the results like semantic_search_filtered.",
}, semantic.Similar)
mcp.AddTool(srv, &mcp.Tool{
Name: "semantic_search_filtered",
Description: "Semantic search constrained by metadata filters (source type, repository, properties).",
}, semantic.SemanticSearchFiltered)
return 3
}
// registerLearningTools registers the store_learning MCP tool for persisting
// agent learnings into the knowledge graph with optional embeddings.
// Returns the number of tools registered.
func registerLearningTools(srv *mcp.Server, learning *tools.Learning) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "store_learning",
Description: "Store a learning (insight, pattern, gotcha) with optional tags. The learning is persisted with embeddings and immediately searchable via semantic_search. Use to build semantic memory across sessions. Pins as_of to the vault's git HEAD unless the caller passes as_of (owner/repo@<sha>) for a learning observed elsewhere; optionally records evidence locators, a validity status, and the identity of a learning this one supersedes (the target is marked superseded_by, never deleted). Concurrent same-target supersessions are serialized; a losing call returns supersedes_warning naming the winner.",
}, learning.StoreLearning)
mcp.AddTool(srv, &mcp.Tool{
Name: "supersede_learning",
Description: "Link two existing learnings: the successor gains supersedes naming the target, and the target gains superseded_by and validity: superseded. The target is never deleted and its tier never changes. Use to confirm a compile-proposed supersession at the review gate, or to record an explicit replacement between learnings that already exist. Refuses unknown identities, same-learning pairs, already-superseded targets, conflicting declarations, and any link that would close a cycle; a pre-existing cyclic chain is reported for human repair and never extended.",
}, learning.SupersedeLearning)
return 2
}
// registerIndexingTools registers the index and reindex MCP tools for
// triggering source re-indexing while the server is running. These are
// write operations — excluded in read-only mode (per plan D4, D8).
// Returns the number of tools registered.
func registerIndexingTools(srv *mcp.Server, indexing *tools.Indexing) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "index",
Description: "Fetch and index configured content sources. Updates the knowledge graph with new and changed content from disk, GitHub, web, and code sources. Optionally filter to a single source by ID.",
}, indexing.Index)
mcp.AddTool(srv, &mcp.Tool{
Name: "reindex",
Description: "Delete and rebuild all external source content in the index. Preserves local vault content and stored learnings. Use when the index is stale or corrupted.",
}, indexing.Reindex)
return 2
}
// registerCompileTools registers the compile MCP tool for synthesizing
// stored learnings into compiled knowledge articles. Write operation —
// excluded in read-only mode.
// Returns the number of tools registered.
func registerCompileTools(srv *mcp.Server, compile *tools.Compile) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "compile",
Description: "Synthesize stored learnings into compiled knowledge articles. Groups learnings by topic, cites sources per claim, proposes supersessions for human confirmation instead of resolving contradictions by recency, and produces current-state articles with history and citation coverage.",
}, compile.Compile)
mcp.AddTool(srv, &mcp.Tool{
Name: "store_compiled",
Description: "Persist a compiled article that was synthesized by the calling agent. Use after calling compile (which returns synthesis prompts) and performing the synthesis yourself.",
}, compile.StoreCompiled)
return 2
}
// registerCurateTools registers the curate MCP tool for extracting
// structured knowledge from indexed sources into knowledge stores.
// Write operation — excluded in read-only mode.
// Returns the number of tools registered.
func registerCurateTools(srv *mcp.Server, curateTool *tools.Curate) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "curate",
Description: "Curate knowledge from indexed sources into structured knowledge stores.",
}, curateTool.Curate)
return 1
}
// registerLintTools registers the lint MCP tool for scanning the knowledge
// base for quality issues. Write operation when fix=true — excluded in
// read-only mode.
// Returns the number of tools registered.
func registerLintTools(srv *mcp.Server, lint *tools.Lint) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "lint",
Description: "Scan the knowledge base for quality issues: stale decisions, uncompiled learnings, embedding gaps, potential contradictions, knowledge-store quality, stale knowledge stores, sanitization findings, citation coverage of store-backed compiled articles (citation_coverage), and learnings whose cited code changed (anchor_drift) or is absent at the pinned commit (anchor_missing). The anchor_checks field reports whether the anchor checks ran, were skipped, or failed. With fix=true, regenerates missing embeddings and marks drifted learnings validity stale-unverified (tiers are never changed).",
}, lint.Lint)
return 1
}
// registerPromoteTools registers the promote MCP tool. Promotion is a
// frontmatter file edit on the current branch (git-is-the-source-of-record,
// PW-FR-001): the tool writes tier: validated into the page file and never
// writes the database tier, which stays a cache recomputed on the next
// index. Write operation — excluded in read-only mode.
// Returns the number of tools registered.
func registerPromoteTools(srv *mcp.Server, promote *tools.Promote) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "promote",
Description: "Promote a draft compiled article or curated knowledge page by writing tier: validated into the page file's frontmatter on the current branch — the file diff, carried by a pull request, is the promotion artifact for human review. The database tier is a cache recomputed on the next index, so a branch-only promotion keeps indexing as draft until the pull request merges to the default branch and the server re-indexes (the merge is the vouch). Accepts page for one page or pages for a batch; names resolve exact, then case-insensitive, then bare tags against the compiled/, learning/, and knowledge/ namespaces, then source doc IDs; ambiguous matches are refused. Only files under compiled/ or knowledge/ are promotable — learnings stay draft forever and are never promotable. Batch promotion is all-or-nothing.",
}, promote.Promote)
return 1
}
// registerVerifyTools registers the verify_candidates MCP tool for the
// read-only verification of the promotable candidate queue ahead of the
// human promotion gate. The tool itself mutates nothing — verification is
// not endorsement — but it needs the persistent store, so it is registered
// with the other store-backed knowledge tools, which are excluded in
// read-only mode.
// Returns the number of tools registered.
func registerVerifyTools(srv *mcp.Server, verify *tools.Verify) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "verify_candidates",
Description: "Read-only verification of the promotable candidate queue — every draft page under learning/, compiled/, and knowledge/ — ahead of the human promotion gate. Checks each candidate's cited evidence locators against its as_of pin and HEAD via local git and reports one result per candidate (anchors_ok, drifted, missing, no_anchors, or skipped) plus summary counts. Nothing is mutated: no tier, validity, content, or file changes. Verification is not endorsement — anchors_ok states only that cited paths exist at the pin and are unchanged at HEAD, never that a claim is correct or worth acting on — and promotion stays a human decision. Provide pages (exact page names, deduplicated; a missing or non-draft page is reported skipped with a reason) or tags (matching via page-name prefixes learning/{tag}-* and compiled/{tag} or the tag property, exact with the delimiter after the tag, never from prose), not both; with neither, every draft candidate is verified.",
}, verify.VerifyCandidates)
return 1
}
// registerDistillTools registers the unattended distill pipeline tools
// (018-weekly-distill-automation, T036): scope, group_learners, and
// rolling_pr, registered with the other store-backed knowledge tools —
// rolling_pr writes branches and PRs, so read-only mode excludes all
// three.
// Returns the number of tools registered.
func registerDistillTools(srv *mcp.Server, distill *tools.Distill) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "scope",
Description: "Compute the unattended distill scope — every learning identity at the vault's default-branch ref, minus identities cited by compiled articles' frontmatter sources, minus distill-policy tag exclusions — deterministically from git alone (filesystem fallback when the ref is unavailable; provenance carries which leg ran). Never interactive: ambiguity or policy absence degrades with warnings, never a question. Optionally pass backlog_from (YYYY-MM-DD) to bound the scope to learnings created on or before that UTC date — the backlog bootstrap; legacy identities without an embedded timestamp always pass. An empty scope exits no-op: the durable run artifact is recorded server-side and the result carries no_op with the artifact path — no PR, no comment. A non-empty scope is recorded server-side as a run and the result carries its run_id: pass that run_id to group_learners and then rolling_pr instead of copying identities between calls.",
}, distill.Scope)
mcp.AddTool(srv, &mcp.Tool{
Name: "group_learners",
Description: "Group in-scope learnings into per-theme clusters for the rolling distill PRs: must-colocate supersession components first, then embedding-cosine assignment to the closest compiled article with tag-centroid fallback when embeddings are unavailable, and a deterministic tie-breaker within the margin. Every assignment carries its source and confidence. Learning texts, supersession edges, and existing articles are re-derived server-side from the vault. Pass the scope tool's run_id: the tool reads the in-scope identities from the run, records the themes back to it, and returns a compact summary (theme names, member counts, decision mix). A run whose vault HEAD or scope changed since scope ran is refused — call scope again. The in_scope input is deprecated (kept for one release; returns the full themes) and cannot be combined with run_id.",
}, distill.GroupLearners)
mcp.AddTool(srv, &mcp.Tool{
Name: "rolling_pr",
Description: "Create or update one rolling dewey-distill/<theme> PR per grouped theme: a fresh branch with draft articles and a human-gate PR for new themes, and rebase-preserving-human-commits updates with review-queue bodies and force-with-lease pushes for existing ones. Human edits are never overwritten (the regeneration guard skips them and the PR body lists them), closed PRs are never reopened, and no path writes tier: validated — the server guard rejects it. The durable run artifact is recorded server-side. Pass the run_id group_learners recorded its themes to, plus optional per-theme lint findings; a stale run (vault HEAD or scope changed since scope ran) is refused. The run artifact is written before the first theme and updated after each, so a cancelled or failed call still records the themes it finished (status incomplete). The themes input is deprecated (kept for one release) and cannot be combined with run_id. Pass dry_run: true for the output-only preview — no branch, article, push, PR, or artifact is recorded, each theme reports would_create or would_update.",
}, distill.RollingPR)
return 3
}
// registerHealthTool registers the health check tool that reports server status,
// embedding coverage, and source information.
// Returns the number of tools registered.
func registerHealthTool(srv *mcp.Server, b backend.Backend, readOnly bool, cfg *serverConfig) int {
mcp.AddTool(srv, &mcp.Tool{
Name: "health",
Description: "Check server status: version, backend type, read-only mode, page count. Use to verify the server is alive and see its configuration.",
}, func(ctx context.Context, req *mcp.CallToolRequest, input struct{}) (*mcp.CallToolResult, any, error) {
backendType := "obsidian"
if _, ok := b.(backend.HasDataScript); ok {
backendType = "logseq"
}
pages, _ := b.GetAllPages(ctx)
pingErr := b.Ping(ctx)
status := "ok"
if pingErr != nil {
status = fmt.Sprintf("error: %v", pingErr)
}
result := map[string]any{
"status": status,
"version": version,
"backend": backendType,
"readOnly": readOnly,
"pageCount": len(pages),
}
// Add Dewey-specific fields per contracts/mcp-tools.md.
deweyInfo := map[string]any{}
if cfg.store != nil {
deweyInfo["persistent"] = true
embeddingCount, _ := cfg.store.CountEmbeddings()
blockCount, _ := cfg.store.CountBlocks()
deweyInfo["embeddingCount"] = embeddingCount
var coverage float64
if blockCount > 0 {
coverage = float64(embeddingCount) / float64(blockCount)
}
deweyInfo["embeddingCoverage"] = coverage
// Include per-source status in health response.
storedSources, _ := cfg.store.ListSources()
var sourcesInfo []map[string]any
for _, src := range storedSources {
srcInfo := map[string]any{
"id": src.ID,
"type": src.Type,
"status": src.Status,
}
pc, _ := cfg.store.CountPagesBySource(src.ID)
srcInfo["pageCount"] = pc
if src.LastFetchedAt > 0 {
srcInfo["lastFetched"] = fmt.Sprintf("%d", src.LastFetchedAt)
}
sourcesInfo = append(sourcesInfo, srcInfo)
}
deweyInfo["sources"] = sourcesInfo
} else {
deweyInfo["persistent"] = false
deweyInfo["embeddingCount"] = 0
deweyInfo["embeddingCoverage"] = 0.0
deweyInfo["sources"] = []map[string]any{}
}
if cfg.embedder != nil {
deweyInfo["embeddingModel"] = cfg.embedder.ModelID()
deweyInfo["embeddingAvailable"] = cfg.embedder.Available()
} else {
deweyInfo["embeddingModel"] = ""
deweyInfo["embeddingAvailable"] = false
}
// Report background indexing status when the flag is available (FR-007, D2).
if cfg.indexReady != nil {
deweyInfo["indexing"] = !cfg.indexReady.Load()
}
result["dewey"] = deweyInfo
data, _ := json.MarshalIndent(result, "", " ")
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: string(data)}},
}, nil, nil
})
return 1
}