Files
magpie/internal/gui/builtins_test.go
T
yetone 6ac7032b4b plugins: a community plugin's tools reach every agent through magpie's MCP server /mcp/magpie/tools (P4 tool point)
A plugin's OpenCode `tool` hook ({tool: {name: tool({description, args,
execute})}}) used to reach no agent. Now the plugin host collects each
loaded plugin's tools, turns their zod args (v3/v4 shape or object; a
raw JSON Schema is kept) into JSON Schema, and runs one on a `tool`
call: arguments checked against the tool's own zod first (defaults
filled, a wrong one named), execute raced against ToolTimeout (55s,
ctx.abort fires), the answer as text.

The gateway serves them as an MCP server at /mcp/magpie/tools
(tools_mcp.go, guarded by serveMCP as the search one, 4 MiB body):
tools/list names each <plugin short name>_<tool>, at most 64 chars,
a shared name numbered _2; tools/call holds the call to the calling
key's limit through reserveFor and runs it with the calling agent.
The built-in plugin `tools` ("Plugin tools", Essential) serves
gwtool.PluginTools; off, nothing is listed, a call says the plugin is
off and the host isn't asked. InUse counts plugins that are on and
gave tools, from plugin-tools.json, which the host writes after each
load (whole, only on change), so it never starts Bun; the gateway's
KeepFresh watches that note too. Tool answers go to the calling
agent only, so masking doesn't apply (said in the docs).

The Plugins page lists an on plugin's tools by their MCP names, with
descriptions on hover and a button copying the server's address; a
plugin of tools alone has no Provider chip and isn't said to sign in
to nothing. Not done: a Library featured opt-in entry; wiring is the
copied address.

Docs: docs/subsystems/plugin-tools.md (new), plugin-runtime.md's new
"P4: community plugins at every point" section with the tool row, the
README index, usemagpie.ai/docs/plugins#tools in en, zh, ja with an
example. Strings in zh, zh-TW, ja, de. Example plugin:
internal/plugin/testdata/tools.

Run at this commit's tree (base 4df1ba0c6), each package alone, -p 2:
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  over internal/plugin, gwtool, gateway, plugins/..., gui, pluginrt: ok
- go test ./internal/plugin -run Tool; ./plugins/...; ./internal/pluginrt;
  ./internal/gui -run 'Builtin|Plugins'; ./internal/gateway -timeout 45m
  -run 'ToolsMCP|ServingGates|OwnMCPRejects|SearchOnAndOff|KeyLimitsOnAndOff':
  all ok
- GUI, Chromium and WebKit: every plugin-*.test.cjs, i18n-keys,
  builtins: 461/461 pass; plugin-tools.test.cjs (new) covers en, zh,
  zh-TW, ja, de at 980 and 420 px

Broken by hand, each red, then restored:
- tools/list ignoring the gwtool gate -> TestToolsMCPOff
- tools/call ignoring the gate -> TestToolsMCPOff
- reserveFor removed -> TestToolsMCPHeldToKeyLimit (tool ran)
- collision suffix dropped -> TestToolsMCPServesPluginTools
- ToolsOn ignoring Off -> TestPluginTools
- host arg check removed -> TestPluginTools
- host timeout race not listening -> TestPluginTools (answered at
  5.3s by Go's backstop; the test now bounds it at 4s, and the first
  try at this break was a syntax error that proved nothing)
- GUI listing an off plugin's tools -> plugin-tools.test.cjs

Real use: a built magpie in a sandbox HOME (MAGPIE_ADDR 127.0.0.1:3491,
real Bun), the example plugin added with `magpie plugin add`. curl over
MCP: initialize, tools/list (4 tools, schemas), shout "HI HI (for
curl)", a missing argument as isError naming it, add {"sum":6.5}, fail
"it broke", a foreign Origin 403; plugin-tools.json written. Claude
Code (sandbox CLAUDE_CONFIG_DIR) `claude mcp add --transport http` +
`mcp list`: Connected. Not tried: a model calling a tool through a
real agent turn (no model in the sandbox). Binary and HOME removed.
2026-10-15 22:36:59 +08:00

267 lines
8.4 KiB
Go

