Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 74 additions & 4 deletions pkgs/mcpx/internal/daemon/call_frames_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/config"
"github.com/developing-today/code/pkgs/mcpx/internal/execsvc"
"github.com/developing-today/code/pkgs/mcpx/internal/logging"
)

// collectFrames registers a sink for run on s and returns the frames it
Expand All @@ -24,12 +27,79 @@ func collectFrames(s *Server, run string) *[]execsvc.Frame {
return frames
}

func TestReportCallFrameWritesPayloadFreeLedgerWithoutRun(t *testing.T) {
dir := t.TempDir()
ledger, err := logging.NewFileSink(logging.FileOptions{Dir: dir})
if err != nil {
t.Fatal(err)
}
defer ledger.Close()
s := &Server{callLedger: ledger}
start := time.Now().Add(-25 * time.Millisecond)
s.reportCallFrame(context.Background(), "srv", "tool", "session-7", map[string]any{"secret": "do-not-write"}, start,
json.RawMessage(`{"isError":true,"content":[{"text":"private error"}]}`), nil)
s.reportCallFrame(context.Background(), "srv", "ok", "", map[string]any{}, time.Now(), json.RawMessage(`{"ok":true}`), nil)

data, err := os.ReadFile(filepath.Join(dir, "mcpx-"+time.Now().Format("2006-01-02")+".jsonl"))
if err != nil {
t.Fatal(err)
}
lines := strings.Split(strings.TrimSpace(string(data)), "\n")
if len(lines) != 2 {
t.Fatalf("ledger has %d records, want exactly 2: %s", len(lines), data)
}
var failed, succeeded map[string]any
if err := json.Unmarshal([]byte(lines[0]), &failed); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal([]byte(lines[1]), &succeeded); err != nil {
t.Fatal(err)
}
if failed["server"] != "srv" || failed["tool"] != "tool" || failed["outcome"] != "error" || failed["msg"] != "tool_call" || failed["caller_session"] != "session-7" {
t.Fatalf("error ledger row = %v", failed)
}
if _, ok := failed["duration_ms"]; !ok || failed["ts"] == nil {
t.Fatalf("error ledger row lacks timestamp or duration: %v", failed)
}
if succeeded["server"] != "srv" || succeeded["tool"] != "ok" || succeeded["outcome"] != "success" {
t.Fatalf("success ledger row = %v", succeeded)
}
if strings.Contains(string(data), "secret") || strings.Contains(string(data), "private error") {
t.Fatalf("ledger leaked call payload: %s", data)
}
}

func TestPruneCallLedgerKeepsEightCalendarDays(t *testing.T) {
dir := t.TempDir()
now := time.Date(2026, time.November, 18, 12, 0, 0, 0, time.UTC)
for _, name := range []string{
"mcpx-2026-11-10.jsonl",
"mcpx-2026-11-11.jsonl",
"mcpx-2026-11-11-120000.jsonl",
"other-2026-11-01.jsonl",
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte("{}\n"), 0o600); err != nil {
t.Fatal(err)
}
}

pruneCallLedger(dir, now)
if _, err := os.Stat(filepath.Join(dir, "mcpx-2026-11-10.jsonl")); !os.IsNotExist(err) {
t.Fatalf("expired daily ledger file was not removed: %v", err)
}
for _, name := range []string{"mcpx-2026-11-11.jsonl", "mcpx-2026-11-11-120000.jsonl", "other-2026-11-01.jsonl"} {
if _, err := os.Stat(filepath.Join(dir, name)); err != nil {
t.Fatalf("kept ledger/unrelated file %s missing: %v", name, err)
}
}
}

