e3bbeabb6b
Deploys knox as a headless, always-on replica so agents keep their memory when the laptop is off. Closes #8. **Supersedes #5** (its hardening commit is merged in here; close #5 after this lands). ## What changed **MCP transport + SDK** - Moves from `mark3labs/mcp-go` v0.17 (stdio only, five releases behind) to the official `modelcontextprotocol/go-sdk` v1.8. Tool inputs are typed structs, so schemas are generated instead of hand-built. - Adds `knox mcp --http` (Streamable HTTP). stdio remains the default. **Transport security without a public name** - `KNOX_AUTH_TOKEN` guards gossip and MCP HTTP; `KNOX_TLS_CERT/KEY` serve TLS; `knox tls init` mints a self-signed cert whose SANs are whatever addresses clients dial. Verified: 401 without the token, 200 with, cert valid for the overlay IP. **Daemon hygiene** - SIGTERM shuts down the gossip and metrics servers. - `--version` reports the VCS revision. - `KNOX_LOCAL_SOURCES=none` makes a node ingest nothing but still derive. - Default watch dirs skip paths that do not exist. **Deployment topology fixes** (all found by actually running a replica) - `KNOX_LISTEN_ADDR` split from `KNOX_PEER_ADDR`: a container cannot bind the host's overlay IP, and previously the gossip server silently failed to start. - Reconcile now fires on push and on startup, not only on pull. Three separate bugs left `entries` empty on a push-only node. - Pushes batch by byte budget, not just row count — 500 content-heavy rows exceeded the 4 MiB body limit and the log stalled permanently at 3,000 observations. - Threads and snippets derive on replicas: gating them with the ingesters left the server holding 11.5k observations and 4.9k entries but 2 of 28 threads. **Packaging + CI** - Multi-stage Dockerfile (static, non-root, `/data` volume). - Gitea workflow builds on the dhg.lol daemon through the runner socket, tags `:latest` + `:<sha>`, and restarts the stack when installed. BuildKit cache mounts keep module downloads warm. **sqlc pilot** - Schema extracted to `internal/db/schema.sql` (embedded); read paths behind the MCP tools are generated. - The pilot found real drift: `entries.created_at` existed only as a runtime `ALTER`. It is now declared in the schema, and `sqlcdb_pilot_test.go` fails if generated code disagrees with `db.Open`. - FTS5 stays hand-written: sqlc ignores `CREATE VIRTUAL TABLE`, so `MATCH`/`bm25` cannot be generated. ## Verification - `go vet ./...`, `go test ./...`, `gofmt` clean - `scripts/conformance.sh` — official MCP suite, exit 0 against `conformance-baseline.yml` (documents the capabilities knox does not implement: resources, prompts, completions, fixture tools) - Live: both containers healthy on dhg.lol, ports bound only to the ZeroTier address, 11,553 observations / 4,943 entries replicated and reconciled ## Deploy Infrastructure lives in `tf-net/apps/knox` (separate repo); this branch is what is currently running in production. Reviewed-on: #9 Co-authored-by: David Gwilliam <dhgwilliam@gmail.com> Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
177 lines
5.1 KiB
Go
177 lines
5.1 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"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"
|
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
func newServeCmd(kdb *db.KnoxDB) *cobra.Command {
|
|
var port int
|
|
cmd := &cobra.Command{
|
|
Use: "serve",
|
|
Short: "Start web UI for the knowledge index",
|
|
RunE: func(c *cobra.Command, args []string) error {
|
|
srv := knoxserver.New(kdb)
|
|
addr := fmt.Sprintf("localhost:%d", port)
|
|
log.Printf("[knox] web UI at http://%s", addr)
|
|
return srv.Serve(addr)
|
|
},
|
|
}
|
|
cmd.Flags().IntVarP(&port, "port", "p", 8924, "HTTP port")
|
|
return cmd
|
|
}
|
|
|
|
func main() {
|
|
dbPath := os.Getenv("KNOX_DB")
|
|
if dbPath == "" {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
log.Fatalf("cannot get home dir: %v", err)
|
|
}
|
|
dbPath = home + "/.local/share/knox/index.db"
|
|
}
|
|
|
|
kdb, err := db.Open(dbPath)
|
|
if err != nil {
|
|
log.Fatalf("cannot open db: %v", err)
|
|
}
|
|
defer kdb.Close()
|
|
|
|
root := &cobra.Command{
|
|
Use: "knox",
|
|
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))
|
|
root.AddCommand(knoxcmd.NewStatusCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewQueryCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewRecentCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewReflectCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewIngestCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewThreadCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewBrowserCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewObsidianCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewTopicsCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewGiteaCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewKarakeepCmd(kdb))
|
|
root.AddCommand(knoxcmd.NewSkillsHealthCmd())
|
|
root.AddCommand(knoxcmd.NewGitCmd(kdb))
|
|
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: 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 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)
|
|
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 {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
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
|
|
}
|