library: a tools plugin is a Library server of its own, in the MCP hub (Search1API)

chenxiang0010 (Discord #general) asked for a tools plugin's tools, Search1API's
(@magpie-community/tools-search1api), to be in magpie's aggregated MCP server.
Until now plugin tools were served only at /mcp/magpie/tools, wired by hand;
the hub listed Library servers only.

Now each plugin that is on and gives tools becomes a Library server once the
plugin host has noted its tools (plugin-tools.json, new plugin.ToolsNoted):
- named by the plugin's short name (search1api, search1api-plugin beside a
  user's server of that name), `plugin` set, `local`, its URL the new
  /mcp/magpie/tools/<short> (gateway ToolsMCPOne), which serves that
  plugin's tools alone by their own names;
- added with the hub on, it is on for the agents given the hub's entry, so
  their hub lists search1api__search etc. at once; with the hub off it is on
  for none until switched on. Per agent and per tool it is switched like any
  server;
- the hub lists and runs its tools in process (gateway.PluginToolsOf,
  RunPluginToolOf, under the Plugin tools gate); with the hub off an agent is
  given the per-plugin URL at the address it reaches the gateway (through),
  with a key from another machine;
- offered once (pluginsOffered): removed by the user, it comes back only when
  the plugin is removed and added again. The plugin removed takes the server
  out; turned off it stays and lists nothing; an unreadable plugins.json
  changes nothing (plugin.ReadList). Edited in the Library's editor, which
  doesn't send `plugin`, it stays the plugin's.
Docs: docs/subsystems/plugin-tools.md, mcp-hub.md, site docs plugins (en, zh, ja).

Run (mote; full suite at this change on origin/main 024393fbb, then rebased on
acdc85ac8, whose 5 commits touch internal/plugin/page.go and a gateway test;
library, gateway and plugin focused runs again at the pushed head: ok):
- go test -tags nogui ./internal/library ./internal/gateway ./internal/plugin
  -run 'PluginTool|Hub|ToolsMCP|ServingGates|OwnMCPRejects|Tool': ok.
- TestReadOnlyKeyEveryRoute also covers the new route.
- New tests: TestPluginToolsInHub, TestPluginToolsServerComesAndGoes,
  TestPluginToolsServerThroughAnotherAddress (library), TestToolsMCPOnePlugin
  (gateway).
- go vet (darwin, GOOS=linux, GOOS=windows) on the three packages; go build: ok.
  gofmt -l: clean.
- Full suite, go test -tags nogui -count=1 -timeout 45m ./... (log kept):
  80 packages ok, internal/gateway red on TestReadOnlyKeyEveryRoute: the new
  route wasn't classified for read-only keys. Added to readOnlyRefused's
  list in the test (a read-only key is refused there, as at
  /mcp/magpie/tools); internal/gateway whole package again: ok (846s).
- Real run, sandbox HOME on mote, built binary, MAGPIE_ADDR on a free port:
  `magpie plugin add @magpie-community/tools-search1api` (latest from npm),
  `magpie serve`. library.json got the search1api server (plugin, local,
  url .../mcp/magpie/tools/search1api, pluginsOffered); the per-plugin
  endpoint listed search, news, ask, crawl, sitemap, trending, send_feedback;
  with the hub on, /mcp/magpie/hub listed search1api__search ... and
  search1api__search answered isError "Sign in with `magpie plugin login
  search1api`, configure apiKey ..." from the plugin.

Broken by hand (each red, then restored):
- hub ignoring plugin servers (backend path): TestPluginToolsInHub red
  ("claude's hub tools [fake/a fake/b fake/c]").
- adoptPlugins returning false at once: both library tests red ("no server
  for the plugin").
- through's plugin branch off: TestPluginToolsServerThroughAnotherAddress red.
- the ToolsMCPOne route removed: TestToolsMCPOnePlugin red (404).

Not tried: a signed-in Search1API account (none here), so no search went
through; a real agent (Claude Code, Codex) calling the hub; WSL/remote
agents through another address (unit test only); the GUI's Library page
showing the server (no GUI file changed, GUI suite not run).
This commit is contained in:
yetone
2026-10-30 22:33:25 +08:00
parent acdc85ac89
commit 2f65a33aaf
17 changed files with 671 additions and 5 deletions
+2 -1
View File
@@ -36,13 +36,14 @@ The gateway can't import the library (the library imports the gateway), so the g
- A call that times out leaves the server running for the next; a server that died is started again. A server that can't be started is an error on each call, not a retry loop.
- Every process the hub starts is in a `proc` tree magpie ends when the switch goes off, the server is edited, it has been idle, or the gateway stops. A test ends them in cleanup (`hubSandbox`).
- A gateway key holder on the LAN reaches the Library's command servers through the hub while it is on, as they reach plugin tools. They run with the user's rights on this computer.
- A tools plugin's server (`plugin` set, [Plugin tools](plugin-tools.md)) is behind the hub as any server is, but its tools are listed and run in this process through the plugin host, not over its URL, and they aren't cached: the host has them.
- The tools a server listed are cached until it says they changed, it is edited, or the switch is turned off. A server that changes its tools without saying so shows them after one of those.
## Verification
```sh
go test -tags nogui ./internal/gui -run TestHubOpen
go test -tags nogui ./internal/library -run 'TestHub|TestFakeMCPServer|TestCheck'
go test -tags nogui ./internal/library -run 'TestHub|TestFakeMCPServer|TestCheck|TestPluginTools'
go test -tags nogui ./internal/gateway -run 'HubMCP|OwnMCPRejects' -timeout 45m
go test -tags nogui ./internal/cli -run TestLibraryMCPHub
node --test internal/gui/tests/library-mcp-hub.test.cjs
+7 -1
View File
@@ -32,13 +32,19 @@ A tool's answer goes back to the agent that called it, on this computer or on a
- A plugin's tool runs in the plugin host with the user's rights, as its provider code does. Installing a plugin is trusting it.
- One host serves every plugin. A tool that never answers is answered at `ToolTimeout`, and its call's slot in the host is left for its own abort to end; the host goes on serving (`TestPluginTools`).
- Names are stable for a given set of plugins on. Turning on a plugin earlier in plugins.json that gives a tool of the same MCP name renumbers the later one.
- Wiring is the user's: the Plugins page copies the address, and magpie writes no agent's MCP config for it. There is no Library entry yet. The Library's own servers have an endpoint of the same kind beside this one, `/mcp/magpie/hub/<agent>`, which magpie does write into agents ([MCP hub](mcp-hub.md)); plugin tools aren't in it.
- Each plugin that is on and gives tools is also a [Library](library.md) server of its own (chenxiang0010 on Discord: Search1API's tools in the MCP hub), so magpie wires it like any other ([`plugin_tools.go`](../../internal/library/plugin_tools.go)):
- Once the host has noted the plugin's tools (plugin-tools.json, `plugin.ToolsNoted`), the library adds an `http` server named by the plugin's short name (`search1api`, `search1api-plugin` when a server has that name), with `plugin` set to the plugin's name and its URL `/mcp/magpie/tools/<short>` (`ToolsMCPOne`), which serves that plugin's tools alone, each by its own name.
- Added with the MCP hub on, it is on for the agents given the hub's entry, so its tools are in their hub at once as `<short>__<tool>`; with the hub off it is on for none until the user switches it on. Per agent and per tool it is then switched like any server.
- The hub runs its tools in this process (`gateway.PluginToolsOf`, `RunPluginToolOf`), under the same Plugin tools gate. With the hub off an agent is given the gateway's address of the plugin's tools as it reaches the gateway (`through`), with a key from another machine.
- It is `local`: a carry or backup never takes it to a computer that may lack the plugin. It is offered once (`pluginsOffered`): a server the user removed comes back only when the plugin is removed and added again. The plugin removed takes its server out; turned off, the server stays and lists nothing. A plugins.json that can't be read changes nothing.
- `/mcp/magpie/tools`, every plugin's tools under one server, stays for agents wired to it by hand.
## Verification
```sh
go test ./internal/plugin/ -run Tool
go test ./internal/gateway/ -run 'ToolsMCP|ServingGates|OwnMCPRejects' -timeout 45m
go test ./internal/library/ -run PluginTools
go test ./plugins/tools/ ./internal/pluginrt/
go test ./internal/gui/ -run 'Builtin|Plugins'
node --test internal/gui/tests/plugin-tools.test.cjs internal/gui/tests/builtins.test.cjs
+1
View File
@@ -862,6 +862,7 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc(ImageMCPPath, s.imageMCP)
mux.HandleFunc(ImageMCPFiles+"{name}", s.imageMCPFile)
mux.HandleFunc(ToolsMCPPath, s.toolsMCP)
mux.HandleFunc(ToolsMCPOne+"{plugin}", s.toolsMCPOne)
mux.HandleFunc(HubMCPPath+"{agent}", s.hubMCP)
mux.HandleFunc(HubMCPAll, s.hubMCP)
mux.HandleFunc(CodexPath+"/", s.codexBackend)
+1 -1
View File
@@ -42,7 +42,7 @@ var readOnlyRefused = []string{
"GET /v1/videos/{id}/content", "GET /videos/{id}/content",
// MCP servers, plugins' and Codex's backends, Gemini, everything else
"POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}",
SearchMCPPath, VisionMCPPath, ImageMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath,
SearchMCPPath, VisionMCPPath, ImageMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}",
HubMCPPath + "{agent}", HubMCPAll, CodexPath + "/", "GET " + CodexCatalogPath,
"GET /v1beta/models", "POST /v1beta/models/{call...}", "/",
}
+86 -1
View File
@@ -3,8 +3,11 @@ package gateway
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"slices"
"strconv"
"strings"
"unicode/utf8"
@@ -143,13 +146,92 @@ var anyPluginOn = func() bool {
}
func (s *Server) toolsMCPCall(r *http.Request, m mcpMessage) (any, map[string]any) {
return s.toolsMCPServe(r, m, "", servedTools)
}
// ToolsMCPOne is where one plugin's tools are served, each by its own
// name, the plugin's short name (ToolPrefix) after it: the address of the
// Library server magpie gives each plugin with tools
// (library/plugin_tools.go), so it can be switched on per agent and put
// behind the MCP hub like any other.
const ToolsMCPOne = ToolsMCPPath + "/"
// ToolPrefix is the name a plugin's tools are under: its short name, in
// the characters MCP clients take.
func ToolPrefix(spec string) string { return toolPrefix(spec) }
func (s *Server) toolsMCPOne(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("plugin")
serveMCP(w, r, "magpie's plugin tools", "magpie-tools", toolsMCPBody, func(r *http.Request, m mcpMessage) (any, map[string]any) {
return s.toolsMCPServe(r, m, name, func(ctx context.Context) ([]mcpTool, error) {
spec, ts, err := pluginToolsBy(ctx, func(spec string) bool { return toolPrefix(spec) == name })
out := make([]mcpTool, 0, len(ts))
for _, t := range ts {
out = append(out, mcpTool{spec: spec, Tool: t, name: t.Name})
}
return out, err
})
})
}
// pluginToolsBy are the tools of the first plugin that is on that is
// picks, and its spec; none while Plugin tools is off, or no plugin that
// is on is it. With no plugin on, the plugin host isn't started for it.
func pluginToolsBy(ctx context.Context, is func(spec string) bool) (string, []plugin.Tool, error) {
if !gwtool.Served(gwtool.PluginTools) || !anyPluginOn() {
return "", nil, nil
}
pts, err := pluginTools(ctx)
if err != nil {
return "", nil, err
}
for _, pt := range pts {
if is(pt.Spec) {
return pt.Spec, pt.Tools, nil
}
}
return "", nil, nil
}
// PluginToolsOf are the tools of the plugin called name (plugin.Name of
// its spec) while it is on and Plugin tools is served: what the MCP hub
// lists for its Library server.
func PluginToolsOf(ctx context.Context, name string) ([]plugin.Tool, error) {
_, ts, err := pluginToolsBy(ctx, func(spec string) bool { return plugin.Name(spec) == name })
return ts, err
}
// RunPluginToolOf runs tool of the plugin called name for agent, as the
// MCP hub calls it: the text it answered, or why it couldn't run. The hub
// has held the call to the caller's key limit already.
func RunPluginToolOf(ctx context.Context, name, tool string, args json.RawMessage, agent string) (string, error) {
if !gwtool.Served(gwtool.PluginTools) {
return "", errors.New(errToolsOff)
}
spec, ts, err := pluginToolsBy(ctx, func(spec string) bool { return plugin.Name(spec) == name })
if err != nil {
return "", fmt.Errorf("magpie couldn't load its plugins: %w", err)
}
if !slices.ContainsFunc(ts, func(t plugin.Tool) bool { return t.Name == tool }) {
return "", fmt.Errorf("the plugin %s isn't on in magpie, or gives no tool %s", name, tool)
}
return runPluginTool(ctx, spec, tool, args, agent)
}
// toolsMCPServe answers m for the tools list gives: every plugin's (one
// "") or one plugin's.
func (s *Server) toolsMCPServe(r *http.Request, m mcpMessage, one string, servedTools func(context.Context) ([]mcpTool, error)) (any, map[string]any) {
switch m.Method {
case "initialize":
say := "The tools the plugins added to magpie give, each named <plugin>_<tool>. Add or switch plugins in magpie's Settings → Plugins."
if one != "" {
say = "The tools magpie's plugin " + one + " gives. Add or switch plugins in magpie's Settings → Plugins."
}
return map[string]any{
"protocolVersion": mcpVersion(m),
"capabilities": map[string]any{"tools": map[string]any{}},
"serverInfo": map[string]any{"name": "magpie-tools", "title": "Magpie Plugin Tools", "version": Version},
"instructions": "The tools the plugins added to magpie give, each named <plugin>_<tool>. Add or switch plugins in magpie's Settings → Plugins.",
"instructions": say,
}, nil
case "ping":
return map[string]any{}, nil
@@ -195,6 +277,9 @@ func (s *Server) toolsMCPCall(r *http.Request, m mcpMessage) (any, map[string]an
return toolResult(said, false), nil
}
}
if one != "" {
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": the plugin " + one + " isn't on in magpie, or gives no such tool"}
}
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": no plugin that is on gives it"}
}
return nil, map[string]any{"code": -32601, "message": "method not found: " + m.Method}
+84
View File
@@ -0,0 +1,84 @@
package gateway
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/plugin"
)
func toolsPostTo(h http.Handler, path, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
r.RemoteAddr, r.Host = "127.0.0.1:50000", "127.0.0.1:3425"
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
// One plugin's tools are served at ToolsMCPOne<its short name>, each by
// its own name: the address of the Library server the library gives a
// plugin with tools (chenxiang0010: Search1API in the MCP hub). Another
// plugin's tool isn't listed or run there, and the hub's way in
// (PluginToolsOf, RunPluginToolOf) finds the plugin by its name, whatever
// version its spec pins.
func TestToolsMCPOnePlugin(t *testing.T) {
fresh(t)
ran := fakePluginTools(t, []plugin.PluginTools{
{Spec: "@magpie-community/tools-search1api@0.1.1", Tools: []plugin.Tool{
{Name: "search", Description: "Search the web.", Schema: json.RawMessage(`{"type":"object","properties":{"query":{"type":"string"}}}`)},
{Name: "crawl", Description: "A page."},
}},
{Spec: "opencode-weather-tools", Tools: []plugin.Tool{{Name: "now"}}},
})
h := lanGuard(New().Handler())
at := ToolsMCPOne + "search1api"
m := readMCP(t, toolsPostTo(h, at, toolsList))
var names []string
for _, x := range m.Result.Tools {
names = append(names, x.Name)
}
if strings.Join(names, " ") != "search crawl" {
t.Fatalf("search1api's tools = %v (%+v)", names, m)
}
m = readMCP(t, toolsPostTo(h, at, toolsCall("search", `{"query":"magpie"}`)))
if m.Result.IsError || len(m.Result.Content) != 1 || m.Result.Content[0].Text != "ran search" {
t.Fatalf("call = %+v", m)
}
if m := readMCP(t, toolsPostTo(h, at, toolsCall("now", `{}`))); m.Error == nil || m.Error.Code != -32602 {
t.Errorf("another plugin's tool at search1api's address: %+v", m)
}
if m := readMCP(t, toolsPostTo(h, ToolsMCPOne+"nope", toolsList)); len(m.Result.Tools) != 0 {
t.Errorf("a plugin not on lists %+v", m)
}
ctx := context.Background()
ts, err := PluginToolsOf(ctx, "@magpie-community/tools-search1api")
if err != nil || len(ts) != 2 {
t.Fatalf("PluginToolsOf = %v %v", ts, err)
}
if said, err := RunPluginToolOf(ctx, "@magpie-community/tools-search1api", "crawl", json.RawMessage(`{}`), "claude"); err != nil || said != "ran crawl" {
t.Fatalf("RunPluginToolOf = %q %v", said, err)
}
if _, err := RunPluginToolOf(ctx, "@magpie-community/tools-search1api", "now", json.RawMessage(`{}`), "claude"); err == nil {
t.Error("RunPluginToolOf ran another plugin's tool")
}
if got := (*ran)[len(*ran)-1]; got != `@magpie-community/tools-search1api@0.1.1 crawl {} claude` {
t.Errorf("ran %q", got)
}
// off, nothing is listed or run
stop := gwtool.Gate()
defer stop()
if ts, _ := PluginToolsOf(ctx, "@magpie-community/tools-search1api"); len(ts) != 0 {
t.Errorf("off, PluginToolsOf = %v", ts)
}
if _, err := RunPluginToolOf(ctx, "@magpie-community/tools-search1api", "search", nil, ""); err == nil || !strings.Contains(err.Error(), "Plugin tools plugin is off") {
t.Errorf("off, RunPluginToolOf: %v", err)
}
}
+3
View File
@@ -55,6 +55,9 @@ type Library struct {
// which hands each call on to the library's servers ticked for it, in
// place of their own entries (#2679, mcp_hub.go)
MCPHub bool `json:"mcpHub,omitempty"`
// PluginsOffered are the plugins (plugin.Name) given a server of their
// tools, for one the user removed not to come back (plugin_tools.go)
PluginsOffered []string `json:"pluginsOffered,omitempty"`
// SeenSkills are, by repository and ref ("owner/repo@ref"), the
// folders of skills there the page has offered: picked or not at
// install, or set aside after a check. A check offers only the others
+4
View File
@@ -56,6 +56,10 @@ type Server struct {
// a sync never carries it, and one coming in neither takes it away nor
// puts another computer's of that name in its place (carry.go).
Local bool `json:"local,omitempty"`
// Plugin is the plugin (plugin.Name) whose tools the server is: the
// gateway serves them at its URL, and the hub calls the plugin itself
// (plugin_tools.go)
Plugin string `json:"plugin,omitempty"`
// startupWrote is the startup_timeout_sec magpie last wrote in the
// entry being written, 0 for none: one the entry has otherwise is the
+10 -1
View File
@@ -174,7 +174,13 @@ func (theHub) Tools(ctx context.Context, agentID string) []gateway.HubTool {
wg.Add(1)
go func() {
defer wg.Done()
ts, err := backendOf(s).tools(ctx)
var ts []map[string]json.RawMessage
var err error
if s.Plugin != "" {
ts, err = pluginHubTools(ctx, s)
} else {
ts, err = backendOf(s).tools(ctx)
}
if err != nil {
return
}
@@ -208,6 +214,9 @@ func (theHub) Call(ctx context.Context, agentID, server, tool string, args json.
if slices.Contains(s.DisabledTools, tool) {
return nil, errors.New("the tool is turned off in magpie's Library")
}
if s.Plugin != "" {
return pluginHubCall(ctx, agentID, s, tool, args)
}
return backendOf(s).call(ctx, tool, args)
}
+9
View File
@@ -48,6 +48,15 @@ func relaysAny() bool {
// given it. Only a streamable HTTP server is relayed: an SSE one's stream
// names the address to post to, which would have to be rewritten.
func through(s *Server, base string) *Server {
if s.Plugin != "" {
// a plugin's tools, which the gateway serves itself
c := *s
c.URL = pluginURL(base, s.Plugin)
if k := agent.KeyAt(base); k != gateway.Token {
c.Headers = map[string]string{"Authorization": "Bearer " + k}
}
return &c
}
if s.Transport != "http" || !mcpauth.SignedIn(s.Name, s.URL) {
return s
}
+195
View File
@@ -0,0 +1,195 @@
package library
// A plugin that gives tools (OpenCode's tool hook, served at the gateway's
// /mcp/magpie/tools) is a server in the Library of its own (chenxiang0010
// on Discord: Search1API's tools in the MCP hub). Once the plugin host has
// noted the plugin's tools (plugin-tools.json), the library adds a server
// named by the plugin's short name (search1api), at the gateway's
// ToolsMCPOne<name>, which serves that plugin's tools alone. It is then a
// server as any other: switched on per agent, its tools turned off one by
// one, behind the MCP hub as <name>__<tool>, or written into an agent as
// its own entry with the hub off.
//
// - The hub calls the plugin in this process (pluginToolsOf,
// runPluginToolOf), not through its own address.
// - An agent is given the address as it reaches the gateway (through),
// with a key from another machine.
// - It is kept to this computer (Local): a sync never carries it, as
// another computer may not have the plugin.
// - It is offered once (PluginsOffered): a user who removes the server
// doesn't get it back until the plugin is removed and added again.
// - It goes with the plugin: once plugins.json no longer has the plugin,
// the server is taken out. A plugin turned off keeps its server, which
// lists nothing until the plugin is on again. A plugins.json that
// can't be read takes nothing out.
// - Added with the hub on, it is on for the agents given the hub's
// entry, so its tools are in their hub at once; with the hub off, on
// for none until the user switches it on.
import (
"context"
"encoding/json"
"log"
"net/url"
"slices"
"strconv"
"strings"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/plugin"
)
// pluginToolsOf and runPluginToolOf are the gateway's, a test's fakes in
// their place; pluginsInstalled and toolsNoted are the plugin package's.
var (
pluginToolsOf = gateway.PluginToolsOf
runPluginToolOf = gateway.RunPluginToolOf
pluginsInstalled = plugin.ReadList
toolsNoted = plugin.ToolNames
)
func init() {
plugin.ToolsNoted = func() {
if changed, err := adoptPluginTools(); err != nil {
log.Printf("library: giving plugin tools a server: %v", err)
} else if changed {
if _, err := Sync(); err != nil {
log.Printf("library: syncing after plugin tools: %v", err)
}
}
}
}
// pluginURL is the address of the plugin's tools at the gateway at base.
func pluginURL(base, spec string) string {
return strings.TrimRight(base, "/") + gateway.ToolsMCPOne + url.PathEscape(gateway.ToolPrefix(spec))
}
// adoptPluginTools gives each plugin with tools its server, and takes out
// those of plugins removed, saving the library when it changed. It doesn't
// sync.
func adoptPluginTools() (bool, error) {
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return false, err
}
if !l.adoptPlugins() {
return false, nil
}
return true, l.save()
}
// adoptPlugins brings the library's plugin servers in line with the
// plugins installed and the tools they were noted giving; true when it
// changed the library.
func (l *Library) adoptPlugins() bool {
pl, err := pluginsInstalled()
if err != nil {
return false // unknown: nothing added, nothing taken out
}
noted := toolsNoted()
installed := map[string]bool{}
for _, e := range pl.Plugins {
installed[plugin.Name(e.Spec)] = true
}
changed := false
// the plugin removed: its server goes, and it is offered again once
// added again
if n := len(l.PluginsOffered); n > 0 {
l.PluginsOffered = slices.DeleteFunc(l.PluginsOffered, func(name string) bool { return !installed[name] })
changed = changed || len(l.PluginsOffered) != n
}
if n := len(l.MCP); n > 0 {
l.MCP = slices.DeleteFunc(l.MCP, func(s *Server) bool { return s.Plugin != "" && !installed[s.Plugin] })
changed = changed || len(l.MCP) != n
}
for _, e := range pl.Plugins {
name := plugin.Name(e.Spec)
if e.Off || len(noted[e.Spec]) == 0 || slices.Contains(l.PluginsOffered, name) {
continue
}
l.PluginsOffered = append(l.PluginsOffered, name)
changed = true
if slices.ContainsFunc(l.MCP, func(s *Server) bool { return s.Plugin == name }) {
continue
}
l.MCP = append(l.MCP, &Server{Name: l.freeName(gateway.ToolPrefix(e.Spec)), Transport: "http",
URL: pluginURL(gateway.URL(), e.Spec), Plugin: name, Local: true, Agents: l.hubAgents()})
}
// the gateway's address, which the check and the page use, as it is now
for _, s := range l.MCP {
if s.Plugin == "" {
continue
}
if u := pluginURL(gateway.URL(), s.Plugin); s.URL != u {
s.URL, changed = u, true
}
}
return changed
}
// freeName is base, or base-plugin, then a number, whichever no server
// has.
func (l *Library) freeName(base string) string {
name := base
for i := 1; l.server(name) != nil; i++ {
name = base + "-plugin"
if i > 1 {
name += strconv.Itoa(i)
}
}
return name
}
// hubAgents are the agents the hub's entry goes to (those with a server
// behind it), with the hub on; none with it off.
func (l *Library) hubAgents() []string {
out := []string{}
if !l.MCPHub {
return out
}
for _, s := range l.MCP {
if !inHub(s) {
continue
}
for _, a := range s.Agents {
if !slices.Contains(out, a) {
out = append(out, a)
}
}
}
slices.Sort(out)
return out
}
// pluginHubTools are the tools the plugin of s gives, as the hub lists a
// server's: its tools/list entries.
func pluginHubTools(ctx context.Context, s *Server) ([]map[string]json.RawMessage, error) {
ts, err := pluginToolsOf(ctx, s.Plugin)
if err != nil {
return nil, err
}
out := make([]map[string]json.RawMessage, 0, len(ts))
for _, t := range ts {
name, _ := json.Marshal(t.Name)
desc, _ := json.Marshal(t.Description)
spec := map[string]json.RawMessage{"name": name, "description": desc}
if len(t.Schema) > 0 && json.Valid(t.Schema) {
spec["inputSchema"] = t.Schema
}
out = append(out, spec)
}
return out, nil
}
// pluginHubCall runs tool of the plugin of s for agent, its answer as an
// MCP tool result.
func pluginHubCall(ctx context.Context, agentID string, s *Server, tool string, args json.RawMessage) (json.RawMessage, error) {
said, err := runPluginToolOf(ctx, s.Plugin, tool, args, agentID)
if err != nil {
return nil, err
}
return json.Marshal(map[string]any{"content": []map[string]any{{"type": "text", "text": said}}, "isError": false})
}
+217
View File
@@ -0,0 +1,217 @@
package library
import (
"context"
"encoding/json"
"errors"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/plugin"
)
// fakePlugins has the plugins installed be specs (none on when off), each
// noted giving search and crawl, and the gateway's plugin tools be theirs,
// recording each call run.
type fakePlugins struct {
specs []string
off bool
err error
ran []string
}
func fakePluginTools(t *testing.T, specs ...string) *fakePlugins {
t.Helper()
f := &fakePlugins{specs: specs}
oldI, oldN, oldT, oldR := pluginsInstalled, toolsNoted, pluginToolsOf, runPluginToolOf
t.Cleanup(func() { pluginsInstalled, toolsNoted, pluginToolsOf, runPluginToolOf = oldI, oldN, oldT, oldR })
pluginsInstalled = func() (plugin.List, error) {
var l plugin.List
for _, s := range f.specs {
l.Plugins = append(l.Plugins, plugin.Entry{Spec: s, Off: f.off})
}
return l, f.err
}
toolsNoted = func() map[string][]string {
m := map[string][]string{}
for _, s := range f.specs {
m[s] = []string{"crawl", "search"}
}
return m
}
pluginToolsOf = func(_ context.Context, name string) ([]plugin.Tool, error) {
for _, s := range f.specs {
if plugin.Name(s) == name && !f.off {
return []plugin.Tool{
{Name: "search", Description: "Search the web.", Schema: json.RawMessage(`{"type":"object","properties":{"query":{"type":"string"}}}`)},
{Name: "crawl", Description: "A page."},
}, nil
}
}
return nil, nil
}
runPluginToolOf = func(_ context.Context, name, tool string, args json.RawMessage, agentID string) (string, error) {
f.ran = append(f.ran, name+" "+tool+" "+string(args)+" "+agentID)
return "found " + string(args), nil
}
return f
}
const search1api = "@magpie-community/tools-search1api@0.1.1"
// A plugin that gives tools (Search1API, chenxiang0010 on Discord) is a
// Library server of its own once its tools are noted: on, with the hub on,
// for the agents given the hub's entry, its tools in their hub as
// search1api's, run in the plugin for the calling agent, and switched on
// and off per agent and per tool like any server's. With the hub off an
// agent is given the gateway's address of that plugin's tools.
func TestPluginToolsInHub(t *testing.T) {
h := hubSandbox(t)
f := fakePluginTools(t, search1api)
fake := fakeStdio(t, "ok", nil)
fake.Agents = []string{"claude"}
ok(t)(SaveServer("", *fake))
ok(t)(SetMCPHub(true))
ok(t)(Sync())
l, err := load()
if err != nil {
t.Fatal(err)
}
s := l.server("search1api")
if s == nil {
t.Fatalf("no server for the plugin: %+v", l.MCP)
}
if s.Plugin != "@magpie-community/tools-search1api" || !s.Local || !slices.Equal(s.Agents, []string{"claude"}) ||
s.URL != strings.TrimRight(gateway.URL(), "/")+gateway.ToolsMCPOne+"search1api" {
t.Fatalf("the plugin's server: %+v", s)
}
ctx := context.Background()
hub := theHub{}
got := hubNames(hub.Tools(ctx, "claude"))
if !slices.Contains(got, "search1api/search") || !slices.Contains(got, "search1api/crawl") {
t.Fatalf("claude's hub tools %v, want search1api's", got)
}
for _, x := range hub.Tools(ctx, "claude") {
if x.Tool == "search" && !strings.Contains(string(x.Spec["inputSchema"]), "query") {
t.Errorf("search's schema: %s", x.Spec["inputSchema"])
}
}
res, err := hub.Call(ctx, "claude", "search1api", "search", json.RawMessage(`{"query":"magpie"}`))
if err != nil || hubText(t, res) != `found {"query":"magpie"}` {
t.Fatalf("search: %s %v", res, err)
}
if want := `@magpie-community/tools-search1api search {"query":"magpie"} claude`; len(f.ran) != 1 || f.ran[0] != want {
t.Errorf("ran %q, want %q", f.ran, want)
}
if _, err := hub.Call(ctx, "codex", "search1api", "search", json.RawMessage(`{}`)); err == nil || !strings.Contains(err.Error(), "isn't switched on for codex") {
t.Errorf("a plugin not switched on for codex ran: %v", err)
}
// a tool turned off is neither listed nor run
ok(t)(change(func(l *Library) error { l.server("search1api").DisabledTools = []string{"crawl"}; return nil }))
if got := hubNames(hub.Tools(ctx, "claude")); slices.Contains(got, "search1api/crawl") {
t.Errorf("crawl, turned off, listed: %v", got)
}
if _, err := hub.Call(ctx, "claude", "search1api", "crawl", json.RawMessage(`{}`)); err == nil {
t.Error("crawl, turned off, ran")
}
// edited in the Library's editor, which doesn't send it, it stays the
// plugin's
ed := *l.server("search1api")
ed.Plugin, ed.Local, ed.Agents = "", false, []string{"claude", "codex"}
ok(t)(SaveServer("search1api", ed))
if l, _ := load(); l.server("search1api").Plugin == "" || !l.server("search1api").Local {
t.Fatalf("edited, no longer the plugin's: %+v", l.server("search1api"))
}
// the hub off, claude is given the address of the plugin's tools
ok(t)(SetMCPHub(false))
e, err := targetByID("claude").MCP.entries()
if err != nil {
t.Fatal(err)
}
if u, _ := e["search1api"]["url"].(string); u != strings.TrimRight(gateway.URL(), "/")+gateway.ToolsMCPOne+"search1api" {
t.Errorf("claude's search1api entry: %v\n%s", e["search1api"], read(t, filepath.Join(h, ".claude.json")))
}
}
// The server is offered once: removed by the user, it isn't added again
// until the plugin is removed and added again. A plugin removed takes its
// server with it; one turned off keeps it; plugins.json unreadable takes
// nothing out and adds nothing.
func TestPluginToolsServerComesAndGoes(t *testing.T) {
hubSandbox(t)
f := fakePluginTools(t, search1api)
has := func() bool {
t.Helper()
l, err := load()
if err != nil {
t.Fatal(err)
}
return l.server("search1api") != nil
}
ok(t)(Sync())
if !has() {
t.Fatal("no server for the plugin")
}
l, _ := load()
if a := l.server("search1api").Agents; len(a) != 0 {
t.Errorf("with the hub off, on for %v, want none", a)
}
ok(t)(RemoveServer("search1api"))
ok(t)(Sync())
if has() {
t.Fatal("a server the user removed came back")
}
f.specs = nil
ok(t)(Sync())
f.specs = []string{"@magpie-community/tools-search1api@0.1.2"}
ok(t)(Sync())
if !has() {
t.Fatal("the plugin added again, no server")
}
f.off = true
ok(t)(Sync())
if !has() {
t.Fatal("the plugin turned off took its server")
}
f.off = false
f.err = errors.New("unreadable")
f.specs = nil
ok(t)(Sync())
if !has() {
t.Fatal("plugins.json unreadable took the server out")
}
f.err = nil
ok(t)(Sync())
if has() {
t.Fatal("the plugin removed kept its server")
}
// a name a server of the user's has already
ok(t)(SaveServer("", Server{Name: "search1api", Transport: "http", URL: "https://example.com/mcp"}))
f.specs = []string{search1api}
ok(t)(Sync())
l, _ = load()
if s := l.server("search1api-plugin"); s == nil || s.Plugin == "" || l.server("search1api").Plugin != "" {
t.Fatalf("beside the user's search1api: %+v", l.MCP)
}
}
// An agent that reaches the gateway at another address (a WSL distro under
// NAT) is given the plugin's tools at that address.
func TestPluginToolsServerThroughAnotherAddress(t *testing.T) {
sandbox(t)
s := &Server{Name: "search1api", Transport: "http", URL: "http://127.0.0.1:3425" + gateway.ToolsMCPOne + "search1api", Plugin: "@magpie-community/tools-search1api", Local: true}
c := through(s, "http://172.20.0.1:3425")
if c.URL != "http://172.20.0.1:3425"+gateway.ToolsMCPOne+"search1api" {
t.Errorf("through another address: %s", c.URL)
}
if s.URL != "http://127.0.0.1:3425"+gateway.ToolsMCPOne+"search1api" {
t.Errorf("the stored server changed: %s", s.URL)
}
}
+21
View File
@@ -3,6 +3,7 @@ package library
import (
"errors"
"fmt"
"log"
"os"
"slices"
@@ -137,6 +138,10 @@ func syncSteps(all, gone []*Target, b *backups, res *Result) []func(*Library) {
// first operations after opening magpie took seconds (#1624, Hipple).
// It lets go after each agent's part, for whatever waits to go first.
func Sync() (*Result, error) {
// a plugin's tools, a server of their own (plugin_tools.go)
if _, err := adoptPluginTools(); err != nil {
log.Printf("library: giving plugin tools a server: %v", err)
}
res := &Result{Changed: []string{}, Problems: []Problem{}}
b := newBackups()
var all, gone []*Target
@@ -524,6 +529,18 @@ func readView(problems []Problem, glance bool) (*View, error) {
if err != nil {
return nil, err
}
// a plugin's tools, a server of their own (plugin_tools.go): saved,
// and given to the agents by a sync of their own
if l.adoptPlugins() {
if err := l.save(); err != nil {
return nil, err
}
go func() {
if _, err := Sync(); err != nil {
log.Printf("library: syncing after plugin tools: %v", err)
}
}()
}
// the agents are found once for the whole read: finding them looks
// through every agent's folders, in WSL too (#1624)
targets, asleep := targetsAsleep(false)
@@ -707,6 +724,10 @@ func SaveServer(old string, s Server) (*Result, error) {
if s.DisabledTools == nil {
s.DisabledTools = l.MCP[i].DisabledTools
}
// a plugin's server stays the plugin's, and on this computer
if p := l.MCP[i].Plugin; p != "" && s.Plugin == "" {
s.Plugin, s.Local = p, true
}
l.MCP = slices.Delete(l.MCP, i, i+1)
if old != s.Name {
l.renameProjectServers(old, s.Name)
+28
View File
@@ -14,6 +14,7 @@ import (
"time"
"github.com/yetone/magpie/internal/filememo"
"github.com/yetone/magpie/internal/lastgood"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/steady"
)
@@ -111,7 +112,34 @@ func noteTools(loaded []Loaded) {
defer filememo.Forget() // the gateway follows this note (Written)
if err := writeWhole(toolsPath(), append(b, '\n')); err != nil {
log.Printf("plugin tools: noting them: %v", err)
return
}
if f := ToolsNoted; f != nil {
go f()
}
}
// ToolsNoted is called once the note of which plugins give tools has
// changed: the library gives a plugin that gives tools a server of its
// own then (library/plugin_tools.go), which can't be imported here.
var ToolsNoted func()
// ReadList is plugins.json, or an error when it couldn't be read or
// parsed: the plugins installed are then unknown, never none. No file is
// no plugin.
func ReadList() (List, error) {
b, err := lastgood.Read(listPath(), lastgood.JSON)
if errors.Is(err, fs.ErrNotExist) {
return List{}, nil
}
if err != nil {
return List{}, err
}
var l List
if err := json.Unmarshal(b, &l); err != nil {
return List{}, fmt.Errorf("%s: %w", listPath(), err)
}
return l, nil
}
// ToolsOn counts the plugins on in plugins.json that gave tools when the
+1
View File
@@ -776,6 +776,7 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
</div>
<p>設定 → プラグインには各プラグインのツールがこの名前で表示され、サーバーのアドレスをコピーできます。<code>args</code> は zod のフィールド定義(<code>tool.schema</code> は zod)、zod オブジェクト、または JSON Schema オブジェクトです。エージェントにはこれが示され、magpie は <code>execute</code> の前に呼び出しの引数をこれで検証します。引数が正しくなければ、その引数を示すエラーを返します。<code>ctx</code> は OpenCode と同じで、<code>agent</code> は呼び出したエージェントです。ツールの実行時間は 55 秒までで、時間切れになると <code>ctx.abort</code> が発火します。</p>
<p>このサーバーは組み込みプラグイン <span class="ui">プラグインのツール</span> が提供します。オンのプラグインがツールを提供している間はオンのままで、オフのときはツールが一覧に出ず、呼び出しにはオフであることが返ります。ゲートウェイキーでの呼び出しはそのキーの上限に数えられます。ツールはプロバイダープラグインと同じくあなたの権限でプラグインホスト内で動き、結果は呼び出したエージェントにだけ返ります。</p>
<p>ツールを提供するプラグインは、ライブラリの MCP タブにもそれぞれ独立したサーバーとして現れ、プラグインの短い名前(<code>search1api</code>)が付きます。アドレスを手で追加する必要はありません。<a href="mcp-hub.html">MCP ハブ</a>がオンなら、そのツールはハブを使うすべてのエージェントに <code>search1api__search</code> として出ます。ほかのライブラリのサーバーと同じく、エージェントごとにオン・オフでき、ツールを一つずつ止めることもできます。削除すると、プラグインを外して追加し直すまで戻りません。</p>
<h2 id="agents"><a class="anchor" href="#agents">エージェントプラグイン</a></h2>
<p>プラグインは<em>エージェント</em>を追加することもできます。magpie に組み込みの設定がないエージェントです。そのエージェントがモデルをどこに書くか、magpie のゲートウェイを使うために他に何を書くかを伝えます。するとエージェントは magpie 自身のものと同じように<span class="ui">エージェント</span>ページに並びます。その行で magpie のモデルを選ぶと、magpie はモデルをゲートウェイのアドレスとエージェント専用のキーと一緒に設定へ書き込み、スイッチを切るとすべてユーザーの元の状態に戻します。下の例は <a href="https://aider.chat">Aider</a> を追加します。</p>
+1
View File
@@ -776,6 +776,7 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
</div>
<p>Settings → Plugins lists each plugin’s tools by these names and copies the server’s address. <code>args</code> is a zod shape (<code>tool.schema</code> is zod), a zod object or a JSON Schema object. The agent is shown it, and magpie checks a call’s arguments against it before <code>execute</code> runs; a wrong argument is answered as an error naming it. <code>ctx</code> is OpenCode’s, with <code>agent</code> the agent that called. A tool has 55 seconds, and <code>ctx.abort</code> fires when they are up.</p>
<p>The built-in plugin <span class="ui">Plugin tools</span> serves the server. It stays on while a plugin that is on gives a tool; off, no tool is listed and a call says so. A call made with a gateway key counts against that key’s limits. A tool runs in the plugin host with your rights, as a provider plugin does, and its answer goes only to the agent that called it.</p>
<p>Each plugin that gives tools is also a server of its own in the Library’s MCP tab, named by the plugin’s short name (<code>search1api</code>), so you don’t have to add the address by hand. With the <a href="mcp-hub.html">MCP hub</a> on, its tools are in the hub of every agent the hub is given, as <code>search1api__search</code>; switch it on or off per agent, or turn single tools off, as with any Library server. Removed, it comes back only when you remove the plugin and add it again.</p>
<h2 id="agents"><a class="anchor" href="#agents">Agent plugins</a></h2>
<p>A plugin can also add an <em>agent</em>: one magpie has no setup of its own for. It says where the agent keeps its model and what else to write there for the agent to use magpie’s gateway. The agent is then on the <span class="ui">Agents</span> page like magpie’s own: pick one of magpie’s models in its row and magpie writes it into the agent’s config, with the gateway’s address and a key of the agent’s own; switch it off and everything goes back to how the user had it. The example below adds <a href="https://aider.chat">Aider</a>.</p>
+1
View File
@@ -776,6 +776,7 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
</div>
<p>设置 → 插件里会按这些名字列出每个插件的工具,并能复制服务器地址。<code>args</code> 可以是 zod 字段表(<code>tool.schema</code> 就是 zod)、zod 对象或 JSON Schema 对象。智能体会看到它,magpie 在 <code>execute</code> 运行前按它检查调用的参数;参数不对时回一个写明是哪个参数的错误。<code>ctx</code> 与 OpenCode 的相同,<code>agent</code> 是发起调用的智能体。每个工具最多运行 55 秒,到时 <code>ctx.abort</code> 触发。</p>
<p>这个服务器由内置插件 <span class="ui">插件工具</span> 提供。只要有已开启的插件提供工具,它就保持开启;关闭时不列出任何工具,调用会说明它已关闭。用网关密钥发起的调用计入该密钥的限额。工具和提供方插件一样,以你的权限在插件宿主里运行,结果只回给调用它的智能体。</p>
<p>每个提供工具的插件也会在资料库的 MCP 页里成为一个独立的服务器,以插件的短名命名(如 <code>search1api</code>),不用再手动添加地址。开启 <a href="mcp-hub.html">MCP 聚合</a>时,它的工具会出现在每个接入聚合的智能体里,名为 <code>search1api__search</code>;和资料库里其他服务器一样,可以按智能体开关,或单独关掉某个工具。删掉后,只有把插件移除再重新添加才会再出现。</p>
<h2 id="agents"><a class="anchor" href="#agents">Agent 插件</a></h2>
<p>插件还可以添加一个 <em>Agent</em>:magpie 没有内置接入的那种。它说明这个 Agent 把模型写在哪里,以及还要写些什么才能让 Agent 走 magpie 的网关。这样它就和 magpie 内置的 Agent 一样出现在 <span class="ui">Agent</span> 页:在它那一行选一个 magpie 的模型,magpie 就把模型连同网关地址和这个 Agent 自己的 key 写进它的配置;关掉开关,一切恢复成用户原来的样子。下面的例子添加 <a href="https://aider.chat">Aider</a>。</p>