The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
add mcp support
Justin D'Souza9403cd566cf0
diff --git a/cli/beacon/cmd/mcp.go b/cli/beacon/cmd/mcp.gonew file mode 100644index 00000000..73c1543f--- /dev/null+++ b/cli/beacon/cmd/mcp.go@@ -0,0 +1,175 @@+package cmd++import (+ "fmt"+ "net"+ "net/http"+ "os"+ "strings"+ "time"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/activity"+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/mcpserver"+)++const defaultMCPHTTPAddr = "127.0.0.1:8766"++var mcpOpts struct {+ userMode bool+ systemMode bool+ logPath string+ transport string+ addr string+}++var mcpCmd = &cobra.Command{+ Use: "mcp",+ Short: "Expose local Beacon activity through MCP",+}++var mcpServeCmd = &cobra.Command{+ Use: "serve",+ Short: "Run the local Beacon MCP server",+ SilenceUsage: true,+ RunE: runMCPServe,+}++var mcpDoctorCmd = &cobra.Command{+ Use: "doctor",+ Short: "Validate local Beacon MCP setup",+ SilenceUsage: true,+ RunE: runMCPDoctor,+}++func init() {+ rootCmd.AddCommand(mcpCmd)+ mcpCmd.AddCommand(mcpServeCmd)+ mcpCmd.AddCommand(mcpDoctorCmd)+ for _, c := range []*cobra.Command{mcpServeCmd, mcpDoctorCmd} {+ c.Flags().BoolVar(&mcpOpts.userMode, "user", true, "Use per-user endpoint paths")+ c.Flags().BoolVar(&mcpOpts.systemMode, "system", false, "Use system endpoint paths")+ c.Flags().StringVar(&mcpOpts.logPath, "log-path", "", "Runtime JSONL log path")+ c.Flags().StringVar(&mcpOpts.transport, "transport", mcpserver.TransportStdio, "MCP transport: stdio or http")+ c.Flags().StringVar(&mcpOpts.addr, "addr", defaultMCPHTTPAddr, "Loopback HTTP listen address for --transport http")+ }+}++func runMCPServe(cmd *cobra.Command, args []string) error {+ if err := mcpserver.ValidateTransport(mcpOpts.transport); err != nil {+ return err+ }+ runtimeLog := resolveMCPRuntimeLog()+ server := mcpserver.New(mcpserver.Options{LogPath: runtimeLog.EffectiveLogPath, Stderr: os.Stderr})+ switch normalizedTransport() {+ case mcpserver.TransportStdio:+ return server.ServeStdio(cmd.Context(), os.Stdin, os.Stdout)+ case mcpserver.TransportHTTP:+ if err := dashboard.ValidateLoopbackAddr(mcpOpts.addr); err != nil {+ return err+ }+ fmt.Fprintf(os.Stderr, "Beacon MCP server: http://%s/mcp\n", mcpOpts.addr)+ fmt.Fprintf(os.Stderr, "Runtime log: %s\n", runtimeLog.EffectiveLogPath)+ httpServer := &http.Server{+ Addr: mcpOpts.addr,+ Handler: server.HTTPHandler(),+ ReadHeaderTimeout: 5 * time.Second,+ }+ return httpServer.ListenAndServe()+ default:+ return fmt.Errorf("unsupported transport %q", mcpOpts.transport)+ }+}++func runMCPDoctor(cmd *cobra.Command, args []string) error {+ if err := mcpserver.ValidateTransport(mcpOpts.transport); err != nil {+ return err+ }+ runtimeLog := resolveMCPRuntimeLog()+ cfg := loadMCPConfig(runtimeLog.EffectiveUserMode, runtimeLog.EffectiveLogPath)+ fmt.Println("Beacon MCP doctor")+ fmt.Println()+ fmt.Printf("Transport: %s\n", normalizedTransport())+ if normalizedTransport() == mcpserver.TransportHTTP {+ if err := dashboard.ValidateLoopbackAddr(mcpOpts.addr); err != nil {+ return err+ }+ fmt.Printf("HTTP address: %s\n", mcpOpts.addr)+ if err := checkCanListen(mcpOpts.addr); err != nil {+ return err+ }+ fmt.Println("HTTP bind check: ok")+ }+ fmt.Printf("Runtime log: %s\n", runtimeLog.EffectiveLogPath)+ fmt.Printf("Runtime log source: %s\n", runtimeLog.Reason)+ if runtimeLog.Warning != "" {+ fmt.Printf("Runtime log warning: %s\n", runtimeLog.Warning)+ }+ fmt.Printf("Content retention: %s\n", cfg.ContentRetention)+ sampled, malformed, archives, err := activity.InspectLog(runtimeLog.EffectiveLogPath)+ if err != nil {+ return err+ }+ fmt.Printf("Sampled events: %d\n", sampled)+ fmt.Printf("Malformed lines: %d\n", malformed)+ fmt.Printf("Readable archives: %d\n", len(archives))+ server := mcpserver.New(mcpserver.Options{LogPath: runtimeLog.EffectiveLogPath, Stderr: os.Stderr})+ if err := server.HasExpectedTools(); err != nil {+ return err+ }+ fmt.Printf("MCP tools: %s\n", strings.Join(server.ToolNames(), ", "))+ if normalizedTransport() == mcpserver.TransportStdio {+ fmt.Println()+ fmt.Println("MCP client config:")+ fmt.Println(`{`)+ fmt.Println(` "mcpServers": {`)+ fmt.Println(` "beacon": {`)+ fmt.Println(` "command": "beacon",`)+ fmt.Println(` "args": ["mcp", "serve", "--transport", "stdio"]`)+ fmt.Println(` }`)+ fmt.Println(` }`)+ fmt.Println(`}`)+ }+ return nil+}++func resolveMCPRuntimeLog() lifecycle.RuntimeLogSource {+ return lifecycle.ResolveRuntimeLog(mcpUserMode(), mcpOpts.logPath)+}++func loadMCPConfig(userMode bool, logPath string) endpointconfig.Config {+ if cfg, err := endpointconfig.Load(userMode); err == nil {+ if logPath != "" {+ cfg.LogPath = logPath+ }+ return cfg+ }+ if logPath == "" {+ logPath = writer.DefaultPath(userMode)+ }+ return endpointconfig.Default(userMode, logPath)+}++func mcpUserMode() bool {+ return mcpOpts.userMode && !mcpOpts.systemMode+}++func normalizedTransport() string {+ if mcpOpts.transport == "" {+ return mcpserver.TransportStdio+ }+ return mcpOpts.transport+}++func checkCanListen(addr string) error {+ listener, err := net.Listen("tcp", addr)+ if err != nil {+ return fmt.Errorf("HTTP bind check failed for %s: %w", addr, err)+ }+ return listener.Close()+}diff --git a/cli/beacon/cmd/mcp_test.go b/cli/beacon/cmd/mcp_test.gonew file mode 100644index 00000000..315ff858--- /dev/null+++ b/cli/beacon/cmd/mcp_test.go@@ -0,0 +1,40 @@+package cmd++import "testing"++func TestMCPCommandsRegistered(t *testing.T) {+ cmd, _, err := rootCmd.Find([]string{"mcp", "serve"})+ if err != nil {+ t.Fatalf("Find mcp serve returned error: %v", err)+ }+ if cmd == nil || cmd.Use != "serve" {+ t.Fatalf("mcp serve command not registered: %#v", cmd)+ }+ for _, name := range []string{"transport", "addr", "user", "system", "log-path"} {+ if cmd.Flags().Lookup(name) == nil {+ t.Fatalf("mcp serve missing --%s flag", name)+ }+ }++ doctor, _, err := rootCmd.Find([]string{"mcp", "doctor"})+ if err != nil {+ t.Fatalf("Find mcp doctor returned error: %v", err)+ }+ if doctor == nil || doctor.Use != "doctor" {+ t.Fatalf("mcp doctor command not registered: %#v", doctor)+ }+}++func TestMCPDoctorRejectsNonLoopbackHTTP(t *testing.T) {+ oldTransport := mcpOpts.transport+ oldAddr := mcpOpts.addr+ t.Cleanup(func() {+ mcpOpts.transport = oldTransport+ mcpOpts.addr = oldAddr+ })+ mcpOpts.transport = "http"+ mcpOpts.addr = "0.0.0.0:8766"+ if err := runMCPDoctor(mcpDoctorCmd, nil); err == nil {+ t.Fatal("runMCPDoctor accepted non-loopback HTTP address")+ }+}diff --git a/cli/beacon/internal/endpoint/activity/activity.go b/cli/beacon/internal/endpoint/activity/activity.gonew file mode 100644index 00000000..dfbb410d--- /dev/null+++ b/cli/beacon/internal/endpoint/activity/activity.go@@ -0,0 +1,401 @@+package activity++import (+ "fmt"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++const DefaultLimit = 100++type Query struct {+ LogPath string+ Limit int+ Since time.Time+ Until time.Time+ Q string+ Harness string+ Model string+ Action string+ Severity string+ Category string+ Repository string+ Session string+ File string+ Command string+ MCP string+ Approval string+ Decision string+ Policy string+ Review string+ WazuhLevel string+}++type ResultMeta struct {+ TotalMatched int `json:"total_matched"`+ MalformedLines int `json:"malformed_lines"`+ Limit int `json:"limit"`+ Returned int `json:"returned"`+ Truncated bool `json:"truncated"`+ Query string `json:"query,omitempty"`+ Filters map[string]string `json:"filters,omitempty"`+ Caveats []string `json:"caveats,omitempty"`+}++type SearchResult struct {+ Meta ResultMeta `json:"meta"`+ Events []EventSummary `json:"events"`+}++type SummaryResult struct {+ Meta ResultMeta `json:"meta"`+ Summary dashboard.Summary `json:"summary"`+}++type EventResult struct {+ Found bool `json:"found"`+ Event *EventSummary `json:"event,omitempty"`+}++type FilterValuesResult struct {+ Meta ResultMeta `json:"meta"`+ Filters map[string][]ValueCount `json:"filters"`+}++type ValueCount struct {+ Value string `json:"value"`+ Count int `json:"count"`+}++type EventSummary struct {+ ID string `json:"id"`+ Timestamp string `json:"timestamp"`+ Harness string `json:"harness,omitempty"`+ Action string `json:"action,omitempty"`+ Category string `json:"category,omitempty"`+ Severity string `json:"severity,omitempty"`+ Message string `json:"message,omitempty"`+ Session *SessionSummary `json:"session,omitempty"`+ Tool *ToolSummary `json:"tool,omitempty"`+ File *FileSummary `json:"file,omitempty"`+ Command *CommandSummary `json:"command,omitempty"`+ MCP *MCPSummary `json:"mcp,omitempty"`+ Approval *ApprovalSummary `json:"approval,omitempty"`+ Policy *PolicySummary `json:"policy,omitempty"`+ Content *ContentSummary `json:"content,omitempty"`+ Model string `json:"model,omitempty"`+ Repository string `json:"repository,omitempty"`+ Branch string `json:"branch,omitempty"`+ WazuhLevel int `json:"wazuh_level,omitempty"`+ Caveats []string `json:"caveats,omitempty"`+}++type SessionSummary struct {+ ID string `json:"id,omitempty"`+ WorkingDirectory string `json:"working_directory,omitempty"`+}++type ToolSummary struct {+ Name string `json:"name,omitempty"`+ Command string `json:"command,omitempty"`+ Path string `json:"path,omitempty"`+}++type FileSummary struct {+ Path string `json:"path,omitempty"`+ Operation string `json:"operation,omitempty"`+ Language string `json:"language,omitempty"`+ DiffHash string `json:"diff_hash,omitempty"`+ DiffBytes int `json:"diff_bytes,omitempty"`+}++type CommandSummary struct {+ Command string `json:"command,omitempty"`+ ExitCode *int `json:"exit_code,omitempty"`+ DurationMS int64 `json:"duration_ms,omitempty"`+}++type MCPSummary struct {+ Server string `json:"server,omitempty"`+ Tool string `json:"tool,omitempty"`+}++type ApprovalSummary struct {+ Required bool `json:"required,omitempty"`+ Decision string `json:"decision,omitempty"`+ Reason string `json:"reason,omitempty"`+}++type PolicySummary struct {+ ID string `json:"id,omitempty"`+ Name string `json:"name,omitempty"`+ Decision string `json:"decision,omitempty"`+ Enforcement string `json:"enforcement,omitempty"`+ Reason string `json:"reason,omitempty"`+}++type ContentSummary struct {+ Retention string `json:"retention,omitempty"`+ Included bool `json:"included"`+ Redacted bool `json:"redacted,omitempty"`+ Truncated bool `json:"truncated,omitempty"`+ FieldTruncated bool `json:"field_truncated,omitempty"`+}++func Search(query Query) (SearchResult, error) {+ result, err := read(query)+ if err != nil {+ return SearchResult{}, err+ }+ events := make([]EventSummary, 0, len(result.Events))+ for _, record := range result.Events {+ events = append(events, summarizeRecord(record))+ }+ return SearchResult{Meta: metaFromResult(result), Events: events}, nil+}++func Summarize(query Query) (SummaryResult, error) {+ result, err := read(query)+ if err != nil {+ return SummaryResult{}, err+ }+ return SummaryResult{Meta: metaFromResult(result), Summary: dashboard.BuildSummary(result)}, nil+}++func GetEvent(logPath, id string) (EventResult, error) {+ record, ok, err := dashboard.FindEvent(logPath, id)+ if err != nil {+ return EventResult{}, err+ }+ if !ok {+ return EventResult{Found: false}, nil+ }+ event := summarizeRecord(record)+ return EventResult{Found: true, Event: &event}, nil+}++func ListFilters(query Query) (FilterValuesResult, error) {+ if query.Limit == 0 {+ query.Limit = 2000+ }+ result, err := read(query)+ if err != nil {+ return FilterValuesResult{}, err+ }+ counts := map[string]map[string]int{+ "actions": {},+ "categories": {},+ "harnesses": {},+ "models": {},+ "repositories": {},+ "sessions": {},+ "mcp_servers": {},+ "mcp_tools": {},+ "commands": {},+ "files": {},+ }+ for _, record := range result.Events {+ event := record.Event+ add(counts["actions"], event.Event.Action)+ add(counts["categories"], event.Event.Category)+ add(counts["harnesses"], event.Harness.Name)+ add(counts["models"], event.Model)+ add(counts["repositories"], event.Repository)+ if event.Session != nil {+ add(counts["sessions"], event.Session.ID)+ }+ if event.MCP != nil {+ add(counts["mcp_servers"], event.MCP.Server)+ add(counts["mcp_tools"], event.MCP.Tool)+ }+ if event.Command != nil {+ add(counts["commands"], event.Command.Command)+ }+ if event.Tool != nil {+ add(counts["commands"], event.Tool.Command)+ }+ if event.File != nil {+ add(counts["files"], event.File.Path)+ }+ }+ filters := make(map[string][]ValueCount, len(counts))+ for name, values := range counts {+ filters[name] = topValues(values, 20)+ }+ return FilterValuesResult{Meta: metaFromResult(result), Filters: filters}, nil+}++func InspectLog(logPath string) (sampledEvents, malformedLines int, archives []string, err error) {+ result, err := read(Query{LogPath: logPath, Limit: 25})+ if err != nil {+ return 0, 0, nil, err+ }+ dir := filepath.Dir(logPath)+ base := filepath.Base(logPath)+ entries, readErr := os.ReadDir(dir)+ if readErr != nil && !os.IsNotExist(readErr) {+ return 0, 0, nil, readErr+ }+ prefix := base + "."+ for _, entry := range entries {+ if strings.HasPrefix(entry.Name(), prefix) {+ archives = append(archives, filepath.Join(dir, entry.Name()))+ }+ }+ sort.Strings(archives)+ return len(result.Events), result.MalformedLines, archives, nil+}++func read(query Query) (dashboard.EventResult, error) {+ if query.LogPath == "" {+ return dashboard.EventResult{}, fmt.Errorf("runtime log path is required")+ }+ return dashboard.ReadEvents(query.LogPath, dashboard.EventQuery{+ Limit: limitOrDefault(query.Limit),+ Since: query.Since,+ Until: query.Until,+ Q: query.Q,+ Harness: query.Harness,+ Model: query.Model,+ Action: query.Action,+ Severity: query.Severity,+ Category: query.Category,+ Repository: query.Repository,+ Session: query.Session,+ File: query.File,+ Command: query.Command,+ MCP: query.MCP,+ Approval: query.Approval,+ Decision: query.Decision,+ Policy: query.Policy,+ Review: query.Review,+ WazuhLevel: query.WazuhLevel,+ })+}++func limitOrDefault(limit int) int {+ if limit == 0 {+ return DefaultLimit+ }+ return limit+}++func metaFromResult(result dashboard.EventResult) ResultMeta {+ meta := ResultMeta{+ TotalMatched: result.TotalMatched,+ MalformedLines: result.MalformedLines,+ Limit: result.Limit,+ Returned: result.Returned,+ Truncated: result.Truncated,+ Query: result.Query,+ Filters: result.Filters,+ }+ if result.Truncated {+ meta.Caveats = append(meta.Caveats, "result set truncated by limit")+ }+ if result.MalformedLines > 0 {+ meta.Caveats = append(meta.Caveats, "one or more malformed log lines were skipped")+ }+ return meta+}++func summarizeRecord(record dashboard.EventRecord) EventSummary {+ event := record.Event+ summary := EventSummary{+ ID: record.ID,+ Timestamp: event.Timestamp,+ Harness: event.Harness.Name,+ Action: event.Event.Action,+ Category: event.Event.Category,+ Severity: string(event.Severity),+ Message: event.Message,+ Model: event.Model,+ Repository: event.Repository,+ Branch: event.Branch,+ WazuhLevel: record.WazuhLevel,+ }+ if event.Session != nil {+ summary.Session = &SessionSummary{ID: event.Session.ID, WorkingDirectory: event.Session.WorkingDirectory}+ }+ if event.Tool != nil {+ summary.Tool = &ToolSummary{Name: event.Tool.Name, Command: event.Tool.Command, Path: event.Tool.Path}+ }+ if event.File != nil {+ summary.File = &FileSummary{Path: event.File.Path, Operation: event.File.Operation, Language: event.File.Language, DiffHash: event.File.DiffHash, DiffBytes: event.File.DiffBytes}+ }+ if event.Command != nil {+ summary.Command = &CommandSummary{Command: event.Command.Command, ExitCode: event.Command.ExitCode, DurationMS: event.Command.DurationMS}+ }+ if event.MCP != nil {+ summary.MCP = &MCPSummary{Server: event.MCP.Server, Tool: event.MCP.Tool}+ }+ if event.Approval != nil {+ summary.Approval = &ApprovalSummary{Required: event.Approval.Required, Decision: event.Approval.Decision, Reason: event.Approval.Reason}+ }+ if event.Policy != nil {+ summary.Policy = &PolicySummary{ID: event.Policy.ID, Name: event.Policy.Name, Decision: event.Policy.Decision, Enforcement: event.Policy.Enforcement, Reason: event.Policy.Reason}+ }+ if event.Content != nil || event.Truncated {+ summary.Content = contentSummary(event.Content, event.Truncated)+ summary.Caveats = append(summary.Caveats, contentCaveats(summary.Content)...)+ }+ return summary+}++func contentSummary(content *schema.ContentInfo, fieldTruncated bool) *ContentSummary {+ summary := &ContentSummary{FieldTruncated: fieldTruncated}+ if content != nil {+ summary.Retention = content.Retention+ summary.Included = content.Included+ summary.Redacted = content.Redacted+ summary.Truncated = content.Truncated+ }+ return summary+}++func contentCaveats(content *ContentSummary) []string {+ if content == nil {+ return nil+ }+ var caveats []string+ if content.Retention == schema.ContentRetentionMetadata {+ caveats = append(caveats, "content retention is metadata; prompt/tool details may be omitted")+ }+ if content.Redacted {+ caveats = append(caveats, "content was redacted")+ }+ if content.Truncated || content.FieldTruncated {+ caveats = append(caveats, "content was truncated")+ }+ return caveats+}++func add(counts map[string]int, value string) {+ value = strings.TrimSpace(value)+ if value != "" {+ counts[value]+++ }+}++func topValues(counts map[string]int, limit int) []ValueCount {+ values := make([]ValueCount, 0, len(counts))+ for value, count := range counts {+ values = append(values, ValueCount{Value: value, Count: count})+ }+ sort.Slice(values, func(i, j int) bool {+ if values[i].Count == values[j].Count {+ return values[i].Value < values[j].Value+ }+ return values[i].Count > values[j].Count+ })+ if len(values) > limit {+ values = values[:limit]+ }+ return values+}diff --git a/cli/beacon/internal/endpoint/activity/activity_test.go b/cli/beacon/internal/endpoint/activity/activity_test.gonew file mode 100644index 00000000..7a8a5b49--- /dev/null+++ b/cli/beacon/internal/endpoint/activity/activity_test.go@@ -0,0 +1,122 @@+package activity++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++func TestSearchReturnsCompactRetentionAwareDTOs(t *testing.T) {+ path := filepath.Join(t.TempDir(), "runtime.jsonl")+ event := testEvent("2026-05-13T01:00:00Z", "claude", "prompt.submitted", "prompt")+ event.Prompt = &schema.PromptInfo{Text: "summarize local MCP use"}+ event.Content = &schema.ContentInfo{Retention: schema.ContentRetentionMetadata, Included: false}+ writeLog(t, path, event)++ result, err := Search(Query{LogPath: path, Harness: "claude", Limit: 10})+ if err != nil {+ t.Fatalf("Search returned error: %v", err)+ }+ if result.Meta.TotalMatched != 1 || len(result.Events) != 1 {+ t.Fatalf("matched events = total %d len %d, want 1/1", result.Meta.TotalMatched, len(result.Events))+ }+ got := result.Events[0]+ if got.ID == "" || got.Action != "prompt.submitted" || got.Harness != "claude" {+ t.Fatalf("unexpected event summary: %#v", got)+ }+ if got.Content == nil || got.Content.Retention != schema.ContentRetentionMetadata {+ t.Fatalf("content summary = %#v, want metadata retention", got.Content)+ }+ if len(got.Caveats) == 0 {+ t.Fatal("expected retention caveat")+ }+}++func TestListFiltersIncludesRotatedArchives(t *testing.T) {+ path := filepath.Join(t.TempDir(), "runtime.jsonl")+ active := testEvent("2026-05-13T01:02:00Z", "cursor", "prompt.submitted", "prompt")+ active.Repository = "repo-active"+ archive := testEvent("2026-05-13T01:00:00Z", "claude", "mcp.tool_invoked", "mcp")+ archive.MCP = &schema.MCPInfo{Server: "github", Tool: "get_issue"}+ writeLog(t, path, active)+ writeLog(t, path+".1", archive)++ result, err := ListFilters(Query{LogPath: path, Limit: 10})+ if err != nil {+ t.Fatalf("ListFilters returned error: %v", err)+ }+ if !hasValue(result.Filters["harnesses"], "claude") || !hasValue(result.Filters["mcp_servers"], "github") {+ t.Fatalf("filters missing archive values: %#v", result.Filters)+ }+}++func TestGetEventReturnsNotFound(t *testing.T) {+ result, err := GetEvent(filepath.Join(t.TempDir(), "runtime.jsonl"), "line-1")+ if err != nil {+ t.Fatalf("GetEvent returned error: %v", err)+ }+ if result.Found {+ t.Fatal("Found = true, want false")+ }+}++func TestSearchReportsMalformedLines(t *testing.T) {+ path := filepath.Join(t.TempDir(), "runtime.jsonl")+ event := testEvent("2026-05-13T01:00:00Z", "cursor", "command.executed", "command")+ data, err := json.Marshal(event)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, append(append(data, '\n'), []byte("{not json\n")...), 0644); err != nil {+ t.Fatal(err)+ }+ result, err := Search(Query{LogPath: path, Limit: 10})+ if err != nil {+ t.Fatalf("Search returned error: %v", err)+ }+ if result.Meta.MalformedLines != 1 || len(result.Meta.Caveats) == 0 {+ t.Fatalf("malformed meta = %#v, want malformed caveat", result.Meta)+ }+}++func hasValue(values []ValueCount, want string) bool {+ for _, value := range values {+ if value.Value == want {+ return true+ }+ }+ return false+}++func writeLog(t *testing.T, path string, events ...schema.Event) {+ t.Helper()+ var data []byte+ for _, event := range events {+ line, err := json.Marshal(event)+ if err != nil {+ t.Fatalf("marshal event: %v", err)+ }+ data = append(data, line...)+ data = append(data, '\n')+ }+ if err := os.WriteFile(path, data, 0644); err != nil {+ t.Fatalf("write log: %v", err)+ }+}++func testEvent(ts, harness, action, category string) schema.Event {+ return schema.Event{+ Timestamp: ts,+ Vendor: schema.Vendor,+ Product: schema.Product,+ SchemaVersion: schema.SchemaVersion,+ Event: schema.EventInfo{Kind: "agent_runtime", Action: action, Category: category},+ Severity: schema.SeverityInfo,+ Endpoint: schema.EndpointInfo{OS: "darwin"},+ Harness: schema.HarnessInfo{Name: harness},+ Message: action,+ }+}diff --git a/cli/beacon/internal/endpoint/dashboard/events.go b/cli/beacon/internal/endpoint/dashboard/events.goindex dbbb26da..c379383c 100644--- a/cli/beacon/internal/endpoint/dashboard/events.go+++ b/cli/beacon/internal/endpoint/dashboard/events.go@@ -32,6 +32,7 @@ type EventRecord struct {type EventQuery struct {Limit intSince time.Time+ Until time.TimeQ stringHarness stringModel string@@ -285,6 +286,11 @@ func matchesQuery(record EventRecord, query EventQuery) bool {return false}}+ if !query.Until.IsZero() {+ if record.Parsed.IsZero() || record.Parsed.After(query.Until) {+ return false+ }+ }if query.Harness != "" && !strings.EqualFold(event.Harness.Name, query.Harness) {return false}@@ -505,6 +511,9 @@ func activeFilters(query EventQuery) map[string]string {if !query.Since.IsZero() {filters["since"] = query.Since.Format(time.RFC3339)}+ if !query.Until.IsZero() {+ filters["until"] = query.Until.Format(time.RFC3339)+ }if len(filters) == 0 {return nil}diff --git a/cli/beacon/internal/endpoint/dashboard/events_test.go b/cli/beacon/internal/endpoint/dashboard/events_test.goindex bb6b9fa5..1f5c2a03 100644--- a/cli/beacon/internal/endpoint/dashboard/events_test.go+++ b/cli/beacon/internal/endpoint/dashboard/events_test.go@@ -7,6 +7,7 @@ import ("os""path/filepath""testing"+ "time""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema")@@ -250,6 +251,28 @@ func TestReadEventsFiltersByModel(t *testing.T) {}}+func TestReadEventsFiltersByUntil(t *testing.T) {+ path := filepath.Join(t.TempDir(), "runtime.jsonl")+ writeTestLog(t, path,+ testEvent("2026-05-13T01:00:00Z", "cursor", "prompt.submitted", "prompt", "repo-a"),+ testEvent("2026-05-13T02:00:00Z", "cursor", "command.executed", "command", "repo-b"),+ )+ until, err := time.Parse(time.RFC3339, "2026-05-13T01:30:00Z")+ if err != nil {+ t.Fatal(err)+ }+ result, err := ReadEvents(path, EventQuery{Until: until, Limit: 10})+ if err != nil {+ t.Fatalf("ReadEvents returned error: %v", err)+ }+ if result.TotalMatched != 1 || result.Events[0].Event.Event.Action != "prompt.submitted" {+ t.Fatalf("matched %d action %q, want prompt.submitted", result.TotalMatched, result.Events[0].Event.Event.Action)+ }+ if got := result.Filters["until"]; got != "2026-05-13T01:30:00Z" {+ t.Fatalf("until filter = %q, want RFC3339 value", got)+ }+}+func TestReadEventsIncludesRotatedArchives(t *testing.T) {path := filepath.Join(t.TempDir(), "runtime.jsonl")writeTestLog(t, path+".2",diff --git a/cli/beacon/internal/endpoint/dashboard/server.go b/cli/beacon/internal/endpoint/dashboard/server.goindex 701caca5..e5140ee1 100644--- a/cli/beacon/internal/endpoint/dashboard/server.go+++ b/cli/beacon/internal/endpoint/dashboard/server.go@@ -200,6 +200,11 @@ func parseQuery(r *http.Request, fallbackLimit int) EventQuery {query.Since = parsed}}+ if until := q.Get("until"); until != "" {+ if parsed, err := time.Parse(time.RFC3339, until); err == nil {+ query.Until = parsed+ }+ }return query}diff --git a/cli/beacon/internal/mcpserver/server.go b/cli/beacon/internal/mcpserver/server.gonew file mode 100644index 00000000..828222c5--- /dev/null+++ b/cli/beacon/internal/mcpserver/server.go@@ -0,0 +1,418 @@+package mcpserver++import (+ "bufio"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "os"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/activity"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"+)++const (+ TransportStdio = "stdio"+ TransportHTTP = "http"+)++type Options struct {+ LogPath string+ Stderr io.Writer+}++type Server struct {+ logPath string+ tools map[string]Tool+ order []string+ stderr io.Writer+}++type Tool struct {+ Name string `json:"name"`+ Description string `json:"description"`+ InputSchema map[string]interface{} `json:"inputSchema"`+ handler func(context.Context, map[string]interface{}) (interface{}, error)+}++type rpcRequest struct {+ JSONRPC string `json:"jsonrpc"`+ ID json.RawMessage `json:"id,omitempty"`+ Method string `json:"method"`+ Params json.RawMessage `json:"params,omitempty"`+}++type rpcResponse struct {+ JSONRPC string `json:"jsonrpc"`+ ID interface{} `json:"id,omitempty"`+ Result interface{} `json:"result,omitempty"`+ Error *rpcError `json:"error,omitempty"`+}++type rpcError struct {+ Code int `json:"code"`+ Message string `json:"message"`+}++type callToolParams struct {+ Name string `json:"name"`+ Arguments map[string]interface{} `json:"arguments,omitempty"`+}++type toolResult struct {+ Content []textContent `json:"content"`+ IsError bool `json:"isError,omitempty"`+}++type textContent struct {+ Type string `json:"type"`+ Text string `json:"text"`+}++func New(opts Options) *Server {+ if opts.Stderr == nil {+ opts.Stderr = os.Stderr+ }+ server := &Server{+ logPath: opts.LogPath,+ tools: map[string]Tool{},+ stderr: opts.Stderr,+ }+ server.registerTools()+ return server+}++func ValidateTransport(transport string) error {+ switch transport {+ case "", TransportStdio, TransportHTTP:+ return nil+ default:+ return fmt.Errorf("transport must be %q or %q", TransportStdio, TransportHTTP)+ }+}++func (s *Server) ToolNames() []string {+ names := make([]string, len(s.order))+ copy(names, s.order)+ return names+}++func (s *Server) HasExpectedTools() error {+ expected := []string{"search_activity", "summarize_activity", "get_activity_event", "list_activity_filters"}+ for _, name := range expected {+ if _, ok := s.tools[name]; !ok {+ return fmt.Errorf("missing MCP tool %q", name)+ }+ }+ return nil+}++func (s *Server) ServeStdio(ctx context.Context, in io.Reader, out io.Writer) error {+ scanner := bufio.NewScanner(in)+ scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)+ encoder := json.NewEncoder(out)+ for scanner.Scan() {+ select {+ case <-ctx.Done():+ return ctx.Err()+ default:+ }+ response, ok := s.handle(ctx, scanner.Bytes())+ if !ok {+ continue+ }+ if err := encoder.Encode(response); err != nil {+ return err+ }+ }+ if err := scanner.Err(); err != nil {+ return err+ }+ return nil+}++func (s *Server) HTTPHandler() http.Handler {+ mux := http.NewServeMux()+ mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ writeHTTPError(w, http.StatusMethodNotAllowed, "method not allowed")+ return+ }+ writeHTTPJSON(w, map[string]string{"status": "ok"})+ })+ mux.HandleFunc("/mcp", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ writeHTTPError(w, http.StatusMethodNotAllowed, "method not allowed")+ return+ }+ body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4*1024*1024))+ if err != nil {+ writeHTTPError(w, http.StatusBadRequest, err.Error())+ return+ }+ response, ok := s.handle(r.Context(), body)+ if !ok {+ w.WriteHeader(http.StatusAccepted)+ return+ }+ writeHTTPJSON(w, response)+ })+ return mux+}++func (s *Server) handle(ctx context.Context, data []byte) (rpcResponse, bool) {+ var request rpcRequest+ if err := json.Unmarshal(data, &request); err != nil {+ return errorResponse(nil, -32700, "parse error"), true+ }+ id, hasID := requestID(request.ID)+ if !hasID && strings.HasPrefix(request.Method, "notifications/") {+ return rpcResponse{}, false+ }+ if !hasID {+ return rpcResponse{}, false+ }+ result, err := s.dispatch(ctx, request)+ if err != nil {+ return errorResponse(id, -32000, err.Error()), true+ }+ return rpcResponse{JSONRPC: "2.0", ID: id, Result: result}, true+}++func (s *Server) dispatch(ctx context.Context, request rpcRequest) (interface{}, error) {+ switch request.Method {+ case "initialize":+ return map[string]interface{}{+ "protocolVersion": "2024-11-05",+ "capabilities": map[string]interface{}{+ "tools": map[string]interface{}{},+ },+ "serverInfo": map[string]string{+ "name": "beacon",+ "version": version.GetVersion(),+ },+ }, nil+ case "tools/list":+ return map[string]interface{}{"tools": s.listTools()}, nil+ case "tools/call":+ var params callToolParams+ if len(request.Params) > 0 {+ if err := json.Unmarshal(request.Params, ¶ms); err != nil {+ return nil, fmt.Errorf("invalid tool call params: %w", err)+ }+ }+ return s.callTool(ctx, params)+ default:+ return nil, fmt.Errorf("unsupported MCP method %q", request.Method)+ }+}++func (s *Server) listTools() []Tool {+ tools := make([]Tool, 0, len(s.order))+ for _, name := range s.order {+ tool := s.tools[name]+ tool.handler = nil+ tools = append(tools, tool)+ }+ return tools+}++func (s *Server) callTool(ctx context.Context, params callToolParams) (toolResult, error) {+ tool, ok := s.tools[params.Name]+ if !ok {+ return toolResult{}, fmt.Errorf("unknown tool %q", params.Name)+ }+ value, err := tool.handler(ctx, params.Arguments)+ if err != nil {+ return toolResult{IsError: true, Content: []textContent{{Type: "text", Text: err.Error()}}}, nil+ }+ data, err := json.Marshal(value)+ if err != nil {+ return toolResult{}, err+ }+ return toolResult{Content: []textContent{{Type: "text", Text: string(data)}}}, nil+}++func (s *Server) register(tool Tool) {+ s.tools[tool.Name] = tool+ s.order = append(s.order, tool.Name)+}++func (s *Server) registerTools() {+ s.register(Tool{+ Name: "search_activity",+ Description: "Search local Beacon agent activity logs and return compact event summaries.",+ InputSchema: querySchema("Search filters for local activity events."),+ handler: func(ctx context.Context, args map[string]interface{}) (interface{}, error) {+ query, err := parseQuery(s.logPath, args)+ if err != nil {+ return nil, err+ }+ return activity.Search(query)+ },+ })+ s.register(Tool{+ Name: "summarize_activity",+ Description: "Summarize local Beacon agent activity over a time window and optional filters.",+ InputSchema: querySchema("Summary filters for local activity events."),+ handler: func(ctx context.Context, args map[string]interface{}) (interface{}, error) {+ query, err := parseQuery(s.logPath, args)+ if err != nil {+ return nil, err+ }+ return activity.Summarize(query)+ },+ })+ s.register(Tool{+ Name: "get_activity_event",+ Description: "Fetch one compact Beacon activity log entry by ID returned from search_activity.",+ InputSchema: objectSchema(map[string]interface{}{+ "id": map[string]interface{}{"type": "string", "description": "Event ID, such as line-12 or archive-1-line-4."},+ }, []string{"id"}),+ handler: func(ctx context.Context, args map[string]interface{}) (interface{}, error) {+ id, _ := args["id"].(string)+ if strings.TrimSpace(id) == "" {+ return nil, errors.New("id is required")+ }+ return activity.GetEvent(s.logPath, id)+ },+ })+ s.register(Tool{+ Name: "list_activity_filters",+ Description: "List common filter values found in local Beacon activity logs.",+ InputSchema: querySchema("Filters for selecting the activity window to inspect."),+ handler: func(ctx context.Context, args map[string]interface{}) (interface{}, error) {+ query, err := parseQuery(s.logPath, args)+ if err != nil {+ return nil, err+ }+ return activity.ListFilters(query)+ },+ })+}++func parseQuery(logPath string, args map[string]interface{}) (activity.Query, error) {+ query := activity.Query{LogPath: logPath}+ if args == nil {+ return query, nil+ }+ query.Limit = intArg(args, "limit")+ query.Q = stringArg(args, "q")+ query.Harness = stringArg(args, "harness")+ query.Model = stringArg(args, "model")+ query.Action = stringArg(args, "action")+ query.Severity = stringArg(args, "severity")+ query.Category = stringArg(args, "category")+ query.Repository = stringArg(args, "repository")+ query.Session = stringArg(args, "session")+ query.File = stringArg(args, "file")+ query.Command = stringArg(args, "command")+ query.MCP = stringArg(args, "mcp")+ query.Approval = stringArg(args, "approval")+ query.Decision = stringArg(args, "decision")+ query.Policy = stringArg(args, "policy")+ query.Review = stringArg(args, "review")+ query.WazuhLevel = stringArg(args, "wazuh_level")+ var err error+ if query.Since, err = timeArg(args, "since"); err != nil {+ return activity.Query{}, err+ }+ if query.Until, err = timeArg(args, "until"); err != nil {+ return activity.Query{}, err+ }+ return query, nil+}++func querySchema(description string) map[string]interface{} {+ return objectSchema(map[string]interface{}{+ "limit": map[string]interface{}{"type": "integer", "description": "Maximum number of events to return."},+ "since": map[string]interface{}{"type": "string", "description": "RFC3339 lower time bound, inclusive."},+ "until": map[string]interface{}{"type": "string", "description": "RFC3339 upper time bound, inclusive."},+ "q": map[string]interface{}{"type": "string", "description": "Free-text query across structured event fields."},+ "harness": map[string]interface{}{"type": "string", "description": "Agent harness name, such as claude, cursor, or codex."},+ "model": map[string]interface{}{"type": "string", "description": "Model name substring."},+ "action": map[string]interface{}{"type": "string", "description": "Beacon event action."},+ "severity": map[string]interface{}{"type": "string", "description": "Beacon severity."},+ "category": map[string]interface{}{"type": "string", "description": "Event category such as prompt, tool, command, file, mcp, or approval."},+ "repository": map[string]interface{}{"type": "string", "description": "Repository substring."},+ "session": map[string]interface{}{"type": "string", "description": "Session ID substring."},+ "file": map[string]interface{}{"type": "string", "description": "File path substring."},+ "command": map[string]interface{}{"type": "string", "description": "Command or tool command substring."},+ "mcp": map[string]interface{}{"type": "string", "description": "MCP server or tool substring."},+ "approval": map[string]interface{}{"type": "string", "description": "Approval decision or reason substring."},+ "decision": map[string]interface{}{"type": "string", "description": "Approval or policy decision substring."},+ "policy": map[string]interface{}{"type": "string", "description": "Policy ID, name, decision, or reason substring."},+ "review": map[string]interface{}{"type": "string", "description": "Set true to return events needing review."},+ "wazuh_level": map[string]interface{}{"type": "string", "description": "Wazuh-compatible severity level."},+ }, nil, description)+}++func objectSchema(properties map[string]interface{}, required []string, descriptions ...string) map[string]interface{} {+ schema := map[string]interface{}{"type": "object", "properties": properties}+ if len(required) > 0 {+ schema["required"] = required+ }+ if len(descriptions) > 0 && descriptions[0] != "" {+ schema["description"] = descriptions[0]+ }+ return schema+}++func requestID(raw json.RawMessage) (interface{}, bool) {+ if len(raw) == 0 {+ return nil, false+ }+ var id interface{}+ if err := json.Unmarshal(raw, &id); err != nil {+ return nil, false+ }+ return id, true+}++func errorResponse(id interface{}, code int, message string) rpcResponse {+ return rpcResponse{JSONRPC: "2.0", ID: id, Error: &rpcError{Code: code, Message: message}}+}++func stringArg(args map[string]interface{}, key string) string {+ value, _ := args[key].(string)+ return strings.TrimSpace(value)+}++func intArg(args map[string]interface{}, key string) int {+ switch value := args[key].(type) {+ case float64:+ return int(value)+ case int:+ return value+ default:+ return 0+ }+}++func timeArg(args map[string]interface{}, key string) (time.Time, error) {+ value := stringArg(args, key)+ if value == "" {+ return time.Time{}, nil+ }+ parsed, err := time.Parse(time.RFC3339, value)+ if err != nil {+ return time.Time{}, fmt.Errorf("%s must be RFC3339: %w", key, err)+ }+ return parsed, nil+}++func writeHTTPJSON(w http.ResponseWriter, value interface{}) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(value)+}++func writeHTTPError(w http.ResponseWriter, status int, message string) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(map[string]string{"error": message})+}diff --git a/cli/beacon/internal/mcpserver/server_test.go b/cli/beacon/internal/mcpserver/server_test.gonew file mode 100644index 00000000..7168d9ab--- /dev/null+++ b/cli/beacon/internal/mcpserver/server_test.go@@ -0,0 +1,105 @@+package mcpserver++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++func TestServeStdioListsAndCallsTools(t *testing.T) {+ path := filepath.Join(t.TempDir(), "runtime.jsonl")+ writeTestLog(t, path, testEvent("2026-05-13T01:00:00Z", "cursor", "prompt.submitted", "prompt"))+ server := New(Options{LogPath: path})+ input := strings.Join([]string{+ `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`,+ `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"search_activity","arguments":{"harness":"cursor","limit":5}}}`,+ "",+ }, "\n")+ var output bytes.Buffer+ if err := server.ServeStdio(t.Context(), strings.NewReader(input), &output); err != nil {+ t.Fatalf("ServeStdio returned error: %v", err)+ }+ lines := strings.Split(strings.TrimSpace(output.String()), "\n")+ if len(lines) != 2 {+ t.Fatalf("response lines = %d, want 2; output=%s", len(lines), output.String())+ }+ var list map[string]interface{}+ if err := json.Unmarshal([]byte(lines[0]), &list); err != nil {+ t.Fatalf("decode tools/list: %v", err)+ }+ if !strings.Contains(lines[0], "search_activity") {+ t.Fatalf("tools/list missing search_activity: %s", lines[0])+ }+ if !strings.Contains(lines[1], "prompt.submitted") {+ t.Fatalf("tools/call missing event result: %s", lines[1])+ }+}++func TestHTTPHandlerHealthAndMCP(t *testing.T) {+ path := filepath.Join(t.TempDir(), "runtime.jsonl")+ writeTestLog(t, path, testEvent("2026-05-13T01:00:00Z", "cursor", "prompt.submitted", "prompt"))+ handler := New(Options{LogPath: path}).HTTPHandler()++ health := httptest.NewRecorder()+ handler.ServeHTTP(health, httptest.NewRequest(http.MethodGet, "/health", nil))+ if health.Code != http.StatusOK {+ t.Fatalf("health status = %d, want 200", health.Code)+ }++ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":"a","method":"tools/call","params":{"name":"summarize_activity","arguments":{}}}`))+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("mcp status = %d, want 200; body=%s", rec.Code, rec.Body.String())+ }+ if !strings.Contains(rec.Body.String(), "total_events") {+ t.Fatalf("mcp response missing summary: %s", rec.Body.String())+ }+}++func TestExpectedToolsRegistered(t *testing.T) {+ server := New(Options{LogPath: "runtime.jsonl"})+ if err := server.HasExpectedTools(); err != nil {+ t.Fatalf("HasExpectedTools returned error: %v", err)+ }+ if got := strings.Join(server.ToolNames(), ","); got != "search_activity,summarize_activity,get_activity_event,list_activity_filters" {+ t.Fatalf("ToolNames = %s", got)+ }+}++func writeTestLog(t *testing.T, path string, events ...schema.Event) {+ t.Helper()+ var data []byte+ for _, event := range events {+ line, err := json.Marshal(event)+ if err != nil {+ t.Fatalf("marshal event: %v", err)+ }+ data = append(data, line...)+ data = append(data, '\n')+ }+ if err := os.WriteFile(path, data, 0644); err != nil {+ t.Fatalf("write log: %v", err)+ }+}++func testEvent(ts, harness, action, category string) schema.Event {+ return schema.Event{+ Timestamp: ts,+ Vendor: schema.Vendor,+ Product: schema.Product,+ SchemaVersion: schema.SchemaVersion,+ Event: schema.EventInfo{Kind: "agent_runtime", Action: action, Category: category},+ Severity: schema.SeverityInfo,+ Endpoint: schema.EndpointInfo{OS: "darwin"},+ Harness: schema.HarnessInfo{Name: harness},+ Message: action,+ }+}