diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index f8f848032..0cd729fb4 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -653,6 +653,51 @@ however old, so a client's history can be backfilled. concurrent posts beside the gateway's own writes, and a backfill of a full 5000-record batch landing on the right 7d/30d/all days. +### Calls to magpie's own MCP tools + +An agent's call to a tool of one of magpie's own MCP servers is a row of +`usage.jsonl` too (ferock on Discord): the image server's +`generate_image`, `generate_video` and `generation_result`, vision, web +search, plugin tools and the hub's. The row has `source: "mcp"`, +`kind: "mcp"`, operation `execute_tool`, the tool's name as `req`, the +server's name as `host` (`magpie-image`, `magpie-vision`, +`magpie-web-search`, `magpie-tools`, or the Library server a hub tool is +of), the agent, the provider and model of the last gateway request the +call made, its duration, its endpoint (the server's path, `stdio` for the +Magpie Image server an agent runs) and, when it failed, the JSON-RPC +error or the `isError` result's first text, clipped by `keepMsg`. Its +arguments are never kept, not even masked. + +- **Written by:** `serveMCP` for every `tools/call` (`callMCPTool` in + [`mcp_calls.go`](../../internal/gateway/mcp_calls.go)). The call's + context carries an `mcpUse`, which `appendUsage` fills with each model + row's provider and model; the image server's jobs keep it, so a + `generation_result` names the model of the job it waited on. A drawing + still running when its call answers leaves that call's row without a + model. The stdio Magpie Image server calls the gateway's `/v1/images` + and `/v1/videos` itself, so it reports each call it answered to the + gateway's image MCP server with the JSON-RPC method `magpie/toolCalled` + (`gateway.MCPCalledMethod`, params `MCPCalled`: tool, ms, model, + error); a tool not Magpie Image's is -32602. An older gateway that + doesn't know the method just leaves the call unlisted. +- **Counted nowhere:** `Record.IsProbe` is true for these rows, so they + ride the probe lane above: listed (`probeChunk`, kept as they are), + never in a total, chart, budget (`budget.counts`) or `Load`. The model + requests a call made are rows of their own and count as any. The + index's provider hosts skip them (`sawHost`), as their host is a + server's name. +- **On the page:** the Requests row has an `MCP` badge (`.src.mcp`, + muted, no stripe) whose tooltip names the agent, tool and server and + says the arguments are not kept; the Where cell is the provider and the + server, the Requested cell the tool, and the status Succeeded or + Failed. The Purpose filter names `kind:mcp` "MCP tool" + (`purposeKinds`, `purposes.js`). + +`TestMCPToolCallIsARequestRow`, `TestMCPHubCallIsARequestRow`, +`TestMCPCalledFromStdioIsARow` and the others in `mcp_calls_test.go`, +`TestToolCallsAreReported` (imagemcp), `TestMCPCallRowsListedNotCounted` +(usage) and `usage-ledger-mcp.test.cjs` cover it. + ### Requests magpie sends on its own The provider editor's Test, Detect APIs and per-model detection, and a diff --git a/docs/subsystems/mcp-hub.md b/docs/subsystems/mcp-hub.md index fc6738301..397c3919b 100644 --- a/docs/subsystems/mcp-hub.md +++ b/docs/subsystems/mcp-hub.md @@ -26,6 +26,7 @@ The gateway can't import the library (the library imports the gateway), so the g Another app does the same at `/mcp/magpie/hub`, under the same guard: from another computer it needs a gateway key, as every LAN request does. 3. `tools/call` finds the tool by its hub name in the same list, holds it to the key's limit, and calls `Call` under `hubCallWait` (50s, under the 60s an MCP client gives a call). The server's result goes back as it gave it. 4. An error comes back as `isError` text naming the server: `The MCP server S couldn't run T: `, where why is how it exited and its last line on stderr, a sign-in it needs, its command not found, or `it didn't answer in 50s`. +5. Each call is a row of the request log (`serveMCP`'s `callMCPTool`): the hub's tool name, the Library server as its host, the agent of the path, how long it took and its error, never its arguments. It counts in no total ([Calls to magpie's own MCP tools](gateway-sessions.md#calls-to-magpies-own-mcp-tools)). ## Constraints and failure behavior diff --git a/internal/budget/budget.go b/internal/budget/budget.go index 22d8baf5e..3f86b2ff9 100644 --- a/internal/budget/budget.go +++ b/internal/budget/budget.go @@ -97,8 +97,11 @@ func slot(keyID string) string { return usage.Path() + "\x00" + keyID } // counts reports whether r is a call a key's budget counts. // A call an app reported itself (#1874) never counts: it didn't go through -// magpie, and may be a backfill of calls long past. -func counts(r usage.Record) bool { return !r.IsRejected() && !r.IsReported() && r.Computer == "" } +// magpie, and may be a backfill of calls long past. Nor does an MCP tool +// call (usage.SourceMCP): the model requests it made are calls of their own. +func counts(r usage.Record) bool { + return !r.IsRejected() && !r.IsReported() && !r.IsProbe() && r.Computer == "" +} // sumsFor is keyID's sums for each window starting at starts, read from // usage.jsonl the first time; those of windows no limit counts in now diff --git a/internal/gateway/hub_mcp.go b/internal/gateway/hub_mcp.go index b72b7e576..1228398c4 100644 --- a/internal/gateway/hub_mcp.go +++ b/internal/gateway/hub_mcp.go @@ -77,7 +77,7 @@ const errHubOff = "magpie's MCP hub is off, so it runs no server's tools: turn i func (s *Server) hubMCP(w http.ResponseWriter, r *http.Request) { agent := r.PathValue("agent") - serveMCP(w, r, "magpie's MCP hub", hubBody, func(r *http.Request, m mcpMessage) (any, map[string]any) { + serveMCP(w, r, "magpie's MCP hub", "magpie", hubBody, func(r *http.Request, m mcpMessage) (any, map[string]any) { return s.hubMCPCall(r, agent, m) }) } @@ -180,6 +180,10 @@ func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, m // limit. A server that is down or doesn't answer in time is an error // result naming it, never a wait past the client's. func (s *Server) hubMCPRun(r *http.Request, agent string, t hubTool, args json.RawMessage) any { + // the request log names the Library's server, and the agent the hub is mounted for + use := mcpUseOf(r.Context()) + use.on(t.Server) + use.as(agent) release, err := reserveFor(access.Caller(r.Context()), int64(len(args)), "", limitClock()) if err != nil { return toolResult(err.Error(), true) diff --git a/internal/gateway/image_mcp.go b/internal/gateway/image_mcp.go index 02769241d..978840d0f 100644 --- a/internal/gateway/image_mcp.go +++ b/internal/gateway/image_mcp.go @@ -181,6 +181,9 @@ type imageJob struct { started time.Time done chan struct{} result map[string]any // the tool result, once done + // use is what the call that started it used, which a + // generation_result's row names too + use *mcpUse } type imageFile struct { @@ -190,7 +193,7 @@ type imageFile struct { } func (s *Server) imageMCP(w http.ResponseWriter, r *http.Request) { - serveMCP(w, r, "magpie's image generation", visionMCPBody, s.imageMCPCall) + serveMCP(w, r, "magpie's image generation", imageServerName, visionMCPBody, s.imageMCPCall) } // imageMCPCall answers one request: its result, or its JSON-RPC error. @@ -221,6 +224,8 @@ func (s *Server) imageMCPCall(r *http.Request, m mcpMessage) (any, map[string]an return nil, map[string]any{"code": -32602, "message": err.Error()} } return map[string]any{"model": ref}, nil + case MCPCalledMethod: + return imageMCPCalled(r, m.Params) case "tools/call": var p struct { Name string `json:"name"` @@ -319,7 +324,7 @@ func (s *Server) imageMCPDraw(r *http.Request, raw json.RawMessage) map[string]a // the drawing goes on when the call has answered: a job of its own, // with the call's caller (its key, its agent) but not its end in := inProcess(r, context.WithoutCancel(r.Context()), http.MethodPost, path, body) - j := s.imageMCPStart(who.KeyID, func() map[string]any { + j := s.imageMCPStart(who.KeyID, mcpUseOf(r.Context()), func() map[string]any { defer release() ctx, cancel := context.WithTimeout(in.Context(), imageMCPJobMost) defer cancel() @@ -530,6 +535,8 @@ func (s *Server) imageMCPVideo(r *http.Request, id string) map[string]any { } `json:"error"` } json.Unmarshal(rec.body.Bytes(), &v) + // the video's model, provider/model, for a call that only asks after it + mcpUseOf(r.Context()).usedRef(v.Model) switch v.Status { case "completed": length := "" @@ -576,10 +583,10 @@ func (s *Server) imageMCPResult(r *http.Request, id string) map[string]any { return s.imageMCPAwait(r, j) } -// imageMCPStart runs draw as a job started by key. -func (s *Server) imageMCPStart(key string, draw func() map[string]any) *imageJob { +// imageMCPStart runs draw as a job started by key, in a call that is use. +func (s *Server) imageMCPStart(key string, use *mcpUse, draw func() map[string]any) *imageJob { st := &s.imageStore - j := &imageJob{id: "img_" + randomHex(12), key: key, started: time.Now(), done: make(chan struct{})} + j := &imageJob{id: "img_" + randomHex(12), key: key, started: time.Now(), done: make(chan struct{}), use: use} st.mu.Lock() if st.jobs == nil { st.jobs = map[string]*imageJob{} @@ -610,6 +617,7 @@ func (s *Server) imageMCPAwait(r *http.Request, j *imageJob) map[string]any { defer limit.Stop() select { case <-j.done: + mcpUseOf(r.Context()).from(j.use) return j.result case <-limit.C: case <-r.Context().Done(): diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 05105818e..dec0aa5ea 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -573,6 +573,10 @@ func appendUsage(r *http.Request, rec usage.Record) { if r.Context().Value(observedKey{}) != nil { rec.Watched = true } + if !rec.IsProbe() { + // a request an MCP tool call made: its row names the model (mcpUse) + mcpUseOf(r.Context()).used(rec.Provider, rec.Model) + } budget.Append(rec) } diff --git a/internal/gateway/mcp_calls.go b/internal/gateway/mcp_calls.go new file mode 100644 index 000000000..dd2bf8d7d --- /dev/null +++ b/internal/gateway/mcp_calls.go @@ -0,0 +1,197 @@ +package gateway + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/usage" +) + +// An agent's call to a tool of one of magpie's own MCP servers is a row of +// the request log (usage.SourceMCP), apart from the model requests (ferock +// on Discord): which tool, when, the provider and model it used, how long +// it took and whether it worked. serveMCP writes one for every tools/call +// the gateway's servers answer (image, vision, web search, plugin tools, +// the hub), and the Magpie Image server an agent runs reports its own +// (MCPCalledMethod), as its calls never pass here. A call's arguments are +// never kept: the row has the tool's name and, when it failed, what it +// said, clipped as a vendor's error is (keepMsg). + +// MCPCalledMethod is the JSON-RPC method the Magpie Image server an agent +// runs tells the gateway's image MCP server of a tool call it answered: +// MCPCalled, as params. It is answered with an empty result. +const MCPCalledMethod = "magpie/toolCalled" + +// MCPCalled is one tool call the Magpie Image server answered. +type MCPCalled struct { + Tool string `json:"tool"` + // Millis is how long the call took, to its answer + Millis int64 `json:"ms"` + // Model is what the gateway's answer named the model by: provider/model + Model string `json:"model,omitempty"` + // Error is what a failed call said + Error string `json:"error,omitempty"` +} + +// imageServerName is what the request log names both image servers by. +const imageServerName = "magpie-image" + +// mcpUseKey holds a tool call's *mcpUse in its request's context. +type mcpUseKey struct{} + +// mcpUse is what one tool call was: its server, and the provider and +// model of the last gateway request it made (appendUsage), which may run +// after the call has answered (an image still drawing). +type mcpUse struct { + mu sync.Mutex + agent, server, provider, model string +} + +func mcpUseOf(ctx context.Context) *mcpUse { + u, _ := ctx.Value(mcpUseKey{}).(*mcpUse) + return u +} + +// used is that the call's request went to provider's model. +func (u *mcpUse) used(provider, model string) { + if u == nil || provider == "" { + return + } + u.mu.Lock() + u.provider, u.model = provider, model + u.mu.Unlock() +} + +// usedRef is used with the provider/model an answer names the model by. +func (u *mcpUse) usedRef(ref string) { + if p, m, ok := strings.Cut(ref, "/"); ok { + u.used(p, m) + } +} + +// from is that the call was of what o, an earlier call's, used: a +// generation_result's, of the generate call that started the job. +func (u *mcpUse) from(o *mcpUse) { + if u == nil || o == nil || u == o { + return + } + o.mu.Lock() + p, m := o.provider, o.model + o.mu.Unlock() + u.used(p, m) +} + +// on names the server the call went to, for the hub's, whose tools are +// of the servers in the Library. +func (u *mcpUse) on(server string) { + if u == nil || server == "" { + return + } + u.mu.Lock() + u.server = server + u.mu.Unlock() +} + +// as names the agent the call was for, for the hub's, mounted per agent. +func (u *mcpUse) as(agent string) { + if u == nil || agent == "" { + return + } + u.mu.Lock() + u.agent = agent + u.mu.Unlock() +} + +func (u *mcpUse) get() (agent, server, provider, model string) { + u.mu.Lock() + defer u.mu.Unlock() + return u.agent, u.server, u.provider, u.model +} + +// callMCPTool answers a tools/call to server with call, and writes its row. +func callMCPTool(r *http.Request, server string, m mcpMessage, call func(*http.Request, mcpMessage) (any, map[string]any)) (any, map[string]any) { + use := &mcpUse{server: server} + start := time.Now() + result, rpcErr := call(r.WithContext(context.WithValue(r.Context(), mcpUseKey{}, use)), m) + var p struct { + Name string `json:"name"` + } + json.Unmarshal(m.Params, &p) + agent, server, prov, model := use.get() + logMCPCall(r, agent, server, r.URL.Path, p.Name, prov, model, start, time.Since(start), mcpFailure(result, rpcErr)) + return result, rpcErr +} + +// logMCPCall writes a tool call's row; agent "" is the request's caller. +// endpoint is the server's path, "stdio" for one an agent runs. +func logMCPCall(r *http.Request, agent, server, endpoint, tool, prov, model string, start time.Time, took time.Duration, failure string) { + who := callerOf(r) + rec := usage.Record{Operation: "execute_tool", Time: start, Agent: who.agent, Via: who.via, + Provider: prov, Model: model, Requested: keepMsg(tool), Host: server, Millis: took.Milliseconds(), + Error: keepMsg(failure), Endpoint: endpoint, Kind: usage.KindMCP, Source: usage.SourceMCP} + if agent != "" { + rec.Agent = agent + } + appendUsage(r, rec) +} + +// mcpFailure is what a failed call said: its JSON-RPC error's message, or +// the text of a result that is an error; "" for one that worked. +func mcpFailure(result any, rpcErr map[string]any) string { + if rpcErr != nil { + if s, _ := rpcErr["message"].(string); s != "" { + return s + } + return "failed" + } + var res struct { + IsError bool `json:"isError"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` + } + switch v := result.(type) { + case map[string]any: + if e, _ := v["isError"].(bool); !e { + return "" + } + case nil: + return "" + } + b, err := json.Marshal(result) + if err != nil || json.Unmarshal(b, &res) != nil || !res.IsError { + return "" + } + for _, c := range res.Content { + if c.Type == "text" && strings.TrimSpace(c.Text) != "" { + return c.Text + } + } + return "failed" +} + +// imageMCPCalled writes the row of a call the Magpie Image server an +// agent runs answered (MCPCalledMethod). +func imageMCPCalled(r *http.Request, raw json.RawMessage) (any, map[string]any) { + var c MCPCalled + if err := json.Unmarshal(raw, &c); err != nil { + return nil, map[string]any{"code": -32602, "message": "invalid params: " + err.Error()} + } + switch c.Tool { + case GenerateImageTool, GenerateVideoTool, GenerationResultTool: + default: + return nil, map[string]any{"code": -32602, "message": "no tool " + c.Tool + " is Magpie Image's"} + } + took := time.Duration(max(c.Millis, 0)) * time.Millisecond + prov, model, _ := strings.Cut(c.Model, "/") + if model == "" { + prov = "" + } + logMCPCall(r, "", imageServerName, "stdio", c.Tool, prov, model, time.Now().Add(-took), took, c.Error) + return map[string]any{}, nil +} diff --git a/internal/gateway/mcp_calls_test.go b/internal/gateway/mcp_calls_test.go new file mode 100644 index 000000000..ba8cad96b --- /dev/null +++ b/internal/gateway/mcp_calls_test.go @@ -0,0 +1,266 @@ +package gateway + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// loggedRows is every row of usage.jsonl, the MCP ones included, which +// usage.Load leaves out (they ride the probe lane), and the file's text. +func loggedRows(t *testing.T) ([]usage.Record, string) { + t.Helper() + b, err := os.ReadFile(usage.Path()) + if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + var out []usage.Record + sc := bufio.NewScanner(strings.NewReader(string(b))) + sc.Buffer(make([]byte, 1<<20), 1<<24) + for sc.Scan() { + var r usage.Record + if json.Unmarshal(sc.Bytes(), &r) == nil { + out = append(out, r) + } + } + return out, string(b) +} + +func mcpRows(t *testing.T) []usage.Record { + t.Helper() + all, _ := loggedRows(t) + var out []usage.Record + for _, r := range all { + if r.Source == usage.SourceMCP { + out = append(out, r) + } + } + return out +} + +// A tool call to the gateway's image MCP server is a row of the request +// log (ferock on Discord): the tool, its server, the provider and model +// the drawing went to, how long it took, and nothing of its arguments. +// The drawing's own request is a model row beside it, and only that one +// counts. +func TestMCPToolCallIsARequestRow(t *testing.T) { + s, _ := easeled(t) + t.Setenv("MAGPIE_PUBLIC_URL", "") + t.Cleanup(s.imageStore.running.Wait) + h := lanGuard(s.Handler()) + const prompt = "a magpie on a secret-plum-branch" + m := readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerateImageTool, map[string]any{"prompt": prompt}), "User-Agent", "claude-cli/2.1.0 (external, cli)")) + if m.Result.IsError { + t.Fatalf("drawn: %+v", m) + } + rows := mcpRows(t) + if len(rows) != 1 { + t.Fatalf("MCP rows %+v", rows) + } + r := rows[0] + if r.Requested != GenerateImageTool || r.Host != imageServerName || r.Kind != usage.KindMCP || r.Endpoint != ImageMCPPath || + r.Provider != "art" || r.Model == "" || r.Error != "" || r.Operation != "execute_tool" || r.Time.IsZero() { + t.Fatalf("row %+v", r) + } + if !r.IsProbe() { + t.Fatal("an MCP row is counted") + } + all, text := loggedRows(t) + if strings.Contains(text, "secret-plum-branch") { + t.Fatalf("the prompt was kept: %s", text) + } + // the drawing is a model row of its own, the one Load lists + if len(all) < 2 || len(usage.Load(r.Time.Add(-1))) == 0 { + t.Fatalf("no model row beside it: %+v", all) + } + for _, x := range usage.Load(r.Time.Add(-1)) { + if x.Source == usage.SourceMCP { + t.Fatalf("Load lists the MCP row %+v", x) + } + } +} + +// A call that fails says so, and a call to a tool the server has not is +// a row too, failed. +func TestMCPToolCallFailureIsKept(t *testing.T) { + s, _ := easeled(t) + t.Setenv("MAGPIE_PUBLIC_URL", "") + t.Cleanup(s.imageStore.running.Wait) + h := lanGuard(s.Handler()) + readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerationResultTool, map[string]any{"id": "img_nothing"}))) + w := imagePost(h, "127.0.0.1:5000", imageToolCall("draw_me", map[string]any{"prompt": "x"})) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + rows := mcpRows(t) + if len(rows) != 2 || rows[0].Requested != GenerationResultTool || !strings.Contains(rows[0].Error, "no image is being made") || + rows[1].Requested != "draw_me" || rows[1].Error == "" { + t.Fatalf("rows %+v", rows) + } +} + +// generation_result is of the model that started the job it waits on. +func TestMCPGenerationResultNamesTheJobsModel(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_PUBLIC_URL", "") + gate := make(chan struct{}) + e := &easel{} + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-gate + e.ServeHTTP(w, r) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "art", Name: "Art", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-image-1"}}); err != nil { + t.Fatal(err) + } + s := New() + opened := false + open := func() { + if !opened { + opened = true + close(gate) + } + } + t.Cleanup(s.imageStore.running.Wait) + t.Cleanup(open) + h := lanGuard(s.Handler()) + was := imageMCPWithin + t.Cleanup(func() { imageMCPWithin = was }) + imageMCPWithin = 10 * time.Millisecond + m := readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerateImageTool, map[string]any{"prompt": "a magpie"}))) + text := m.Result.Content[0].Text + i := strings.Index(text, `"img_`) + if m.Result.IsError || i < 0 { + t.Fatalf("still drawing: %+v", m) + } + id := strings.Trim(strings.Fields(text[i:])[0], `".,`) + open() + imageMCPWithin = time.Minute + m = readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerationResultTool, map[string]any{"id": id}))) + if m.Result.IsError { + t.Fatalf("waited on: %+v", m) + } + rows := mcpRows(t) + if len(rows) != 2 || rows[1].Requested != GenerationResultTool || rows[1].Provider != "art" || rows[1].Model != "gpt-image-1" { + t.Fatalf("rows %+v", rows) + } +} + +// A hub call's row names the Library server the tool is of and the agent +// the hub is mounted for; its arguments are not kept. +func TestMCPHubCallIsARequestRow(t *testing.T) { + fresh(t) + f := &fakeHub{on: true, tools: map[string][]HubTool{ + "claude": {{Server: "github", Tool: "create_issue", Spec: hubSpec("create_issue")}, {Server: "fs", Tool: "read", Spec: hubSpec("read")}}, + }} + f.call = func(_ context.Context, server, tool string) (json.RawMessage, error) { + if server == "fs" { + return nil, errors.New("fs is down") + } + return json.RawMessage(`{"content":[{"type":"text","text":"done"}]}`), nil + } + withHub(t, f) + h := lanGuard(New().Handler()) + readMCP(t, hubPost(h, "claude", here, toolsCall("github__create_issue", `{"q":"secret-plum-title"}`))) + readMCP(t, hubPost(h, "claude", here, toolsCall("fs__read", `{"q":"x"}`))) + readMCP(t, hubPost(h, "claude", here, toolsList)) // not a call: no row + rows := mcpRows(t) + if len(rows) != 2 { + t.Fatalf("rows %+v", rows) + } + if r := rows[0]; r.Requested != "github__create_issue" || r.Host != "github" || r.Agent != "claude" || r.Error != "" || r.Provider != "" { + t.Fatalf("hub row %+v", r) + } + if r := rows[1]; r.Host != "fs" || !strings.Contains(r.Error, "fs is down") { + t.Fatalf("failed hub row %+v", r) + } + if _, text := loggedRows(t); strings.Contains(text, "secret-plum-title") { + t.Fatalf("arguments kept: %s", text) + } +} + +// The web search server's call is a row of magpie-web-search. +func TestMCPSearchCallIsARequestRow(t *testing.T) { + fresh(t) + apis := newSearchAPIs(t) + if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil { + t.Fatal(err) + } + h := lanGuard(New().Handler()) + readMCP(t, mcpPost(h, here, mcpSearchCall)) + rows := mcpRows(t) + if len(rows) != 1 || rows[0].Requested != "web_search" || rows[0].Host != "magpie-web-search" || rows[0].Error != "" { + t.Fatalf("rows %+v", rows) + } + if _, text := loggedRows(t); strings.Contains(text, "latest go") { + t.Fatalf("the query was kept: %s", text) + } +} + +// The Magpie Image server an agent runs reports each call it answered +// (MCPCalledMethod): a row of its tool and model, at "stdio"; a tool not +// Magpie Image's is turned away. +func TestMCPCalledFromStdioIsARow(t *testing.T) { + s, _ := easeled(t) + h := lanGuard(s.Handler()) + body := func(c MCPCalled) string { + b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 9, "method": MCPCalledMethod, "params": c}) + return string(b) + } + m := readMCP(t, imagePost(h, "127.0.0.1:5000", body(MCPCalled{Tool: GenerateImageTool, Millis: 1500, Model: "art/gpt-image-1"}))) + if m.Error != nil { + t.Fatalf("reported: %+v", m) + } + readMCP(t, imagePost(h, "127.0.0.1:5000", body(MCPCalled{Tool: GenerateVideoTool, Millis: 20, Error: "no model makes videos"}))) + if m := readMCP(t, imagePost(h, "127.0.0.1:5000", body(MCPCalled{Tool: "rm_rf"}))); m.Error == nil || m.Error.Code != -32602 { + t.Fatalf("another tool: %+v", m) + } + rows := mcpRows(t) + if len(rows) != 2 { + t.Fatalf("rows %+v", rows) + } + if r := rows[0]; r.Requested != GenerateImageTool || r.Host != imageServerName || r.Endpoint != "stdio" || r.Provider != "art" || r.Model != "gpt-image-1" || r.Millis != 1500 { + t.Fatalf("row %+v", r) + } + if r := rows[1]; r.Provider != "" || r.Error != "no model makes videos" { + t.Fatalf("failed row %+v", r) + } +} + +// A key's MCP tool call adds nothing to what its limit counts, as read +// back from usage.jsonl: the model requests it made are its calls. +func TestMCPCallCountsInNoKeyLimit(t *testing.T) { + fresh(t) + f := &fakeHub{on: true, tools: map[string][]HubTool{"claude": {{Server: "fs", Tool: "read", Spec: hubSpec("read")}}}} + withHub(t, f) + keys, secrets := newCaller(t, "Capped") + lim := &access.Limit{Period: "day", Tokens: 700} + setLimit(t, keys[0].ID, lim) + h := lanGuard(New().Handler()) + st := budget.Of(access.Key{ID: keys[0].ID, Limit: lim}, time.Now()) + if st == nil || st.Calls != 0 { + t.Fatalf("before: %+v", st) + } + m := readMCP(t, hubPost(h, "claude", here, toolsCall("fs__read", `{"q":"x"}`), "Authorization", "Bearer "+secrets[0])) + if m.Result.IsError || len(f.ran()) != 1 { + t.Fatalf("call: %+v %v", m, f.ran()) + } + if rows := mcpRows(t); len(rows) != 1 || rows[0].CallerKeyID != keys[0].ID { + t.Fatalf("rows %+v", rows) + } + if st := budget.Of(access.Key{ID: keys[0].ID, Limit: lim}, time.Now()); st == nil || st.Calls != 0 { + t.Fatalf("an MCP call counted: %+v", st) + } +} diff --git a/internal/gateway/search_mcp.go b/internal/gateway/search_mcp.go index ab11837f5..eb8e2b299 100644 --- a/internal/gateway/search_mcp.go +++ b/internal/gateway/search_mcp.go @@ -53,13 +53,15 @@ type mcpMessage struct { } func (s *Server) searchMCP(w http.ResponseWriter, r *http.Request) { - serveMCP(w, r, "magpie's web search", 1<<20, s.searchMCPCall) + serveMCP(w, r, "magpie's web search", "magpie-web-search", 1<<20, s.searchMCPCall) } // serveMCP answers the JSON-RPC messages POSTed to one of magpie's own MCP -// servers (what names it in a refusal) with call, a body up to limit bytes -// long: guarded as a gateway route, and a web page turned away. -func serveMCP(w http.ResponseWriter, r *http.Request, what string, limit int64, call func(*http.Request, mcpMessage) (any, map[string]any)) { +// servers (what names it in a refusal, server in the request log) with +// call, a body up to limit bytes long: guarded as a gateway route, and a +// web page turned away. Each tools/call is a row of the request log +// (callMCPTool). +func serveMCP(w http.ResponseWriter, r *http.Request, what, server string, limit int64, call func(*http.Request, mcpMessage) (any, map[string]any)) { if !local(r) && !sharedWith(r) { http.Error(w, what+" is served to another machine only when magpie is shared on the local network and the request carries a gateway key (Authorization: Bearer )", http.StatusForbidden) return @@ -103,7 +105,13 @@ func serveMCP(w http.ResponseWriter, r *http.Request, what string, limit int64, if len(m.ID) == 0 || bytes.Equal(m.ID, []byte("null")) || m.Method == "" { continue } - result, rpcErr := call(r, m) + var result any + var rpcErr map[string]any + if m.Method == "tools/call" { + result, rpcErr = callMCPTool(r, server, m, call) + } else { + result, rpcErr = call(r, m) + } reply := map[string]any{"jsonrpc": "2.0", "id": m.ID} if rpcErr != nil { reply["error"] = rpcErr diff --git a/internal/gateway/tools_mcp.go b/internal/gateway/tools_mcp.go index f64f617fd..f2cca00ea 100644 --- a/internal/gateway/tools_mcp.go +++ b/internal/gateway/tools_mcp.go @@ -45,7 +45,7 @@ var ( const errToolsOff = "magpie's Plugin tools plugin is off, so no plugin's tool runs; turn it on in magpie's Settings → Plugins" func (s *Server) toolsMCP(w http.ResponseWriter, r *http.Request) { - serveMCP(w, r, "magpie's plugin tools", toolsMCPBody, s.toolsMCPCall) + serveMCP(w, r, "magpie's plugin tools", "magpie-tools", toolsMCPBody, s.toolsMCPCall) } // mcpTool is one plugin tool as the server names it. diff --git a/internal/gateway/vision_mcp.go b/internal/gateway/vision_mcp.go index 3b4ce6a38..bda19b20e 100644 --- a/internal/gateway/vision_mcp.go +++ b/internal/gateway/vision_mcp.go @@ -59,7 +59,7 @@ var visionMCPSchema = map[string]any{ } func (s *Server) visionMCP(w http.ResponseWriter, r *http.Request) { - serveMCP(w, r, "magpie's image recognition", visionMCPBody, s.visionMCPCall) + serveMCP(w, r, "magpie's image recognition", "magpie-vision", visionMCPBody, s.visionMCPCall) } // visionMCPCall answers one request: its result, or its JSON-RPC error. diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 46e835f93..74edf10fd 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1520,7 +1520,7 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske .led .src.access-subscription { --badge-ink: var(--tk-k); } .led .src.proto { --badge-ink: var(--muted); font-weight: 500; } .led .src.reported { --badge-ink: var(--tk-o); } -.led .src.probe { --badge-ink: var(--muted); } +.led .src.probe, .led .src.mcp { --badge-ink: var(--muted); } .led .duration { font-weight: 550; } .led .duration-fast { color: var(--tk-s); } .led .duration-slow { color: var(--amber); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 8292cc5fe..b5dd37f2d 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3498,6 +3498,7 @@ const I18N = { "Luna Reserve": "Luna 储备", "Suggestions": "提示词建议", "Image description": "图片描述", + "MCP tool": "MCP 工具", "Routing classifier": "路由分类器", "magpie's own": "magpie 自身", "{n} request in this period was magpie's own": "此期间有 {n} 个请求是 magpie 自身发出的", @@ -7638,6 +7639,7 @@ const I18N = { "Luna Reserve": "Luna 儲備", "Suggestions": "提示詞建議", "Image description": "圖片描述", + "MCP tool": "MCP 工具", "Routing classifier": "路由分類器", "magpie's own": "magpie 自身", "{n} request in this period was magpie's own": "此期間有 {n} 個請求是 magpie 自身發出的", @@ -11796,6 +11798,7 @@ const I18N = { "Luna Reserve": "Luna Reserve", "Suggestions": "提案", "Image description": "画像の説明", + "MCP tool": "MCP ツール", "Routing classifier": "ルーティング分類器", "magpie's own": "magpie 自身", "{n} request in this period was magpie's own": "この期間のリクエストのうち {n} 件は magpie 自身のものです", @@ -15962,6 +15965,7 @@ const I18N = { "Luna Reserve": "Luna Reserve", "Suggestions": "Vorschläge", "Image description": "Bildbeschreibung", + "MCP tool": "MCP-Tool", "Routing classifier": "Routing-Klassifikator", "magpie's own": "von magpie selbst", "{n} request in this period was magpie's own": "{n} Anfrage in diesem Zeitraum kam von magpie selbst", diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index e7d79ec54..f7f6ffc04 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -79,6 +79,7 @@ magpie.strings({ "reported by apps": "由应用上报", "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由发起请求的应用通过 POST /v1/magpie/usage/requests 上报:这次请求直接发给了服务商,没有经过 magpie。", "magpie sent this itself to test the provider (Test, Detect APIs or a model list), not for an agent. It is not counted in any total.": "这是 magpie 自己为测试供应商发出的请求(测试、检测协议或模型列表),不是 agent 发出的,不计入任何汇总。", + "{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.": "{agent} 调用了 magpie 的 MCP 服务器 {server} 的工具 {tool}。不保存调用参数,也不计入任何汇总:它发出的模型请求各有自己的一行。", "all requests": "全部请求", "Show only these requests": "只看这些请求", "Show every request again": "重新显示全部请求", @@ -314,6 +315,7 @@ magpie.strings({ "reported by apps": "由應用程式回報", "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由發出請求的應用程式透過 POST /v1/magpie/usage/requests 回報:這次請求直接送往服務商,沒有經過 magpie。", "magpie sent this itself to test the provider (Test, Detect APIs or a model list), not for an agent. It is not counted in any total.": "這是 magpie 自己為測試供應商發出的請求(測試、檢測協議或模型列表),不是 agent 發出的,不計入任何彙總。", + "{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.": "{agent} 呼叫了 magpie 的 MCP 伺服器 {server} 的工具 {tool}。不保存呼叫參數,也不計入任何彙總:它發出的模型請求各有自己的一列。", "all requests": "全部請求", "Show only these requests": "只看這些請求", "Show every request again": "重新顯示全部請求", @@ -549,6 +551,7 @@ magpie.strings({ "reported by apps": "アプリからの報告", "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "リクエストを送ったアプリが POST /v1/magpie/usage/requests で報告したものです。このリクエストは magpie を経由せず、直接ベンダーに送られました。", "magpie sent this itself to test the provider (Test, Detect APIs or a model list), not for an agent. It is not counted in any total.": "プロバイダをテストするために magpie 自身が送ったリクエストです(テスト、API を検出、モデル一覧)。エージェントのものではなく、どの合計にも数えません。", + "{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.": "{agent} が magpie の MCP サーバー {server} のツール {tool} を呼び出しました。引数は保存せず、どの合計にも数えません。これが送ったモデルへのリクエストはそれぞれ別の行です。", "all requests": "すべてのリクエスト", "Show only these requests": "これらのリクエストだけを表示", "Show every request again": "すべてのリクエストを再表示", @@ -784,6 +787,7 @@ magpie.strings({ "reported by apps": "von Apps gemeldet", "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "Von der App gemeldet, die die Anfrage gestellt hat (POST /v1/magpie/usage/requests): Die Anfrage ging direkt an den Anbieter, nicht über magpie.", "magpie sent this itself to test the provider (Test, Detect APIs or a model list), not for an agent. It is not counted in any total.": "magpie hat dies selbst gesendet, um den Anbieter zu testen (Testen, APIs erkennen oder eine Modellliste), nicht für einen Agent. Es zählt in keiner Summe.", + "{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.": "{agent} hat das Tool {tool} von magpies MCP-Server {server} aufgerufen. Seine Argumente werden nicht gespeichert, und es zählt in keiner Summe: die Modellanfragen, die es gesendet hat, sind eigene Zeilen.", "all requests": "alle Anfragen", "Show only these requests": "Nur diese Anfragen zeigen", "Show every request again": "Wieder alle Anfragen zeigen", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index f25caec50..2fc24e097 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -2274,6 +2274,8 @@ function renderLedger() { // one that tested the provider (the editor's Test, Detect APIs, a model // list) is counted nowhere, and says so (neiko on Discord) const probe = r.source === "probe"; + // an agent's call to a tool of magpie's MCP servers (ferock on Discord) + const mcp = r.source === "mcp"; if (r.agent === "magpie") { const own = ownBadge(); if (probe) own.title = probeWhy(); @@ -2289,7 +2291,9 @@ function renderLedger() { // resolved to a provider's name, which would promote an unknown request // to an official provider — and the row keeps saying it is a local // session. A row whose file names none says only that. - const where = local ? (r.session_account || r.session_provider || t("Local session")) : t(r.providerName) + (r.host ? " · " + r.host : ""); + const where = local ? (r.session_account || r.session_provider || t("Local session")) + : mcp ? [r.providerName && t(r.providerName), r.host].filter(Boolean).join(" · ") || "—" + : t(r.providerName) + (r.host ? " · " + r.host : ""); const wc = td(el("div", "where-name", where), "where", where); const badges = el("div", "source-badges"); if (local && r.session_account && r.session_official_login) { @@ -2327,6 +2331,11 @@ function renderLedger() { k.title = probeWhy(); badges.append(k); } + if (mcp) { + const k = el("span", "src mcp", "MCP"); + k.title = t("{agent} called the tool {tool} of magpie's MCP server {server}. Its arguments are not kept, and it is not counted in any total: the model requests it made are rows of their own.", { agent: name, tool: r.req || "—", server: r.host || "magpie" }); + badges.append(k); + } if (badges.childElementCount) wc.append(badges); // the model sent is what the gateway sent the vendor: a session file has none // The log names a model, but does not capture the outbound HTTP request. @@ -2374,7 +2383,7 @@ function renderLedger() { const st = el("span", "st"); // a status when the gateway logged the call; a session file has none, // and says only whether it went well - let word = r.status ? String(r.status) : r.source === "log" ? (bad ? r.err_type || t("Failed") : t("Succeeded")) : "—"; + let word = r.status ? String(r.status) : r.source === "log" || mcp ? (bad ? r.err_type || t("Failed") : t("Succeeded")) : "—"; if (r.status && bad && r.err_type) word += " · " + r.err_type; if (r.handed_on) word += " · " + t("handed on"); else if (r.tries > 1) word += " · " + t("{n} tries", { n: r.tries }); diff --git a/internal/gui/assets/purposes.js b/internal/gui/assets/purposes.js index 661504cc4..0a02ecd22 100644 --- a/internal/gui/assets/purposes.js +++ b/internal/gui/assets/purposes.js @@ -1,107 +1,2 @@ // Code generated by go generate ./internal/usage; DO NOT EDIT. -const REQUEST_KINDS = { - "agent_job": { - "purpose": "kind:collab_spawn", - "name": "Subagent" - }, - "ambient_suggestion_safety": { - "purpose": "kind:ambient_suggestions", - "name": "Suggestions" - }, - "ambient_suggestions": { - "purpose": "kind:ambient_suggestions", - "name": "Suggestions" - }, - "api_detect": { - "purpose": "kind:api_detect", - "name": "Detect APIs" - }, - "auto_review": { - "purpose": "kind:guardian", - "name": "Approval check" - }, - "collab_spawn": { - "purpose": "kind:collab_spawn", - "name": "Subagent" - }, - "compact": { - "purpose": "kind:compact", - "name": "Compaction" - }, - "composer_predictions": { - "purpose": "kind:composer_predictions", - "name": "Prediction" - }, - "guardian": { - "purpose": "kind:guardian", - "name": "Approval check" - }, - "guardian_review": { - "purpose": "kind:guardian", - "name": "Approval check" - }, - "luna_reserve": { - "purpose": "kind:luna_reserve", - "name": "Luna Reserve" - }, - "memgen": { - "purpose": "kind:memory_consolidation", - "name": "Memory" - }, - "memory": { - "purpose": "kind:memory_consolidation", - "name": "Memory" - }, - "memory_consolidation": { - "purpose": "kind:memory_consolidation", - "name": "Memory" - }, - "model_list": { - "purpose": "kind:model_list", - "name": "Model list" - }, - "provider_test": { - "purpose": "kind:provider_test", - "name": "Test" - }, - "review": { - "purpose": "kind:review", - "name": "Review" - }, - "routing": { - "purpose": "kind:routing", - "name": "Routing classifier" - }, - "thread_description": { - "purpose": "kind:thread_description", - "name": "Description" - }, - "thread_spawn": { - "purpose": "kind:collab_spawn", - "name": "Subagent" - }, - "thread_title": { - "purpose": "kind:thread_title", - "name": "Title" - }, - "thread_title_reconsideration": { - "purpose": "kind:thread_title", - "name": "Title" - }, - "title": { - "purpose": "kind:thread_title", - "name": "Title" - }, - "title_generation": { - "purpose": "kind:thread_title", - "name": "Title" - }, - "vision": { - "purpose": "kind:vision", - "name": "Image description" - }, - "web_search": { - "purpose": "kind:web_search", - "name": "Web search" - } -}; +const REQUEST_KINDS = {"agent_job":{"purpose":"kind:collab_spawn","name":"Subagent"},"ambient_suggestion_safety":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"ambient_suggestions":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"api_detect":{"purpose":"kind:api_detect","name":"Detect APIs"},"auto_review":{"purpose":"kind:guardian","name":"Approval check"},"collab_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"compact":{"purpose":"kind:compact","name":"Compaction"},"composer_predictions":{"purpose":"kind:composer_predictions","name":"Prediction"},"guardian":{"purpose":"kind:guardian","name":"Approval check"},"guardian_review":{"purpose":"kind:guardian","name":"Approval check"},"luna_reserve":{"purpose":"kind:luna_reserve","name":"Luna Reserve"},"mcp":{"purpose":"kind:mcp","name":"MCP tool"},"memgen":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory_consolidation":{"purpose":"kind:memory_consolidation","name":"Memory"},"model_list":{"purpose":"kind:model_list","name":"Model list"},"provider_test":{"purpose":"kind:provider_test","name":"Test"},"review":{"purpose":"kind:review","name":"Review"},"routing":{"purpose":"kind:routing","name":"Routing classifier"},"thread_description":{"purpose":"kind:thread_description","name":"Description"},"thread_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"thread_title":{"purpose":"kind:thread_title","name":"Title"},"thread_title_reconsideration":{"purpose":"kind:thread_title","name":"Title"},"title":{"purpose":"kind:thread_title","name":"Title"},"title_generation":{"purpose":"kind:thread_title","name":"Title"},"vision":{"purpose":"kind:vision","name":"Image description"},"web_search":{"purpose":"kind:web_search","name":"Web search"}}; diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 49ee0e5f7..1279b84d4 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_317_705 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30) - coreScriptBudget = 1_539_423 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30) + coreScriptBudget = 1_538_975 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/genpurposes/main.go b/internal/gui/genpurposes/main.go index 43cfc3a7f..50db301f0 100644 --- a/internal/gui/genpurposes/main.go +++ b/internal/gui/genpurposes/main.go @@ -13,7 +13,7 @@ import ( func main() { out := flag.String("out", "", "JavaScript asset to write") flag.Parse() - b, err := json.MarshalIndent(usage.PurposeKinds(), "", " ") + b, err := json.Marshal(usage.PurposeKinds()) if err != nil { log.Fatal(err) } diff --git a/internal/gui/tests/usage-ledger-mcp.test.cjs b/internal/gui/tests/usage-ledger-mcp.test.cjs new file mode 100644 index 000000000..24e3a72a1 --- /dev/null +++ b/internal/gui/tests/usage-ledger-mcp.test.cjs @@ -0,0 +1,123 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An agent's call to a tool of magpie's own MCP servers (ferock on +// Discord) is a row of the Requests tab: an "MCP" badge, the tool's name +// as the model asked for, the server it is of beside the provider, the +// model it used, how long it took and whether it worked; its tooltip says +// its arguments are not kept and it counts nowhere. The Purpose filter +// names it. In every language, Chromium and WebKit, wide and narrow, +// light and dark; no backend, the API is faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const tot = (calls, tokens, cost) => ({ calls, errors: 0, input: tokens * 0.2, output: tokens * 0.1, cache_write: 0, cache_read: tokens * 0.7, cost }); +const ROW = { t: new Date().toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", provider: "anthropic", providerName: "Claude", model: "claude-sonnet-5", in: 2, out: 600, cache_write: 0, cache_read: 3900, ms: 2380, status: 200, cost: 0.08, priced: true }; +const MCP = { ...ROW, provider: "art", providerName: "Art", model: "gpt-image-1", req: "generate_image", host: "magpie-image", in: 0, out: 0, cache_read: 0, ms: 8400, status: 0, cost: 0, priced: false, source: "mcp", kind: "mcp", endpoint: "/v1/magpie/mcp/image" }; +const FAILED = { ...MCP, t: new Date(Date.now() - 60000).toISOString(), provider: "", providerName: "", model: "", req: "github__create_issue", host: "github", ms: 40, err: "github is down" }; + +function page(q, called) { + const rows = [ROW, ...(called ? [MCP, FAILED] : [])]; + return { + period: "today", rows, offset: 0, total: rows.length, ...tot(1, 4500, 0.08), reasoning: 0, unpriced: 0, + bucket: "hour", series: [], by: { provider: [], agent: [], model: [] }, + agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], providers: [{ id: "anthropic", name: "Claude", icon: "claudecode-color" }], + through: tot(1, 4500, 0.08), direct: tot(0, 0, 0), purposes: called ? ["kind:mcp", "unmarked"] : ["unmarked"], + }; +} + +function server(lang, theme, called, asked) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"${theme}",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme }, fx: { rate: 7.2, at: new Date().toISOString() } }); + if (url.pathname === "/api/usage/requests") { asked.push(url.searchParams); return json(page(url.searchParams, called)); } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage") return json({ calls: 1, errors: 0, input: 1, output: 1, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 1, bucket: "day", series: [], agents: [], models: [], path: "~/.config/magpie/usage.jsonl" }); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] }); + if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// the purpose's name, a word of the tooltip that says it counts nowhere, +// and the status words +const L = { + en: { purpose: "MCP tool", why: "not counted in any total", ok: "Succeeded", bad: "Failed" }, + zh: { purpose: "MCP 工具", why: "不计入任何汇总", ok: "成功", bad: "失败" }, + "zh-TW": { purpose: "MCP 工具", why: "不計入任何彙總", ok: "成功", bad: "失敗" }, + ja: { purpose: "MCP ツール", why: "どの合計にも数えません", ok: "成功", bad: "失敗" }, + de: { purpose: "MCP-Tool", why: "zählt in keiner Summe", ok: "Erfolgreich", bad: "Fehlgeschlagen" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": an MCP tool call is a row of its own", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const shots = process.env.ARTIFACT_DIR; + if (shots) await fs.mkdir(shots, { recursive: true }); + + const open = async (lang, { theme = "light", width = 1180, called = true } = {}) => { + const errors = [], asked = []; + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + t.after(() => context.close()); + const p = await context.newPage(); + p.setDefaultTimeout(5000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang, theme, called, asked)); + await p.goto("http://magpie.test/"); + await p.locator('[data-view="usage"]').first().click(); + await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + await p.locator("#ledVia .blk").first().waitFor(); + return { p, errors }; + }; + + for (const lang of Object.keys(L)) { + const w = L[lang]; + for (const width of [1180, 420]) { + await t.test(`${lang} at ${width}`, async () => { + const { p, errors } = await open(lang, { width, theme: width < 600 ? "dark" : "light" }); + const badge = p.locator(".led .src.mcp"); + await badge.first().waitFor(); + assert.equal(await badge.count(), 2); + assert.equal(await badge.first().textContent(), "MCP"); + const why = await badge.first().getAttribute("title"); + assert(why.includes(w.why) && why.includes("generate_image") && why.includes("magpie-image") && why.includes("Claude Code"), why); + // the model row has none, and neither is a probe + assert.equal(await p.locator(".led .src.probe").count(), 0); + const drawn = p.locator(".led tr.led-row", { has: p.locator(".src.mcp") }).first(); + const text = await drawn.textContent(); + assert(text.includes("generate_image") && text.includes("gpt-image-1") && text.includes("magpie-image"), text); + const failed = p.locator(".led tr.led-row", { hasText: "github__create_issue" }); + { + assert((await drawn.locator(".st").textContent()).startsWith(w.ok)); + assert((await failed.locator(".st").textContent()).startsWith(w.bad)); + } + // the purpose picker names it in the page's language + assert.equal(await p.evaluate(() => purposeOptions(["kind:mcp"], "")[0].name), w.purpose); + // no coloured stripe down its side, and the page doesn't scroll sideways + assert(parseFloat(await badge.first().evaluate((b) => getComputedStyle(b).borderLeftWidth)) <= 1); + assert(await p.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), "no sideways scroll"); + if (shots) await p.screenshot({ path: path.join(shots, `mcp-${engine}-${lang}-${width}.png`) }); + assert.deepEqual(errors, []); + }); + } + } + + await t.test("no MCP call: no badge", async () => { + const { p, errors } = await open("en", { called: false }); + await p.locator(".led tr", { hasText: "claude-sonnet-5" }).first().waitFor(); + assert.equal(await p.locator(".led .src.mcp").count(), 0); + assert.deepEqual(errors, []); + }); + }); +} diff --git a/internal/imagemcp/imagemcp.go b/internal/imagemcp/imagemcp.go index e421f9b64..08316aba2 100644 --- a/internal/imagemcp/imagemcp.go +++ b/internal/imagemcp/imagemcp.go @@ -144,10 +144,12 @@ type job struct { done chan struct{} text string err error + // model is the one the gateway named, provider/model: set by run + model string } // start runs run as a job of tool. -func (s *server) start(tool string, run func() (string, error)) *job { +func (s *server) start(tool string, run func(*job) (string, error)) *job { s.mu.Lock() if s.jobs == nil { s.jobs = map[string]*job{} @@ -159,7 +161,7 @@ func (s *server) start(tool string, run func() (string, error)) *job { s.running.Add(1) go func() { defer s.running.Done() - j.text, j.err = run() + j.text, j.err = run(j) close(j.done) }() return j @@ -286,6 +288,9 @@ func (s *server) serve(r io.Reader) error { func (s *server) handle(req rpc) { var result any var rpcErr any + began := time.Now() + var called *gateway.MCPCalled // a tool call, for the gateway's request log + var j *job switch req.Method { case "initialize": var p struct { @@ -330,7 +335,7 @@ func (s *server) handle(req rpc) { rpcErr = map[string]any{"code": -32602, "message": "unknown tool " + p.Name} break } - var j *job + called = &gateway.MCPCalled{Tool: p.Name} if p.Name == resultTool { var a struct { ID string `json:"id"` @@ -348,7 +353,7 @@ func (s *server) handle(req rpc) { if p.Name == videoTool { generate = s.film } - j = s.start(p.Name, func() (string, error) { return generate(p.Arguments) }) + j = s.start(p.Name, func(j *job) (string, error) { return generate(p.Arguments, &j.model) }) } if !s.await(j, p.Meta.ProgressToken) { result = map[string]any{"content": []any{map[string]any{"type": "text", "text": stillGoing(j)}}} @@ -369,6 +374,37 @@ func (s *server) handle(req rpc) { out["result"] = result } s.send(out) + if called != nil { + called.Millis = time.Since(began).Milliseconds() + if j != nil { + select { + case <-j.done: + called.Model = j.model + default: // still being made: the model isn't known yet + } + } + if res, _ := result.(map[string]any); res["isError"] == true { + called.Error = "failed" + if c, _ := res["content"].([]any); len(c) > 0 { + if t, _ := c[0].(map[string]any)["text"].(string); t != "" { + called.Error = t + } + } + } + s.report(*called) + } +} + +// report tells the gateway of a tool call this server answered, for its +// request log (gateway.MCPCalledMethod): in the background, after the +// answer, and a gateway that can't take it (not running, an older magpie) +// is let be. The call's arguments are never sent. +func (s *server) report(c gateway.MCPCalled) { + s.running.Add(1) + go func() { + defer s.running.Done() + s.ask(gateway.MCPCalledMethod, c) + }() } type args struct { @@ -383,8 +419,9 @@ type args struct { } // generate asks the gateway for the images and saves them; what it says is -// where they are. -func (s *server) generate(raw json.RawMessage) (string, error) { +// where they are. used, when not nil, is set to the model the gateway +// named, provider/model. +func (s *server) generate(raw json.RawMessage, used *string) (string, error) { var a args if err := json.Unmarshal(raw, &a); err != nil { return "", err @@ -450,6 +487,9 @@ func (s *server) generate(raw json.RawMessage) (string, error) { } `json:"error"` } json.Unmarshal(data, &out) + if used != nil { + *used = out.Model + } if res.StatusCode != 200 { msg := strings.TrimSpace(string(data)) if out.Error != nil && out.Error.Message != "" { @@ -785,8 +825,9 @@ func gatewaySaid(data []byte) string { } // film asks the gateway to make a video, waits for it and saves it; what -// it says is where it is. -func (s *server) film(raw json.RawMessage) (string, error) { +// it says is where it is. used, when not nil, is set to the model the +// gateway named, provider/model. +func (s *server) film(raw json.RawMessage, used *string) (string, error) { var a filmArgs if err := json.Unmarshal(raw, &a); err != nil { return "", err @@ -851,6 +892,9 @@ func (s *server) film(raw json.RawMessage) (string, error) { if json.Unmarshal(data, &v) != nil || v.ID == "" { return "", fmt.Errorf("no video: the gateway's answer has no id: %s", gatewaySaid(data)) } + if used != nil { + defer func() { *used = v.Model }() + } id, deadline := v.ID, time.Now().Add(videoWait) for v.Status != "completed" { if v.Status == "failed" { diff --git a/internal/imagemcp/imagemcp_test.go b/internal/imagemcp/imagemcp_test.go index 763a62f3b..e836ac002 100644 --- a/internal/imagemcp/imagemcp_test.go +++ b/internal/imagemcp/imagemcp_test.go @@ -199,7 +199,7 @@ func TestGatewayRefusalIsAToolError(t *testing.T) { })) defer up.Close() s := &server{gateway: up.URL, client: http.DefaultClient, agent: "x", pending: map[string]chan rpc{}} - _, err := s.generate(json.RawMessage(`{"prompt":"x"}`)) + _, err := s.generate(json.RawMessage(`{"prompt":"x"}`), nil) if err == nil || !strings.Contains(err.Error(), "Image generation") { t.Fatalf("err = %v", err) } diff --git a/internal/imagemcp/report_test.go b/internal/imagemcp/report_test.go new file mode 100644 index 000000000..b5662e724 --- /dev/null +++ b/internal/imagemcp/report_test.go @@ -0,0 +1,88 @@ +package imagemcp + +import ( + "encoding/json" + "io" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" +) + +// reportGW is gw that keeps the tool calls the server reports. +type reportGW struct { + gw + mu sync.Mutex + calls []string +} + +func (g *reportGW) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == gateway.ImageMCPPath { + b, _ := io.ReadAll(r.Body) + var m struct { + Method string `json:"method"` + Params json.RawMessage `json:"params"` + } + json.Unmarshal(b, &m) + if m.Method == gateway.MCPCalledMethod { + g.mu.Lock() + g.calls = append(g.calls, string(m.Params)) + g.mu.Unlock() + io.WriteString(w, `{"jsonrpc":"2.0","id":1,"result":{}}`) + return + } + modelsMCP(w, b) + return + } + g.gw.ServeHTTP(w, r) +} + +func (g *reportGW) reported(n int) []string { + for end := time.Now().Add(10 * time.Second); time.Now().Before(end); time.Sleep(5 * time.Millisecond) { + g.mu.Lock() + got := append([]string(nil), g.calls...) + g.mu.Unlock() + if len(got) >= n { + return got + } + } + return nil +} + +// Each tool call the Magpie Image server answers is reported to the +// gateway (MCPCalledMethod), for its row in the request log: the tool, +// how long it took, the model the gateway named, and never the prompt. +func TestToolCallsAreReported(t *testing.T) { + g := &reportGW{} + project := t.TempDir() + c := start(t, g, project) + c.call("initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{"roots": map[string]any{}}, "clientInfo": map[string]any{"name": "claude-code", "version": "2.1.0"}}) + r := c.call("tools/call", map[string]any{"name": "generate_image", "arguments": map[string]any{"prompt": "secret-plum-branch"}}) + if r["isError"] == true { + t.Fatalf("%v", r) + } + c.call("tools/call", map[string]any{"name": "generation_result", "arguments": map[string]any{"id": "img_nothing"}}) + got := g.reported(2) + if len(got) != 2 { + t.Fatalf("reported %v", got) + } + by := map[string]gateway.MCPCalled{} + for _, x := range got { + var c gateway.MCPCalled + json.Unmarshal([]byte(x), &c) + by[c.Tool] = c + } + first, second := by["generate_image"], by["generation_result"] + if first.Tool != "generate_image" || first.Model != "art/gpt-image-1" || first.Error != "" || first.Millis < 0 { + t.Fatalf("reported %+v", first) + } + if second.Tool != "generation_result" || second.Error == "" { + t.Fatalf("reported %+v", second) + } + if strings.Contains(strings.Join(got, ""), "secret-plum") { + t.Fatalf("the prompt was reported: %v", got) + } +} diff --git a/internal/usage/log_index.go b/internal/usage/log_index.go index 3d67a2c2d..d2d5dd653 100644 --- a/internal/usage/log_index.go +++ b/internal/usage/log_index.go @@ -82,7 +82,8 @@ var logAppends struct { func (s *logSnapshot) sawHost(r Record) { h, _, _ := strings.Cut(r.Host, " as ") // a subscription's "host as user" h = strings.ToLower(strings.TrimSpace(h)) - if h == "" || r.Provider == "" || strings.EqualFold(r.Provider, h) || r.IsRejected() { + // an MCP tool call's host is its server's name, not a provider's + if h == "" || r.Provider == "" || strings.EqualFold(r.Provider, h) || r.IsRejected() || r.Source == SourceMCP { return } if s.hosts == nil { diff --git a/internal/usage/mcp_calls_test.go b/internal/usage/mcp_calls_test.go new file mode 100644 index 000000000..5aaf8f429 --- /dev/null +++ b/internal/usage/mcp_calls_test.go @@ -0,0 +1,69 @@ +package usage + +import ( + "slices" + "testing" + "time" +) + +// ferock on Discord: an agent's call to a tool of magpie's MCP servers +// (generate_image) is a row of the request log of its own, apart from +// the model requests, picked by the MCP tool purpose, naming the tool, +// its server, the provider and model it used, how long it took and how it +// ended, and counted in nothing: its image request is the call that is. +func TestMCPCallRowsListedNotCounted(t *testing.T) { + reportedHome(t) + spy := &ledgerSpy{} + t.Cleanup(Observe(spy)) + now := time.Now().Add(-time.Hour) + Append(Record{Time: now, Agent: "claude", Provider: "openai", Host: "api.openai.com", Model: "gpt-image-2", Requested: "gpt-image-2", Operation: "generate_content", Endpoint: "/v1/images/generations", Status: 200, Millis: 9000}) + Append(Record{Time: now.Add(time.Second), Agent: "claude", Operation: "execute_tool", Provider: "openai", Model: "gpt-image-2", Requested: "generate_image", + Host: "magpie-image", Millis: 9100, Endpoint: "/mcp/magpie/image", Kind: KindMCP, Source: SourceMCP}) + Append(Record{Time: now.Add(2 * time.Second), Agent: "claude", Operation: "execute_tool", Requested: "github__create_issue", + Host: "github", Millis: 40, Error: "it didn't answer", Endpoint: "/mcp/magpie/hub/claude", Kind: KindMCP, Source: SourceMCP}) + + page := QueryPage(All, Filter{}, 0, 50) + if page.Total != 3 || len(page.Rows) != 3 { + t.Fatalf("total %d, %d rows: %+v", page.Total, len(page.Rows), page.Rows) + } + hub, image := page.Rows[0], page.Rows[1] // newest first + if hub.Source != SourceMCP || !hub.IsProbe() || hub.Requested != "github__create_issue" || hub.Host != "github" || !hub.Failed() || hub.Provider != "" { + t.Fatalf("hub row %+v", hub) + } + if image.Source != SourceMCP || image.Requested != "generate_image" || image.Provider != "openai" || image.Model != "gpt-image-2" || + image.Host != "magpie-image" || image.Millis != 9100 || image.Failed() || image.Endpoint != "/mcp/magpie/image" { + t.Fatalf("image row %+v", image) + } + if page.Sum.Calls != 1 || page.Sum.Errors != 0 || page.Through.Calls != 1 { + t.Fatalf("sum %+v through %+v", page.Sum, page.Through) + } + if !slices.Contains(page.Purposes, "kind:mcp") || PurposeOf(KindMCP) != "kind:mcp" || PurposeKinds()[KindMCP].Name != "MCP tool" { + t.Fatalf("purposes %v", page.Purposes) + } + for dim, shares := range page.By { + for _, s := range shares { + if s.ID == "generate_image" || s.ID == "github__create_issue" || (dim == "provider" && s.Calls != 1) { + t.Fatalf("%s counts a tool call: %+v", dim, shares) + } + } + } + if s := Summarize(All); s.Calls != 1 || s.Errors != 0 { + t.Fatalf("summary %+v", s.Totals) + } + if rs := Load(time.Time{}); len(rs) != 1 { + t.Fatalf("Load %+v", rs) + } + if len(spy.rows) != 1 || spy.rows[0].IsProbe() { + t.Fatalf("observer saw %+v", spy.rows) + } + // the purpose picks the tool calls alone, and counts nothing still + p := QueryPage(All, Filter{Purpose: "kind:mcp"}, 0, 50) + if p.Total != 2 || p.Sum.Calls != 0 || p.Rows[0].Source != SourceMCP || p.Rows[1].Source != SourceMCP { + t.Fatalf("purpose filter: total %d sum %+v rows %+v", p.Total, p.Sum, p.Rows) + } + // a tool call's server is no provider's host: a probe on the host is + // not listed under the provider the tool used + if hosts := readLogSnapshot().hosts; hosts["magpie-image"] != "" || hosts["github"] != "" { + t.Fatalf("hosts %v", hosts) + } +} diff --git a/internal/usage/probes.go b/internal/usage/probes.go index 9f0db4814..a703710a5 100644 --- a/internal/usage/probes.go +++ b/internal/usage/probes.go @@ -18,12 +18,30 @@ import ( // the calls (logSnapshot.probes) so a reader of those never meets it. const SourceProbe = "probe" -// IsProbe is a request magpie sent on its own (SourceProbe). -func (r Record) IsProbe() bool { return r.Source == SourceProbe } +// SourceMCP is Record.Source for an agent's call to a tool of one of +// magpie's own MCP servers: the gateway's (image, vision, web search, +// plugin tools, the MCP hub) and the Magpie Image server an agent runs +// (ferock on Discord). Its Kind is KindMCP, Requested the tool's name as +// it was called, Host the server's, Provider and Model what the tool used +// when it used a model, Millis how long the call took and Error what a +// failed one said. Its arguments are never kept. It rides the probes' +// lane: listed on the request log, told apart there, counted nowhere, as +// the model requests the tool made are rows of their own that are. +const SourceMCP = "mcp" + +// KindMCP is an MCP tool call's Kind, the purpose the request log picks +// them by. +const KindMCP = "mcp" + +// IsProbe is a request magpie sent on its own (SourceProbe), or an MCP +// tool call (SourceMCP): a row listed and counted nowhere. +func (r Record) IsProbe() bool { return r.Source == SourceProbe || r.Source == SourceMCP } // IsProbe is a row of such a request. A packed row keeps the row's Source, // not its record's, so the request log asks the row. -func (r Row) IsProbe() bool { return r.Source == SourceProbe || r.Record.IsProbe() } +func (r Row) IsProbe() bool { + return r.Source == SourceProbe || r.Source == SourceMCP || r.Record.IsProbe() +} // probeRow is a probe's record and where its line ends in the log, as a // gateway row's Order is. @@ -95,6 +113,14 @@ func probeChunk(probes []probeRow, since time.Time, renames provider.Renames, ho c = &rowChunk{} } r := p.Record + if r.Source == SourceMCP { + // a tool call names the provider its gateway call went to, by id + if r.Provider != "" { + r.Provider = renames.Of(r.Provider, r.Time) + } + c.add(Row{Record: r, Source: SourceMCP}, "", p.off, false) + continue + } r.Provider = probeProvider(r, renames, hosts, sites) c.add(Row{Record: r, Source: SourceProbe}, "", p.off, false) } diff --git a/internal/usage/purpose.go b/internal/usage/purpose.go index f1ce325da..0764cf1f7 100644 --- a/internal/usage/purpose.go +++ b/internal/usage/purpose.go @@ -33,6 +33,7 @@ var purposeKinds = func() map[string]PurposeKind { add("Test", "provider_test") // magpie's own (probelog.KindTest) add("Detect APIs", "api_detect") // probelog.KindDetect add("Model list", "model_list") // probelog.KindList + add("MCP tool", KindMCP) // an MCP tool call (SourceMCP) return out }()