Files
knox/main.go
david c13ac12d97 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
2026-11-04 18:13:21 -08:00

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
}