func TestReportCallFrameMarksIsErrorResultsFailed(t *testing.T) {
s := &Server{reg: &Registry{}}
frames := collectFrames(s, "run-1")
ctx := withRun(context.Background(), "run-1")

s.reportCallFrame(ctx, "srv", "tool", map[string]any{}, time.Now(),
s.reportCallFrame(ctx, "srv", "tool", "", map[string]any{}, time.Now(),
json.RawMessage(`{"content":[{"type":"text","text":"no"}],"isError":true}`), nil)
if len(*frames) != 1 {
t.Fatalf("frames = %v, want 1", *frames)
Expand All @@ -39,7 +109,7 @@ func TestReportCallFrameMarksIsErrorResultsFailed(t *testing.T) {
t.Fatalf("isError result must be a failed call frame, got %+v", c)
}

s.reportCallFrame(ctx, "srv", "tool", map[string]any{}, time.Now(),
s.reportCallFrame(ctx, "srv", "tool", "", map[string]any{}, time.Now(),
json.RawMessage(`{"content":[],"isError":false}`), nil)
if len(*frames) != 2 || !(*frames)[1].Call.OK {
t.Fatalf("a clean result must stay ok, got %+v", *frames)
Expand All @@ -58,7 +128,7 @@ func TestReportCallFrameResolvesExactServerBeforeNamespace(t *testing.T) {
frames := collectFrames(s, "run-2")
ctx := withRun(context.Background(), "run-2")

s.reportCallFrame(ctx, "b", "x", map[string]any{}, time.Now(), nil, nil)
s.reportCallFrame(ctx, "b", "x", "", map[string]any{}, time.Now(), nil, nil)
if len(*frames) != 1 {
t.Fatalf("frames = %v, want 1", *frames)
}
Expand All @@ -73,7 +143,7 @@ func TestReportCallFrameResolvesExactServerBeforeNamespace(t *testing.T) {
}}
s2 := &Server{reg: reg2}
frames2 := collectFrames(s2, "run-3")
s2.reportCallFrame(withRun(context.Background(), "run-3"), "ns", "x",
s2.reportCallFrame(withRun(context.Background(), "run-3"), "ns", "x", "",
map[string]any{}, time.Now(), nil, nil)
if len(*frames2) != 1 {
t.Fatalf("frames = %v, want 1", *frames2)
Expand Down
37 changes: 37 additions & 0 deletions pkgs/mcpx/internal/daemon/call_ledger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package daemon

import (
"os"
"path/filepath"
"strings"
"time"
)

// pruneCallLedger keeps eight calendar days of daily JSONL files. FileSink
// separately caps each active file and retains eight size/line/age rotations;
// together these bounds prevent old daily files from accumulating forever.
func pruneCallLedger(dir string, now time.Time) {
entries, err := os.ReadDir(dir)
if err != nil {
return
}
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
cutoff := today.AddDate(0, 0, -7)
for _, entry := range entries {
name := entry.Name()
if !strings.HasPrefix(name, "mcpx-") || !strings.HasSuffix(name, ".jsonl") {
continue
}
stem := strings.TrimSuffix(strings.TrimPrefix(name, "mcpx-"), ".jsonl")
if len(stem) < len("2006-01-02") {
continue
}
day, err := time.Parse("2006-01-02", stem[:len("2006-01-02")])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Parse ledger dates in the same timezone as the retention cutoff

On hosts west of UTC, time.Parse interprets the filename as UTC midnight while cutoff uses local midnight. For example, on November 18 in Los Angeles, mcpx-2026-11-11.jsonl parses to November 11 at 00:00Z, before the cutoff at 08:00Z, and is deleted even though November 11 is the eighth retained calendar day. That file can still contain calls within the aggregator's rolling seven-day window. Use time.ParseInLocation with now.Location(), or compare calendar dates consistently, to avoid prematurely deleting valid history.

Useful? React with 👍 / 👎.

if err != nil || (len(stem) > len("2006-01-02") && stem[len("2006-01-02")] != '-') {
continue
}
if day.Before(cutoff) {
_ = os.Remove(filepath.Join(dir, name))
}
}
}
2 changes: 1 addition & 1 deletion pkgs/mcpx/internal/daemon/input_required.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func (s *Server) handleCallReporting(w http.ResponseWriter, r *http.Request, req
// report the completed call here: an exec run whose calls
// ask questions is still a run whose calls belong in its
// stream.
s.reportCallFrame(callCtx, req.Server, req.Tool, args, start, res, err)
s.reportCallFrame(callCtx, req.Server, req.Tool, cc.SessionID, args, start, res, err)
done <- outcome{res, err}
if err != nil {
return nil, &tasks.Fault{Code: failureStatus(err), Message: err.Error()}
Expand Down
2 changes: 1 addition & 1 deletion pkgs/mcpx/internal/daemon/routes_proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -1058,7 +1058,7 @@ func (s *Server) handleCallPath(w http.ResponseWriter, r *http.Request) {
} else {
res, err = s.reg.Call(callCtx, r.PathValue("server"), r.PathValue("tool"), cc, args)
}
s.reportCallFrame(callCtx, r.PathValue("server"), r.PathValue("tool"), args, start, res, err)
s.reportCallFrame(callCtx, r.PathValue("server"), r.PathValue("tool"), cc.SessionID, args, start, res, err)
if err != nil {
writeJSON(w, failureStatus(err), map[string]any{"ok": false, "error": err.Error()})
return
Expand Down
92 changes: 71 additions & 21 deletions pkgs/mcpx/internal/daemon/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,13 @@ type Server struct {

// sink is the durable log POST /v1/log appends to. Nil when the log
// could not be opened, which the daemon survives and the route reports.
sink *logging.FileSink
lastReq atomic.Int64
sink *logging.FileSink
// callLedger is the dedicated, payload-free execution ledger. It is
// separate from the mixed diagnostic log so analytics can read it safely.
callLedger *logging.FileSink
callLedgerDir string
lastLedgerPrune atomic.Int64
lastReq atomic.Int64

// cfgMu guards cfg, contentHash and stamp. The daemon re-reads its
// configuration from a request goroutine now, so what used to be
Expand Down Expand Up @@ -241,24 +246,43 @@ func NewServer(opts Options) (*Server, error) {
if err := ValidateBearerToken(opts.Settings); err != nil {
return nil, err
}
// This dedicated, payload-free JSONL surface has an explicit rotation
// contract independent of general logging defaults: 16 MiB, 200k records,
// or 24 hours per file, retaining eight rotated files. FileSink names the
// active file mcpx-YYYY-MM-DD.jsonl and rotated files with a time suffix.
callLedger, ledgerErr := logging.NewFileSink(logging.FileOptions{
Dir: filepath.Join(opts.Paths.State, "call-ledger"),
Comment on lines +253 to +254

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Coordinate ledger rotation across config-specific daemons

When different project configurations run concurrently, their daemons share Paths.State (Paths.ForConfig changes only the socket and info paths), so each opens this same daily ledger file. FileSink only synchronizes within one instance and keeps its descriptor open: one daemon can rotate and eventually prune the file another daemon is still writing. The quieter daemon then appends new call records to an unlinked file until its own rotation or day change, silently dropping current activity from analytics. Use a process-safe shared writer/rotation scheme or separate per-daemon files that analytics aggregates.

Useful? React with 👍 / 👎.

MaxBytes: 16 * 1024 * 1024,
MaxLines: 200_000,
MaxAge: 24 * time.Hour,
Keep: 8,
})
if ledgerErr == nil {
pruneCallLedger(filepath.Join(opts.Paths.State, "call-ledger"), time.Now())
}
if ledgerErr != nil {
opts.Logger.Printf("call ledger unavailable: %v", ledgerErr)
}
// logging.trace, which is MCPX_TRACE. It was read here by name, so a
// configuration file or `mcpx daemon --logging-trace` could not turn it on.
if opts.Settings.Bool("logging.trace") {
pool.Trace = func(f string, a ...any) { opts.Logger.Printf(f, a...) }
}
srv := &Server{
set: opts.Settings,
reg: reg,
paths: opts.Paths,
cfg: opts.Config,
logger: opts.Logger,
version: opts.Version,
idleExit: opts.IdleExit,
sink: opts.Sink,
augment: opts.Augment,
Events: events.New(opts.Settings.Int("events.history")),
httpErr: make(chan error, 4),
handedOff: make(chan struct{}),
set: opts.Settings,
reg: reg,
paths: opts.Paths,
cfg: opts.Config,
logger: opts.Logger,
version: opts.Version,
idleExit: opts.IdleExit,
sink: opts.Sink,
callLedger: callLedger,
callLedgerDir: filepath.Join(opts.Paths.State, "call-ledger"),
augment: opts.Augment,
Events: events.New(opts.Settings.Int("events.history")),
httpErr: make(chan error, 4),
handedOff: make(chan struct{}),
}
// The broker is optional: a daemon whose state directory cannot hold a
// database still serves tools, and answers every server question with
Expand Down Expand Up @@ -761,6 +785,9 @@ func (s *Server) shutdown() error {
if s.tokenStore != nil {
_ = s.tokenStore.Close()
}
if s.callLedger != nil {
_ = s.callLedger.Close()
}
_ = os.Remove(s.paths.Socket)
s.paths.RemoveInfo()
s.logger.Printf("stopped")
Expand Down Expand Up @@ -1253,7 +1280,7 @@ func (s *Server) handleCall(w http.ResponseWriter, r *http.Request) {
res, err = s.reg.Call(ctx, req.Server, req.Tool, cc, args)
}
dur := time.Since(start).Truncate(time.Millisecond)
s.reportCallFrame(ctx, req.Server, req.Tool, args, start, res, err)
s.reportCallFrame(ctx, req.Server, req.Tool, cc.SessionID, args, start, res, err)

toolKey := req.Server + ":" + req.Tool
var inBytes, outBytes []byte
Expand Down Expand Up @@ -1405,7 +1432,7 @@ func (s *Server) handleBatch(w http.ResponseWriter, r *http.Request) {
// Batch items bypass the single-call handlers, so report each
// completed one here: a script's batch(...) calls belong in
// its exec stream like any other call.
s.reportCallFrame(ctx, server, tool, args, start, res, err)
s.reportCallFrame(ctx, server, tool, cc.SessionID, args, start, res, err)

if err != nil {
return map[string]any{
Expand Down Expand Up @@ -1914,18 +1941,41 @@ func (s *Server) callRegistry() *execsvc.CallRegistry {
// reportCallFrame tells the exec stream that is running this call, if
// any, that the call happened: a call frame with the tool's resolved
// destructiveHint. A call with no run id, or a run this daemon is not
// executing, has no stream to join and is not reported.
func (s *Server) reportCallFrame(ctx context.Context, server, tool string, args any, start time.Time, res json.RawMessage, callErr error) {
// executing, has no stream to join but still belongs in the call ledger.
func (s *Server) reportCallFrame(ctx context.Context, server, tool, callerSession string, args any, start time.Time, res json.RawMessage, callErr error) {
run := runFrom(ctx)
if run == "" {
return
}
// A tool that ran and returned isError failed, even though the
// transport call itself succeeded: the frame must say so, the way
// the path-per-tool handler already does with resultFailed.
if callErr == nil && resultFailed(res) {
callErr = errors.New("tool returned an error result (isError)")
}
if s.callLedger != nil {
attrs := map[string]any{
"server": server,
"tool": tool,
"outcome": "success",
Comment on lines +1953 to +1957

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude simulated dry-run calls from the execution ledger

When an exec request uses dryRun: true, its calls still reach this reporter after dryRunResult returns synthetic responses without contacting any server, as shown in handleCall, handleBatch, and handleCallPath. The new ledger nevertheless records them as successful executions without preserving the dry-run marker, and readMcpxCallLedger counts those rows as daemon activity. Rehearsing a script therefore inflates execution totals and successful-call counts even though no tools ran. Skip ledger writes for dry-run calls, or preserve and filter their synthetic status while retaining the existing exec call frames.

Useful? React with 👍 / 👎.

"duration_ms": time.Since(start).Milliseconds(),
}
if callErr != nil {
attrs["outcome"] = "error"
}
if run != "" {
attrs["caller_run"] = run
}
if callerSession != "" {
attrs["caller_session"] = callerSession
}
s.callLedger.Write(logging.Record{Time: time.Now(), Msg: "tool_call", Attrs: attrs}, nil)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Record calls from the ask and explicit-task execution paths

Calls executed through /v1/ask or explicit /v1/call tasks never reach this ledger write. handleAskBegin calls s.reg.CallAsk in routes_proto.go:628, and startCallTask calls s.reg.Call in ops.go:804; neither invokes reportCallFrame. The ask path is used by the MCP proxy (internal/cli/serve_ask.go:218), so this omits a production call flow, not just an internal helper. Record outcomes at those execution sites as well, or move ledger recording to a shared execution boundary, so daemon totals include their successes and errors.

Useful? React with 👍 / 👎.

now := time.Now()
last := s.lastLedgerPrune.Load()
if now.Unix()-last >= 3600 && s.lastLedgerPrune.CompareAndSwap(last, now.Unix()) {
pruneCallLedger(s.callLedgerDir, now)
}
}
if run == "" {
return
}
var dh *bool
if picked := s.pickTool(server, tool); picked != nil {
d := destructiveHint(picked.Annotations)
Expand Down
Loading
Loading