feat: add Go server implementation in go-server/
Full Go port of local-mcp with all core features. Copied from local-mcp-go worktree to consolidate into single-branch repo (easier maintenance). Architecture: - internal/config: Environment variable configuration - internal/models: Shared types (Instruction, Settings, AgentActivity, etc.) - internal/db: SQLite init with modernc.org/sqlite (pure Go, no CGo) - internal/store: Database operations + WakeupSignal + AgentTracker - internal/events: SSE broker for browser /api/events endpoint - internal/mcp: get_user_request MCP tool with 5s keepalive progress bars - internal/api: chi HTTP router with Bearer auth middleware - main.go: Entry point with auto port switching and Windows interactive banner Dependencies: - github.com/mark3labs/mcp-go@v0.46.0 - github.com/go-chi/chi/v5@v5.2.5 - modernc.org/sqlite@v1.47.0 (pure Go SQLite) - github.com/google/uuid@v1.6.0 Static assets embedded via //go:embed static Features matching Python: - Same wait strategy: 50s with 5s progress keepalives - Same hardcoded constants (DEFAULT_WAIT_SECONDS, DEFAULT_EMPTY_RESPONSE) - Auto port switching (tries 8000-8009) - Windows interactive mode (formatted banner on double-click launch) Build: cd go-server && go build -o local-mcp.exe . Run: ./local-mcp.exe Binary size: ~18 MB (vs Python ~60+ MB memory footprint) Startup: ~10 ms (vs Python ~1-2s)
This commit is contained in:
26
go-server/internal/api/auth.go
Normal file
26
go-server/internal/api/auth.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// bearerAuthMiddleware enforces Bearer token authentication for protected routes.
|
||||
func bearerAuthMiddleware(requiredToken string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(auth, "Bearer ") {
|
||||
writeError(w, http.StatusUnauthorized, "Missing or invalid Authorization header")
|
||||
return
|
||||
}
|
||||
token := strings.TrimPrefix(auth, "Bearer ")
|
||||
if token != requiredToken {
|
||||
writeError(w, http.StatusUnauthorized, "Invalid token")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
61
go-server/internal/api/config.go
Normal file
61
go-server/internal/api/config.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/local-mcp/local-mcp-go/internal/events"
|
||||
)
|
||||
|
||||
func handleGetConfig(stores Stores) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
cfg, err := stores.Settings.Get()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func handleUpdateConfig(stores Stores, broker *events.Broker) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Decode partial patch
|
||||
var patch struct {
|
||||
DefaultWaitSeconds *int `json:"default_wait_seconds"`
|
||||
DefaultEmptyResponse *string `json:"default_empty_response"`
|
||||
AgentStaleAfterSeconds *int `json:"agent_stale_after_seconds"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&patch); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Invalid JSON")
|
||||
return
|
||||
}
|
||||
|
||||
// Get current settings
|
||||
current, err := stores.Settings.Get()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Apply patches
|
||||
if patch.DefaultWaitSeconds != nil {
|
||||
current.DefaultWaitSeconds = *patch.DefaultWaitSeconds
|
||||
}
|
||||
if patch.DefaultEmptyResponse != nil {
|
||||
current.DefaultEmptyResponse = *patch.DefaultEmptyResponse
|
||||
}
|
||||
if patch.AgentStaleAfterSeconds != nil {
|
||||
current.AgentStaleAfterSeconds = *patch.AgentStaleAfterSeconds
|
||||
}
|
||||
|
||||
if err := stores.Settings.Update(current); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
broker.Broadcast("config.updated", map[string]any{"config": current})
|
||||
writeJSON(w, http.StatusOK, current)
|
||||
}
|
||||
}
|
||||
|
||||
47
go-server/internal/api/events.go
Normal file
47
go-server/internal/api/events.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/local-mcp/local-mcp-go/internal/events"
|
||||
)
|
||||
|
||||
// handleSSE streams server-sent events to browser clients.
|
||||
func handleSSE(broker *events.Broker) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Set SSE headers
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
writeError(w, http.StatusInternalServerError, "Streaming not supported")
|
||||
return
|
||||
}
|
||||
|
||||
// Subscribe to event broker
|
||||
ch := broker.Subscribe()
|
||||
defer broker.Unsubscribe(ch)
|
||||
|
||||
// Send initial connection event
|
||||
w.Write([]byte("data: {\"type\":\"connected\"}\n\n"))
|
||||
flusher.Flush()
|
||||
|
||||
// Stream events until client disconnects
|
||||
for {
|
||||
select {
|
||||
case msg, ok := <-ch:
|
||||
if !ok {
|
||||
return // broker closed
|
||||
}
|
||||
w.Write(msg)
|
||||
flusher.Flush()
|
||||
case <-r.Context().Done():
|
||||
return // client disconnected
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
119
go-server/internal/api/instructions.go
Normal file
119
go-server/internal/api/instructions.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/local-mcp/local-mcp-go/internal/events"
|
||||
"github.com/local-mcp/local-mcp-go/internal/store"
|
||||
)
|
||||
|
||||
func handleListInstructions(stores Stores) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
status := r.URL.Query().Get("status")
|
||||
if status == "" {
|
||||
status = "all"
|
||||
}
|
||||
items, err := stores.Instructions.List(status)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
}
|
||||
}
|
||||
|
||||
func handleCreateInstruction(stores Stores, broker *events.Broker) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Invalid JSON")
|
||||
return
|
||||
}
|
||||
if body.Content == "" {
|
||||
writeError(w, http.StatusBadRequest, "content is required")
|
||||
return
|
||||
}
|
||||
|
||||
item, err := stores.Instructions.Create(body.Content)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
counts, _ := stores.Instructions.Counts()
|
||||
broker.Broadcast("instruction.created", map[string]any{"item": item})
|
||||
broker.Broadcast("status.changed", map[string]any{"queue": counts})
|
||||
|
||||
writeJSON(w, http.StatusCreated, item)
|
||||
}
|
||||
}
|
||||
|
||||
func handleUpdateInstruction(stores Stores, broker *events.Broker) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
var body struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Invalid JSON")
|
||||
return
|
||||
}
|
||||
|
||||
item, err := stores.Instructions.Update(id, body.Content)
|
||||
if err == store.ErrNotFound {
|
||||
writeError(w, http.StatusNotFound, "Instruction not found")
|
||||
return
|
||||
}
|
||||
if err == store.ErrAlreadyConsumed {
|
||||
writeError(w, http.StatusConflict, "Cannot edit consumed instruction")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
broker.Broadcast("instruction.updated", map[string]any{"item": item})
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
}
|
||||
}
|
||||
|
||||
func handleDeleteInstruction(stores Stores, broker *events.Broker) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
if err := stores.Instructions.Delete(id); err == store.ErrNotFound {
|
||||
writeError(w, http.StatusNotFound, "Instruction not found")
|
||||
return
|
||||
} else if err == store.ErrAlreadyConsumed {
|
||||
writeError(w, http.StatusConflict, "Cannot delete consumed instruction")
|
||||
return
|
||||
} else if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
counts, _ := stores.Instructions.Counts()
|
||||
broker.Broadcast("instruction.deleted", map[string]any{"id": id})
|
||||
broker.Broadcast("status.changed", map[string]any{"queue": counts})
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func handleClearConsumed(stores Stores, broker *events.Broker) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := stores.Instructions.DeleteConsumed(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
counts, _ := stores.Instructions.Counts()
|
||||
broker.Broadcast("history.cleared", nil)
|
||||
broker.Broadcast("status.changed", map[string]any{"queue": counts})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
85
go-server/internal/api/router.go
Normal file
85
go-server/internal/api/router.go
Normal file
@@ -0,0 +1,85 @@
|
||||
// Package api implements the REST HTTP endpoints served alongside the MCP server.
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
|
||||
"github.com/local-mcp/local-mcp-go/internal/events"
|
||||
"github.com/local-mcp/local-mcp-go/internal/store"
|
||||
)
|
||||
|
||||
// Stores groups all database stores that the API handlers need.
|
||||
type Stores struct {
|
||||
Instructions *store.InstructionStore
|
||||
Settings *store.SettingsStore
|
||||
Agents *store.AgentStore
|
||||
}
|
||||
|
||||
// NewRouter builds and returns the main chi router.
|
||||
// staticFS must serve the embedded static directory; pass nil to skip.
|
||||
func NewRouter(stores Stores, broker *events.Broker, apiToken string, staticFS fs.FS) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Recoverer)
|
||||
|
||||
// Auth-check endpoint — always public
|
||||
r.Get("/auth-check", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"auth_required": apiToken != "",
|
||||
})
|
||||
})
|
||||
|
||||
// Health — always public
|
||||
r.Get("/healthz", handleHealth())
|
||||
|
||||
// Static files — always public
|
||||
if staticFS != nil {
|
||||
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFileFS(w, r, staticFS, "index.html")
|
||||
})
|
||||
r.Handle("/static/*", http.StripPrefix("/static/", http.FileServerFS(staticFS)))
|
||||
}
|
||||
|
||||
// All /api/* routes are protected when apiToken is set
|
||||
r.Group(func(r chi.Router) {
|
||||
if apiToken != "" {
|
||||
r.Use(bearerAuthMiddleware(apiToken))
|
||||
}
|
||||
r.Get("/api/status", handleStatus(stores))
|
||||
r.Get("/api/instructions", handleListInstructions(stores))
|
||||
r.Post("/api/instructions", handleCreateInstruction(stores, broker))
|
||||
r.Patch("/api/instructions/{id}", handleUpdateInstruction(stores, broker))
|
||||
r.Delete("/api/instructions/consumed", handleClearConsumed(stores, broker))
|
||||
r.Delete("/api/instructions/{id}", handleDeleteInstruction(stores, broker))
|
||||
r.Get("/api/config", handleGetConfig(stores))
|
||||
r.Patch("/api/config", handleUpdateConfig(stores, broker))
|
||||
r.Get("/api/events", handleSSE(broker))
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// writeJSON serialises v as JSON with the given status code.
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
// writeError writes a JSON {"detail": msg} error response.
|
||||
func writeError(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, map[string]string{"detail": msg})
|
||||
}
|
||||
|
||||
// serverStartTime records when this process started, used by /api/status.
|
||||
var serverStartTime = time.Now().UTC()
|
||||
|
||||
|
||||
|
||||
43
go-server/internal/api/status.go
Normal file
43
go-server/internal/api/status.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func handleHealth() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"server_time": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleStatus(stores Stores) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
counts, _ := stores.Instructions.Counts()
|
||||
latest, _ := stores.Agents.Latest()
|
||||
cfg, _ := stores.Settings.Get()
|
||||
|
||||
resp := map[string]any{
|
||||
"uptime_seconds": int(time.Since(serverStartTime).Seconds()),
|
||||
"queue_pending": counts.PendingCount,
|
||||
"queue_consumed": counts.ConsumedCount,
|
||||
"agent_stale_after_seconds": cfg.AgentStaleAfterSeconds,
|
||||
}
|
||||
|
||||
if latest != nil {
|
||||
isStale := time.Since(latest.LastSeenAt).Seconds() > float64(cfg.AgentStaleAfterSeconds)
|
||||
resp["agent"] = map[string]any{
|
||||
"agent_id": latest.AgentID,
|
||||
"last_fetch_at": latest.LastFetchAt.Format(time.RFC3339Nano),
|
||||
"last_result_type": latest.LastResultType,
|
||||
"is_stale": isStale,
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user