feat: mcp over http on the official sdk, tls/token transport, docker, sqlc (#8)

MCP moves from mark3labs/mcp-go v0.17 (stdio only, 5 releases behind) to the
official modelcontextprotocol/go-sdk with typed tool inputs, and gains a
Streamable HTTP transport so a remote node can serve agents.

Transport security works without a public DNS name: KNOX_AUTH_TOKEN guards
every endpoint, KNOX_TLS_CERT/KEY serve TLS from a self-signed cert, and
`knox tls init` mints one whose SANs are whatever addresses clients dial.

Daemon hygiene for an always-on host: SIGTERM shutdown of the gossip and
metrics servers, --version reporting the VCS revision, KNOX_LOCAL_SOURCES=none
for a replicate-only node (no ingest tickers, no Obsidian vault adoption), and
default watch dirs that skip paths which do not exist.

Packaging: multi-stage Dockerfile (static, non-root, /data volume).

sqlc pilot: schema moved to internal/db/schema.sql (embedded) and the read
paths behind the MCP tools are now generated. The pilot found real drift —
entries.created_at existed only as a runtime ALTER — so the column is declared
in schema.sql and a parity test fails if generated code disagrees with db.Open.

Conformance: scripts/conformance.sh runs the official suite against a throwaway
node; conformance-baseline.yml records the capabilities knox deliberately does
not implement (resources, prompts, completions, fixture tools).

Refs #8
This commit is contained in:
2026-11-03 23:02:04 -08:00
parent 1f35b7eea4
commit c13ac12d97
8 changed files with 1272 additions and 1247 deletions
+7
View File
@@ -5,6 +5,7 @@ go 1.26
require (
github.com/fsnotify/fsnotify v1.8.0
github.com/mark3labs/mcp-go v0.17.0
github.com/modelcontextprotocol/go-sdk v1.8.0
github.com/prometheus/client_golang v1.24.1
github.com/spf13/cobra v1.9.1
modernc.org/sqlite v1.37.1
@@ -14,6 +15,7 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
@@ -24,10 +26,15 @@ require (
github.com/prometheus/common v0.70.1 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/spf13/pflag v1.0.6 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/time v0.15.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
modernc.org/libc v1.65.7 // indirect
modernc.org/mathutil v1.7.1 // indirect
+16 -2
View File
@@ -9,8 +9,12 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -25,6 +29,8 @@ github.com/mark3labs/mcp-go v0.17.0 h1:5Ps6T7qXr7De/2QTqs9h6BKeZ/qdeUeGrgM5lPzi9
github.com/mark3labs/mcp-go v0.17.0/go.mod h1:KmJndYv7GIgcPVwEKJjNcbhVQ+hJGJhrCCB/9xITzpE=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
@@ -42,6 +48,10 @@ github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIj
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
@@ -58,13 +68,17 @@ golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5Z
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8=
golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU=
golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.33.0 h1:4qz2S3zmRxbGIhDIAgjxvFutSvH5EfnsYrRBj0UI0bc=
golang.org/x/tools v0.33.0/go.mod h1:CIJMaWEY88juyUfo7UbgPqbC8rU2OqfAV1h2Qp0oMYI=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+1024 -1004
View File
File diff suppressed because it is too large Load Diff
+23 -1
View File
@@ -1,10 +1,13 @@
package cmd
import (
"context"
"fmt"
"io"
"log"
"os"
"os/signal"
"syscall"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/watch"
@@ -26,6 +29,16 @@ func NewWatchCmd(kdb *db.KnoxDB) *cobra.Command {
}
log.Printf("[knox] starting watcher, scanning %d directories", len(dirs))
w := watch.New(kdb, dirs)
// A container sends SIGTERM on stop; shut down the HTTP servers so
// restarts are clean instead of dropping the listeners abruptly.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
<-ctx.Done()
w.Shutdown()
}()
if err := w.Start(); err != nil {
// Not log.Fatalf: --quiet redirects the logger to io.Discard,
// so a fatal exit must reach the user on stderr directly.
@@ -41,8 +54,17 @@ func NewWatchCmd(kdb *db.KnoxDB) *cobra.Command {
func defaultWatchDirs() []string {
home, _ := getHomeDir()
return []string{
candidates := []string{
home + "/.local/share/opencode/log",
home + "/.skills",
}
// A headless node has none of these; watch nothing rather than logging a
// failed watch for every missing path.
dirs := make([]string, 0, len(candidates))
for _, d := range candidates {
if info, err := os.Stat(d); err == nil && info.IsDir() {
dirs = append(dirs, d)
}
}
return dirs
}
+11 -215
View File
@@ -1,219 +1,15 @@
package db
const Schema = `
-- IMMUTABLE LOG: every observation is append-only, never mutated
CREATE TABLE IF NOT EXISTS observations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fingerprint TEXT NOT NULL,
source_id TEXT NOT NULL,
source_path TEXT,
project TEXT,
content_type TEXT,
title TEXT,
summary TEXT,
collected_at TEXT NOT NULL DEFAULT (datetime('now')),
created_at TEXT,
line_start INTEGER,
line_end INTEGER,
confidence REAL DEFAULT 0.5,
ingester_version TEXT DEFAULT '1',
trigger TEXT,
provenance TEXT DEFAULT '{}',
content_hash TEXT DEFAULT '',
content TEXT DEFAULT '',
node_id TEXT NOT NULL DEFAULT '',
hcl INTEGER,
received_at TEXT
);
import _ "embed"
CREATE INDEX IF NOT EXISTS idx_obs_fingerprint ON observations(fingerprint);
CREATE INDEX IF NOT EXISTS idx_obs_collected ON observations(collected_at);
CREATE INDEX IF NOT EXISTS idx_obs_created ON observations(created_at);
CREATE INDEX IF NOT EXISTS idx_obs_source ON observations(source_id, source_path);
CREATE INDEX IF NOT EXISTS idx_obs_project ON observations(project);
CREATE INDEX IF NOT EXISTS idx_obs_trigger ON observations(trigger);
// Schema is the DDL for a fresh index: base tables, the FTS5 full-text indexes
// and their sync triggers. It lives in schema.sql so the same text can be fed
// to sqlc for compile-time checked queries.
//
//go:embed schema.sql
var Schema string
-- MATERIALIZED CACHE: current state, reconstructable from observations
CREATE TABLE IF NOT EXISTS entries (
fingerprint TEXT PRIMARY KEY,
source_id TEXT NOT NULL,
source_path TEXT,
project TEXT,
content_type TEXT,
title TEXT,
summary TEXT,
content TEXT DEFAULT '',
first_seen TEXT,
last_seen TEXT,
ref_count INTEGER DEFAULT 1,
last_confidence REAL DEFAULT 0.5
);
CREATE INDEX IF NOT EXISTS idx_entries_project ON entries(project);
CREATE INDEX IF NOT EXISTS idx_entries_source ON entries(source_id);
CREATE INDEX IF NOT EXISTS idx_entries_seen ON entries(last_seen);
-- FULL-TEXT SEARCH: external-content FTS5 over entries, kept in sync by
-- triggers. BM25-ranked; entries_vocab exposes the term list for typo fallback.
CREATE VIRTUAL TABLE IF NOT EXISTS entries_fts USING fts5(title, project, summary, content, content='entries', content_rowid='rowid');
CREATE VIRTUAL TABLE IF NOT EXISTS entries_vocab USING fts5vocab(entries_fts, 'row');
CREATE TRIGGER IF NOT EXISTS entries_ai AFTER INSERT ON entries BEGIN
INSERT INTO entries_fts(rowid, title, project, summary, content) VALUES (new.rowid, new.title, new.project, new.summary, new.content);
END;
CREATE TRIGGER IF NOT EXISTS entries_ad AFTER DELETE ON entries BEGIN
INSERT INTO entries_fts(entries_fts, rowid, title, project, summary, content) VALUES ('delete', old.rowid, old.title, old.project, old.summary, old.content);
END;
CREATE TRIGGER IF NOT EXISTS entries_au AFTER UPDATE ON entries BEGIN
INSERT INTO entries_fts(entries_fts, rowid, title, project, summary, content) VALUES ('delete', old.rowid, old.title, old.project, old.summary, old.content);
INSERT INTO entries_fts(rowid, title, project, summary, content) VALUES (new.rowid, new.title, new.project, new.summary, new.content);
END;
-- PROVENANCE LINKS: multi-hop lineage between entries
CREATE TABLE IF NOT EXISTS provenance_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
descendant_fp TEXT NOT NULL,
ancestor_fp TEXT NOT NULL,
hop_distance INTEGER NOT NULL,
relation TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_pl_descendant ON provenance_links(descendant_fp);
CREATE INDEX IF NOT EXISTS idx_pl_ancestor ON provenance_links(ancestor_fp);
-- REFLECTION STATE: per-session tracking
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
project TEXT,
title TEXT,
status TEXT DEFAULT 'active',
agent_count INTEGER DEFAULT 0,
started_at TEXT,
ended_at TEXT,
last_seen TEXT DEFAULT (datetime('now')),
indexed INTEGER DEFAULT 0
);
-- SOURCE REGISTRY
CREATE TABLE IF NOT EXISTS sources (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
enabled INTEGER DEFAULT 1,
last_event TEXT,
created_at TEXT DEFAULT (datetime('now'))
);
INSERT OR IGNORE INTO sources (id, name) VALUES ('opencode-session', 'Opencode Session Diffs');
INSERT OR IGNORE INTO sources (id, name) VALUES ('opencode-log', 'Opencode Log Files');
INSERT OR IGNORE INTO sources (id, name) VALUES ('git', 'Git History');
INSERT OR IGNORE INTO sources (id, name) VALUES ('filesystem', 'File System Watcher');
-- KNOWLEDGE THREADS: why observations exist, what questions they answer
CREATE TABLE IF NOT EXISTS threads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
motivation TEXT,
status TEXT DEFAULT 'active',
priority TEXT DEFAULT 'medium',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
resolved_at TEXT,
tags TEXT DEFAULT '[]',
provenance TEXT DEFAULT '{}',
cluster_key TEXT,
retained INTEGER DEFAULT 0,
summary TEXT DEFAULT '',
summarized_at TEXT DEFAULT ''
);
-- SETTINGS: key-value store for runtime configuration
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
);
-- PEERS: other knox nodes known to this one (gossip ring)
CREATE TABLE IF NOT EXISTS peers (
peer_id TEXT PRIMARY KEY, -- remote node_id
addr TEXT, -- e.g. http://192.168.1.20:8931
name TEXT,
last_handshake TEXT,
cursor INTEGER DEFAULT 0, -- remote's max_hcl we've seen (knowledge)
created_at TEXT DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_threads_status ON threads(status);
CREATE TABLE IF NOT EXISTS thread_observations (
thread_id INTEGER NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
observation_id INTEGER NOT NULL REFERENCES observations(id) ON DELETE CASCADE,
relevance TEXT,
added_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (thread_id, observation_id)
);
CREATE TABLE IF NOT EXISTS thread_notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
thread_id INTEGER NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
note TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
);
-- TOPICS: TF-IDF clustered groups of related observations
CREATE TABLE IF NOT EXISTS topics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
keywords TEXT,
score REAL DEFAULT 0,
created_at TEXT DEFAULT (datetime('now'))
);
-- SNIPPETS: code lifted from sessions that demonstrably worked. Two-phase by
-- design: the daemon deterministically extracts *candidates* (no LLM) using
-- conservative success signals (tool completed, bash exit 0, not later
-- overwritten), and an agent curates them via the MCP encode/reject tools.
-- status: candidate | encoded | rejected. superseded_by hides dead ends.
CREATE TABLE IF NOT EXISTS snippets (
fingerprint TEXT PRIMARY KEY, -- content hash of code+language
language TEXT DEFAULT '',
code TEXT NOT NULL,
title TEXT DEFAULT '',
description TEXT DEFAULT '',
tags TEXT DEFAULT '[]',
status TEXT DEFAULT 'candidate',
source_session TEXT DEFAULT '',
source_path TEXT DEFAULT '', -- file the snippet touched (edit/write)
source_entry TEXT DEFAULT '', -- session entry fingerprint
project TEXT DEFAULT '',
tool TEXT DEFAULT '', -- edit | write | bash
model TEXT DEFAULT '',
patch_hash TEXT DEFAULT '',
evidence TEXT DEFAULT '{}', -- JSON: why it counts as "worked"
superseded_by TEXT DEFAULT '', -- later full rewrite of the same file
skill_name TEXT DEFAULT '', -- set when encoded into a ~/.skills entry
reject_reason TEXT DEFAULT '',
junk INTEGER DEFAULT 0, -- heuristic: imports/directives/single-line/empty-body stub
kind TEXT DEFAULT 'code', -- code | technique (how you explored/troubleshot)
discovered_at TEXT DEFAULT (datetime('now')),
reviewed_at TEXT DEFAULT '',
encoded_at TEXT DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_snips_status ON snippets(status);
CREATE INDEX IF NOT EXISTS idx_snips_lang ON snippets(language);
CREATE INDEX IF NOT EXISTS idx_snips_project ON snippets(project);
CREATE INDEX IF NOT EXISTS idx_snips_session ON snippets(source_session);
-- FULL-TEXT SEARCH over snippets, kept in sync by triggers (same pattern as entries_fts).
CREATE VIRTUAL TABLE IF NOT EXISTS snippets_fts USING fts5(title, description, code, language, tags, content='snippets', content_rowid='rowid');
CREATE TRIGGER IF NOT EXISTS snippets_ai AFTER INSERT ON snippets BEGIN
INSERT INTO snippets_fts(rowid, title, description, code, language, tags) VALUES (new.rowid, new.title, new.description, new.code, new.language, new.tags);
END;
CREATE TRIGGER IF NOT EXISTS snippets_ad AFTER DELETE ON snippets BEGIN
INSERT INTO snippets_fts(snippets_fts, rowid, title, description, code, language, tags) VALUES ('delete', old.rowid, old.title, old.description, old.code, old.language, old.tags);
END;
CREATE TRIGGER IF NOT EXISTS snippets_au AFTER UPDATE ON snippets BEGIN
INSERT INTO snippets_fts(snippets_fts, rowid, title, description, code, language, tags) VALUES ('delete', old.rowid, old.title, old.description, old.code, old.language, old.tags);
INSERT INTO snippets_fts(rowid, title, description, code, language, tags) VALUES (new.rowid, new.title, new.description, new.code, new.language, new.tags);
END;
`
// Regenerate the checked queries with `go generate ./internal/db`. sqlc reads
// schema.sql, so any column the runtime migrations add must also appear there.
//
//go:generate sqlc generate -f ../../sqlc.yaml
+20 -2
View File
@@ -13,12 +13,14 @@ import (
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/httpauth"
"github.com/david/knox/internal/metrics"
)
@@ -237,7 +239,7 @@ func (c *Client) Push(kdb *db.KnoxDB, peerVector map[string]int64) (int, error)
return 0, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := (&http.Client{Timeout: c.Timeout}).Do(req)
resp, err := httpauth.Client(c.Timeout).Do(req)
if err != nil {
return 0, err
}
@@ -257,7 +259,7 @@ func (c *Client) get(url string, v any) error {
if err != nil {
return err
}
resp, err := (&http.Client{Timeout: c.Timeout}).Do(req)
resp, err := httpauth.Client(c.Timeout).Do(req)
if err != nil {
return err
}
@@ -398,6 +400,22 @@ func vectorMax(v map[string]int64) int64 {
return m
}
// isLoopbackAddr reports whether a listen address is only reachable locally.
// An empty host (":8931") binds every interface and is therefore not loopback.
func isLoopbackAddr(addr string) bool {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return false
}
if host == "" {
return false
}
if ip := net.ParseIP(host); ip != nil {
return ip.IsLoopback()
}
return host == "localhost"
}
// ListenAddr returns the advertised HTTP address (KNOX_PEER_ADDR or default).
func ListenAddr() (addr string) {
if addr = os.Getenv("KNOX_PEER_ADDR"); addr != "" {
+85 -14
View File
@@ -1,6 +1,7 @@
package watch
import (
"context"
"io/fs"
"log"
"net/http"
@@ -12,6 +13,7 @@ import (
"time"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/httpauth"
"github.com/david/knox/internal/ingest"
"github.com/david/knox/internal/metrics"
"github.com/david/knox/internal/skillsrepo"
@@ -45,6 +47,10 @@ type Watcher struct {
fileIngesters []ingest.Ingester
metrics *metrics.Metrics
lastIngest map[string]fileState
gossipSrv *http.Server
metricsSrv *http.Server
quit chan struct{}
quitOnce sync.Once
}
// fileDebouncer schedules one ingest per path a settle-window after the last
@@ -86,8 +92,12 @@ func (d *fileDebouncer) cancel(path string) {
}
func New(kdb *db.KnoxDB, dirs []string) *Watcher {
// Detect Obsidian vault
vault, _ := ingest.DetectObsidianVault()
// Detect Obsidian vault. A gossip-only node has no local sources to read,
// so it must not adopt whatever vault happens to exist on its filesystem.
var vault string
if LocalSourcesEnabled() {
vault, _ = ingest.DetectObsidianVault()
}
return &Watcher{
knoxDB: kdb,
@@ -100,6 +110,25 @@ func New(kdb *db.KnoxDB, dirs []string) *Watcher {
},
metrics: metrics.New(kdb, "knox"),
lastIngest: make(map[string]fileState),
quit: make(chan struct{}),
}
}
// Shutdown asks Start to return after closing the gossip and metrics servers.
// It is safe to call more than once.
func (w *Watcher) Shutdown() {
w.quitOnce.Do(func() { close(w.quit) })
}
// LocalSourcesEnabled reports whether this node ingests local sources
// (opencode sessions, browser history, git, Gitea, Karakeep, Obsidian).
// Set KNOX_LOCAL_SOURCES=none on a node that only replicates peers.
func LocalSourcesEnabled() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("KNOX_LOCAL_SOURCES"))) {
case "none", "0", "false", "off":
return false
default:
return true
}
}
@@ -129,19 +158,37 @@ func (w *Watcher) Start() error {
// seed is still ingesting. Vault/dirs are logged after the seed below.
gossipAddr := ListenAddr()
node := &Node{Kdb: w.knoxDB, Name: "knox", Addr: gossipAddr, Metrics: w.metrics}
srv := &http.Server{Addr: gossipAddr, Handler: node.Handler(), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
srv := &http.Server{
Addr: gossipAddr,
Handler: httpauth.Middleware(node.Handler()),
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
w.gossipSrv = srv
go func() {
log.Printf("[knox] gossip listening on %s", gossipAddr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("[knox] gossip listening on %s (tls=%t auth=%t)", gossipAddr, httpauth.TLSAvailable(), httpauth.Enabled())
if !httpauth.Enabled() && !isLoopbackAddr(gossipAddr) {
log.Printf("[knox] WARNING: %s is reachable beyond this host with no KNOX_AUTH_TOKEN", gossipAddr)
}
if err := httpauth.Serve(srv); err != nil && err != http.ErrServerClosed {
log.Printf("[knox] gossip server: %v", err)
}
}()
// Prometheus scraping on a dedicated port (KNOX_METRICS_ADDR).
metricsAddr := MetricsAddr()
metricsSrv := &http.Server{Addr: metricsAddr, Handler: node.Metrics.Handler(), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
metricsSrv := &http.Server{
Addr: metricsAddr,
Handler: node.Metrics.Handler(),
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
w.metricsSrv = metricsSrv
go func() {
log.Printf("[knox] metrics listening on %s", metricsAddr)
if !isLoopbackAddr(metricsAddr) {
log.Printf("[knox] WARNING: %s exposes metrics unauthenticated; scrape it over a private network", metricsAddr)
}
if err := metricsSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("[knox] metrics server: %v", err)
}
@@ -168,6 +215,18 @@ func (w *Watcher) Start() error {
threadTicker := time.NewTicker(10 * time.Minute)
snippetTicker := time.NewTicker(snippetInterval)
gossipTicker := time.NewTicker(gossipInterval)
// A node that only replicates peers (a server with none of the local
// sources) skips the ingest/derive tickers entirely. Nil channels block
// forever, so the select simply never fires for them.
var browserC, giteaC, gitC, opencodeC, karakeepC, healthC, threadC, snippetC <-chan time.Time
if LocalSourcesEnabled() {
browserC, giteaC, gitC = browserTicker.C, giteaTicker.C, gitTicker.C
opencodeC, karakeepC, healthC = opencodeTicker.C, karakeepTicker.C, healthTicker.C
threadC, snippetC = threadTicker.C, snippetTicker.C
} else {
log.Printf("[knox] KNOX_LOCAL_SOURCES=none: gossip-only mode, local ingest disabled")
}
var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool
var opencodeRunning, karakeepRunning, healthRunning, snippetRunning atomic.Bool
@@ -215,7 +274,7 @@ func (w *Watcher) Start() error {
w.ingestFile(path, trigger)
})
case <-browserTicker.C:
case <-browserC:
if !browserRunning.CompareAndSwap(false, true) {
continue
}
@@ -223,7 +282,7 @@ func (w *Watcher) Start() error {
defer browserRunning.Store(false)
w.ingestBrowserHistory()
}()
case <-giteaTicker.C:
case <-giteaC:
if !giteaRunning.CompareAndSwap(false, true) {
continue
}
@@ -231,7 +290,7 @@ func (w *Watcher) Start() error {
defer giteaRunning.Store(false)
w.ingestGitea()
}()
case <-gitTicker.C:
case <-gitC:
if !gitRunning.CompareAndSwap(false, true) {
continue
}
@@ -239,7 +298,7 @@ func (w *Watcher) Start() error {
defer gitRunning.Store(false)
w.ingestGit()
}()
case <-opencodeTicker.C:
case <-opencodeC:
if !opencodeRunning.CompareAndSwap(false, true) {
continue
}
@@ -247,7 +306,7 @@ func (w *Watcher) Start() error {
defer opencodeRunning.Store(false)
w.ingestOpenCodeDB()
}()
case <-karakeepTicker.C:
case <-karakeepC:
if !karakeepRunning.CompareAndSwap(false, true) {
continue
}
@@ -255,7 +314,7 @@ func (w *Watcher) Start() error {
defer karakeepRunning.Store(false)
w.ingestKarakeep()
}()
case <-healthTicker.C:
case <-healthC:
if !healthRunning.CompareAndSwap(false, true) {
continue
}
@@ -263,7 +322,7 @@ func (w *Watcher) Start() error {
defer healthRunning.Store(false)
w.checkSkillsHealth()
}()
case <-threadTicker.C:
case <-threadC:
if !threadRunning.CompareAndSwap(false, true) {
continue
}
@@ -271,7 +330,7 @@ func (w *Watcher) Start() error {
defer threadRunning.Store(false)
w.autoThread()
}()
case <-snippetTicker.C:
case <-snippetC:
if !snippetRunning.CompareAndSwap(false, true) {
continue
}
@@ -288,6 +347,18 @@ func (w *Watcher) Start() error {
w.syncGossip()
}()
case <-w.quit:
log.Printf("[knox] shutting down")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if w.gossipSrv != nil {
_ = w.gossipSrv.Shutdown(ctx)
}
if w.metricsSrv != nil {
_ = w.metricsSrv.Shutdown(ctx)
}
return nil
case err, ok := <-watcher.Errors:
if !ok {
return nil
+86 -9
View File
@@ -5,12 +5,19 @@ import (
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"runtime/debug"
"strings"
"syscall"
"time"
knoxcmd "github.com/david/knox/internal/cmd"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/httpauth"
knoxserver "github.com/david/knox/internal/server"
mcpServer "github.com/mark3labs/mcp-go/server"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/spf13/cobra"
)
@@ -51,6 +58,7 @@ func main() {
Short: "Knowledge index & session tracker for opencode",
Long: `Knox watches opencode session data, ingests knowledge fingerprints,
and maintains a searchable index. Use 'knox watch' for daemon mode.`,
Version: buildVersion(),
}
root.AddCommand(knoxcmd.NewWatchCmd(kdb))
@@ -70,26 +78,62 @@ and maintains a searchable index. Use 'knox watch' for daemon mode.`,
root.AddCommand(knoxcmd.NewSnippetsCmd(kdb))
root.AddCommand(knoxcmd.NewReconcileCmd(kdb))
root.AddCommand(knoxcmd.NewGossipCmd(kdb))
root.AddCommand(knoxcmd.NewTLSCmd())
root.AddCommand(newServeCmd(kdb))
// MCP server subcommand
// MCP server subcommand: stdio by default (editor/agent spawns it), or
// Streamable HTTP when --http is set (a remote, always-on node).
var mcpHTTP string
mcpCmd := &cobra.Command{
Use: "mcp",
Short: "Start MCP server for opencode integration",
Short: "Start the MCP server over stdio (default) or HTTP",
Long: `Start the Model Context Protocol server.
With no flags the server speaks MCP over stdio, which is how an editor or agent
runs it locally. With --http it serves Streamable HTTP instead, so a remote node
can answer MCP requests over the network; that transport honours KNOX_AUTH_TOKEN
and KNOX_TLS_CERT/KNOX_TLS_KEY like the gossip API does.`,
RunE: func(c *cobra.Command, args []string) error {
s := knoxcmd.NewMCPServer(kdb)
log.Printf("[knox] starting MCP stdio server")
if err := mcpServer.ServeStdio(s); err != nil {
// SIGINT/SIGTERM cancels the server context: clean shutdown,
// not a failure.
if errors.Is(err, context.Canceled) {
return nil
if mcpHTTP == "" {
log.Printf("[knox] starting MCP stdio server")
if err := s.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
// SIGINT/SIGTERM cancels the server context: clean
// shutdown, not a failure.
if errors.Is(err, context.Canceled) {
return nil
}
return err
}
return nil
}
handler := mcp.NewStreamableHTTPHandler(
func(*http.Request) *mcp.Server { return s },
// Stateful sessions keep GET streams and server→client
// notifications working for current clients; the stateless
// 2026-07-28 mode is a stricter subset we do not need.
nil,
)
srv := &http.Server{Addr: mcpHTTP, Handler: httpauth.Middleware(handler)}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(shutdownCtx)
}()
log.Printf("[knox] MCP over HTTP on %s (tls=%t auth=%t)", mcpHTTP, httpauth.TLSAvailable(), httpauth.Enabled())
if err := httpauth.Serve(srv); err != nil && err != http.ErrServerClosed {
return err
}
return nil
},
}
mcpCmd.Flags().StringVar(&mcpHTTP, "http", "", "Serve Streamable HTTP on this address instead of stdio (e.g. 0.0.0.0:8930)")
root.AddCommand(mcpCmd)
if err := root.Execute(); err != nil {
@@ -97,3 +141,36 @@ and maintains a searchable index. Use 'knox watch' for daemon mode.`,
os.Exit(1)
}
}
// buildVersion reports the module version plus the VCS revision the Go
// toolchain baked in, so a container image can be traced back to a commit.
func buildVersion() string {
info, ok := debug.ReadBuildInfo()
if !ok {
return "dev"
}
version := info.Main.Version
if version == "" || version == "(devel)" {
version = "dev"
}
rev, dirty := "", false
for _, s := range info.Settings {
switch s.Key {
case "vcs.revision":
rev = s.Value
case "vcs.modified":
dirty = s.Value == "true"
}
}
if rev != "" {
if len(rev) > 12 {
rev = rev[:12]
}
version += " (" + rev + ")"
// Main.Version already carries a +dirty suffix for a dirty tree.
if dirty && !strings.Contains(version, "dirty") {
version += "+dirty"
}
}
return version
}