usage: an agent's call to magpie's own MCP tools is a row of Requests

ferock (Discord) asked to see calls to magpie's MCP tools, such as
magpie-image's generate_image, generate_video and generation_result, in
Routing > Requests.

Each tools/call to magpie's own MCP servers (image, vision, web search,
tools and the Library hub) is now a row of the request log. The row has
Source and Kind "mcp", the tool as its model, the server as its host,
how long the call took, and its error if it failed. The provider and
model it shows are those of the model requests the call made, collected
through the request's context in appendUsage. generation_result names
the model of the job it answers. The stdio Magpie Image server reports
each call it answered to the gateway as "magpie/toolCalled". That report
carries the tool, ms, model and error, never the prompt.

The arguments are never stored at all, so there is nothing to mask. The
rows go down the probe lane: they are listed, but no total, host list,
budget or key limit counts them. The model requests a call made are rows
of their own.

In the GUI the row reuses the Requests list. It gets a muted "MCP" badge
with a tooltip, the server beside the provider, and a Succeeded/Failed
status. The Purpose filter gains "MCP tool" in every language. There is
no new page, no <select> and no left border.

The core scripts went over their budget with the new purpose.
genpurposes now writes purposes.js as compact JSON, which makes the core
448 bytes smaller than main in all, and coreScriptBudget is lowered to
the new total, 1,538,975. No room is added.

Run on mote, at the rebased head:
- gofmt -l: clean. go vet -tags nogui ./... with GOOS darwin, linux
  and windows: ok.
- go test -tags nogui -timeout 45m: ./internal/usage, ./internal/imagemcp,
  ./internal/usageapi and ./internal/gui ok. internal/budget has no test
  files. ./internal/gateway (805s): every test ok except five Antigravity
  and Codex/Grok tests. They fail the same on a clean origin/main
  3bebc3839 and are filed as #4362.
- GUI, the usage-ledger*, routing-request*, purpose*, i18n* and
  gui-zh/ja/de files (25). On mote, Chromium: 32 of 32 ok; WebKit
  could not launch (10 other sessions' suites on mote). On Linux
  (wsl-run), both engines: 335 of 355 ok. The 20 reds are
  routing-request-model, usage-ledger, -ttft, -chart and
  -open-settled, which fail the same at the parent 1534474c8 (#4120).
  usage-ledger-mcp, purpose-filter and i18n-keys are ok in both.
  The whole GUI suite runs after the push, and each red it finds gets
  an issue.
- At the pushed head, rebased on 0804f2d97: ./internal/gui (the
  budget and purpose asset tests among them), ./internal/usage,
  ./internal/imagemcp and ./internal/usageapi ok, and ./internal/gateway
  -run "MCP|Purpose|Probe" ok.
- usage-ledger-mcp.test.cjs covers 5 languages, widths 1180 and 420,
  light and dark, with no sideways scroll.

Broken by hand. Each break went red:
- sawHost's MCP skip removed: TestMCPCallRowsListedNotCounted (the hosts
  list had magpie-image).
- Row/Record.IsProbe's MCP case removed: the same test (3 calls counted),
  and TestMCPCallCountsInNoKeyLimit (Calls: 1).
- The callMCPTool hook removed: TestMCPToolCallIsARequestRow and its
  siblings (no rows).
- The appendUsage hook removed: the row had no provider or model.
- imagemcp's report removed: TestToolCallsAreReported.
- The gateway's magpie/toolCalled case removed:
  TestMCPCalledFromStdioIsARow.
budget's in-memory counts() now skips these rows too. Breaking only that
stays green, because budget.Of reads the file through usage.Visit, which
already skips probes, and limits count tokens and cost.

Not tried:
- no real agent calling a real vendor's drawing;
- no test run on Windows or Linux;
- the page not checked in the real app or in WebKitGTK.
A generate call that answers while its drawing still runs has no model on
its row. The generation_result row that follows names it.
This commit is contained in:
yetone
2026-10-30 15:00:16 +08:00
parent 0804f2d97d
commit 1bbaded622
26 changed files with 939 additions and 139 deletions
+45
View File
@@ -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
+1
View File
@@ -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: <why>`, 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
+5 -2
View File
@@ -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
+5 -1
View File
@@ -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)
+13 -5
View File
@@ -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():
+4
View File
@@ -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)
}
+197
View File
@@ -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
}
+266
View File
@@ -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)
}
}
+13 -5
View File
@@ -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 <key>)", 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
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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); }
+4
View File
@@ -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",
@@ -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",
+11 -2
View File
@@ -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 });
+1 -106
View File
@@ -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"}};
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -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)
}
@@ -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, []);
});
});
}
+52 -8
View File
@@ -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" {
+1 -1
View File
@@ -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)
}
+88
View File
@@ -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)
}
}
+2 -1
View File
@@ -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 {
+69
View File
@@ -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)
}
}
+29 -3
View File
@@ -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)
}
+1
View File
@@ -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
}()