package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/settings"
_ "github.com/yetone/magpie/plugins/all"
)
func builtinHome(t *testing.T) http.Handler {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
return Handler(nil, nil)
}
func postBuiltin(h http.Handler, body string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/api/plugins/builtin", strings.NewReader(body)))
return rec
}
// A switch is kept in plugins.yml as the user's own choice and the
// runtime follows it; one in use is refused off and stays on; an unknown
// one is refused.
func TestBuiltinSwitch(t *testing.T) {
h := builtinHome(t)
if _, err := pluginrt.Settle(true); err != nil {
t.Fatal(err)
}
if rec := postBuiltin(h, `{"id":"library","on":true}`); rec.Code != http.StatusOK {
t.Fatalf("library on: %d %s", rec.Code, rec.Body)
} else {
var out []builtinJSON
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if len(out) != 14 {
t.Fatalf("the built-ins: %+v", out)
}
for _, b := range out {
// the Gateway, Routing and Usage pages, the routing strategies,
// the gateway middleware, privacy masking, web search, key
// limits and plugin tools are essential: on in every preset
if b.On != (b.ID == "budget" || b.ID == "library" || b.ID == "gateway" || b.ID == "middleware" || b.ID == "redact" || b.ID == "rotation" || b.ID == "routing" || b.ID == "search" || b.ID == "tools" || b.ID == "usage") || b.On != (b.State == pluginrt.Active) {
t.Fatalf("after library on: %+v", out)
}
}
}
if !pluginrt.Running().Active("library") || pluginrt.Running().Active("sessions") {
t.Fatalf("the runtime: %+v", pluginrt.Running().Statuses())
}
if rec := postBuiltin(h, `{"id":"nope","on":true}`); rec.Code != http.StatusBadRequest {
t.Fatalf("an unknown plugin: %d", rec.Code)
}
// Observability in use: sending to a collector
s := settings.Load()
s.OTel.Enabled = true
s.OTel.Endpoint = "http://127.0.0.1:4318"
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
if rec := postBuiltin(h, `{"id":"otel","on":false}`); rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "in use") {
t.Fatalf("otel off while in use: %d %s", rec.Code, rec.Body)
}
for _, b := range builtinsState() {
if b.ID == "otel" && (!b.On || b.Chosen || b.InUse != 1 || b.Use != "Sending to a collector" || b.Source != pluginrt.FromInUse) {
t.Fatalf("otel in use: %+v", b)
}
}
}
// A plugins.yml that doesn't parse leaves every plugin on, says so, and
// no switch writes over it.
func TestBuiltinBrokenFile(t *testing.T) {
h := builtinHome(t)
if err := os.MkdirAll(filepath.Dir(pluginrt.Path()), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(pluginrt.Path(), []byte("plugins: [\n"), 0o600); err != nil {
t.Fatal(err)
}
for _, b := range builtinsState() {
if b.Broken == "" {
t.Fatalf("not told broken: %+v", b)
}
}
if rec := postBuiltin(h, `{"id":"library","on":false}`); rec.Code != http.StatusBadRequest {
t.Fatalf("switched over a broken file: %d", rec.Code)
}
if b, _ := os.ReadFile(pluginrt.Path()); string(b) != "plugins: [\n" {
t.Fatalf("written over: %q", b)
}
}
// boot.js says what is off before the page paints: everything for a new
// install, nothing for one that ran before.
func TestBootSaysBuiltinsOff(t *testing.T) {
h := builtinHome(t)
boot := func() string {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/boot.js", nil))
return rec.Body.String()
}
if _, err := pluginrt.Settle(false); err != nil {
t.Fatal(err)
}
if b := boot(); !strings.Contains(b, `"featuresOff":[]`) {
t.Fatalf("an existing user: %s", b)
}
if err := pluginrt.SetPreset(pluginrt.PresetEssentials); err != nil {
t.Fatal(err)
}
if err := pluginrt.Set("library", true); err != nil {
t.Fatal(err)
}
if b := boot(); !strings.Contains(b, `"featuresOff":["groups","otel","sessions","warmups"]`) {
t.Fatalf("a new install: %s", b)
}
}
// A plugin's settings are set only as their schema allows, kept in
// plugins.yml, and handed to the page in boot.js; a request says on or
// config, not both.
func TestBuiltinConfig(t *testing.T) {
h := builtinHome(t)
if _, err := pluginrt.Settle(false); err != nil {
t.Fatal(err)
}
gw := func() builtinJSON {
for _, b := range builtinsState() {
if b.ID == "gateway" {
return b
}
}
t.Fatal("no gateway plugin")
return builtinJSON{}
}
if b := gw(); b.Schema == nil || b.Schema.Properties["callsPage"] == nil || b.Config["callsPage"] != int64(20) {
t.Fatalf("before: %+v", b)
}
if rec := postBuiltin(h, `{"id":"gateway","config":{"callsPage":50}}`); rec.Code != http.StatusOK {
t.Fatalf("50: %d %s", rec.Code, rec.Body)
}
if b := gw(); b.Config["callsPage"] != int64(50) || !b.On {
t.Fatalf("after 50: %+v", b)
}
for _, bad := range []string{
`{"id":"gateway","config":{"callsPage":30}}`,
`{"id":"gateway","config":{"other":1}}`,
`{"id":"gateway","on":true,"config":{"callsPage":10}}`,
`{"id":"gateway"}`,
`{"id":"library","config":{"callsPage":10}}`,
} {
if rec := postBuiltin(h, bad); rec.Code != http.StatusBadRequest {
t.Errorf("%s: %d %s", bad, rec.Code, rec.Body)
}
}
if b := gw(); b.Config["callsPage"] != int64(50) {
t.Fatalf("a refused one written: %+v", b)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/boot.js", nil))
if !strings.Contains(rec.Body.String(), `"pluginConfig":{"gateway":{"callsPage":50}}`) {
t.Fatalf("boot.js: %s", rec.Body)
}
}
// Every file a built-in plugin says it has is on disk, loaded by the page
// and named with its hash so a new one isn't read from the cache: a script
// after the kernel and before app.js, which looks for its pages, a
// stylesheet in the head with the others.
func TestBuiltinClientsLoaded(t *testing.T) {
page, err := os.ReadFile("assets/index.html")
if err != nil {
t.Fatal(err)
}
src := string(page)
at := func(name string) int {
tag := `<script src="` + name + `"></script>`
if strings.HasSuffix(name, ".css") {
tag = `<link rel="stylesheet" href="` + name + `">`
}
i := strings.Index(src, tag)
if i < 0 {
t.Fatalf("index.html doesn't load %s", name)
}
return i
}
kernel, app, start := at("kernel.js"), at("app.js"), at("start.js")
if kernel > app || app > start {
t.Fatal("kernel.js, app.js and start.js out of order")
}
n := 0
for _, m := range pluginrt.Registered() {
for _, c := range m.Client {
name := "plugins/" + m.ID + "/" + c
if _, err := os.Stat(filepath.Join("assets", name)); err != nil {
t.Errorf("%s: %v", name, err)
}
attr := "src"
if strings.HasSuffix(name, ".css") {
attr = "href"
if i := at(name); i > strings.Index(src, "</head>") {
t.Errorf("%s isn't in the head", name)
}
} else if c == "page.js" {
// a page's code that runs on app.js's helpers: after app.js,
// before start.js shows the first page
if i := at(name); i < app || i > start {
t.Errorf("%s isn't between app.js and start.js", name)
}
} else if i := at(name); i < kernel || i > app {
t.Errorf("%s isn't between kernel.js and app.js", name)
}
if !strings.Contains(string(versionedPage(page)), attr+`="`+name+`?v=`) {
t.Errorf("%s isn't named with its hash", name)
}
n++
}
}
if n == 0 {
t.Fatal("no plugin has a script")
}
}
// Every string of every built-in plugin is said in every language.
func TestBuiltinsTranslated(t *testing.T) {
src, err := os.ReadFile("assets/i18n.js")
if err != nil {
t.Fatal(err)
}
for _, lang := range []string{"zh: {", `"zh-TW": {`, "ja: {", "de: {"} {
_, block, ok := strings.Cut(string(src), "\n "+lang+"\n")
if !ok {
t.Fatalf("no %s block", lang)
}
block, _, _ = strings.Cut(block, "\n },")
for _, m := range pluginrt.Registered() {
says := []string{m.Name, m.Sub, m.One, m.Many}
if sc := m.Schema(); sc != nil {
for _, p := range sc.Properties {
says = append(says, p.Title, p.Description)
}
}
for _, s := range says {
if s == "" {
continue
}
k, _ := json.Marshal(s)
if !strings.Contains(block, "\n "+string(k)+": ") {
t.Errorf("%s doesn't say %s", lang, k)
}
}
}
}
}