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.
This commit is contained in:
yetone
2026-10-15 22:36:59 +08:00
parent c505b4c458
commit 6ac7032b4b
27 changed files with 1355 additions and 18 deletions
+1
View File
@@ -7,6 +7,7 @@ These pages describe current responsibilities, runtime paths, state, and contrac
| Built-in subscriptions moving to plugins | [Provider and plugin ownership](provider-plugins.md) |
| Built-in plugins: registry, lifecycle, plugins.yml, presets, settings schemas, the window's kernel (slots, error boundary, kit) | [Plugin runtime](plugin-runtime.md) |
| Plugins that run on the gateway's requests and replies | [Gateway middleware](gateway-middleware.md) |
| Tools that plugins give, offered to every agent as an MCP server | [Plugin tools](plugin-tools.md) |
| Claude subscription turns across Claude Code runs | [Claude subscription bridge](claude-subscription-bridge.md) |
| How the gateway picks a provider, key or account, and falls back | [Gateway routing and fallback](gateway-routing.md) |
| Gateway Session Aggregation | [Gateway Session Aggregation](gateway-sessions.md) |
+10
View File
@@ -245,6 +245,16 @@ asks it.
| `plugins/budget` | Requires `settings` and `gateway`, Essential. Apply serves `budget.Limiter`, `internal/budget`'s windows and reservations as before. `InUse` counts the gateway keys with a limit (`access.List`); a keys file that can't be read is an error, so it stays on. Since it is in use whenever a key has a limit, it can only be off while none has; the 503 is for a refresh not yet seen or a plugins.yml edited by hand. The gateway's `KeepFresh` watches the keys file too, so a limit set from the CLI or the window turns it on within 2s. | [`budget.go`](../../plugins/budget/budget.go) |
| Stays in the core | What a key has used and has left (`budget.All`, `budget.Binding`) for `/v1/magpie/limit`, the Gateway page and the CLI, and `budget.Append`, so the usage ledger counts a key's use the same with the plugin on or off. The key editor's limit fields stay with the plugin off, since setting a limit is what turns it back on. | [`budget.go`](../../internal/budget/budget.go) |
## P4: community plugins at every point
P4 opens each gateway extension point to community plugins (OpenCode
plugins, npm packages in the plugin host), each behind the built-in plugin
that serves the point, so off still means off.
| Point | What a community plugin gives | Served by | Reference |
| --- | --- | --- | --- |
| Tool | Its OpenCode `tool` hook's tools, offered to every agent by magpie's MCP server at `/mcp/magpie/tools`, each named `<plugin>_<tool>`, each call held to the calling key's limit and run in the host within 55s. Off, no tool is listed and a call says the plugin is off. | `plugins/tools` ("Plugin tools", Essential; `InUse` counts the plugins on that give tools, from `plugin-tools.json`), `gwtool.PluginTools` | [Plugin tools](plugin-tools.md) |
## Source of truth and composing
What a plugin runs with is composed field by field (`Compose`), each value
+46
View File
@@ -0,0 +1,46 @@
# Plugin tools
A community plugin (an OpenCode plugin, an npm package in the plugin host) can give tools: OpenCode's `tool` hook, `{tool: {name: tool({description, args, execute})}}`. In OpenCode only OpenCode's own model can call them. magpie offers them to every agent instead, as an MCP server of its own at `/mcp/magpie/tools` (Streamable HTTP), which any agent that takes an MCP server can be given. It is the gateway's tool point (P4 of [Plugin runtime](plugin-runtime.md)) opened to community plugins. The built-in plugin `tools` serves it. The provider plugins in the same host are [Provider and plugin ownership](provider-plugins.md); the gateway middleware is [Gateway middleware](gateway-middleware.md).
## Responsibilities and sources of truth
| Part | Responsibility | Source |
| --- | --- | --- |
| Collect | Each loaded plugin's tools: the names that match `^[A-Za-z0-9_-]{1,48}$` and have an `execute`, the last of a name winning, as in OpenCode. Each tool's `args` becomes JSON Schema: a zod shape (v3 or v4, `.describe`, `.optional`, `.default`, enums, arrays, nested objects) or a zod object, while a plain JSON Schema object is kept as it is. They are returned with the plugin list (`Loaded.Tools`). | `toolsOf`, `jsonSchema`, `argsSchema`, `toolList` in [`host.js`](../../internal/plugin/host.js); `Tools` in [`tools.go`](../../internal/plugin/tools.go) |
| Run | The host's `tool` call: it checks the arguments against the tool's own zod schema (defaults filled in; a wrong argument is an error naming its path), then races `execute(args, ctx)` against `ToolTimeout` (55s, under the 60s an MCP client gives a call). `ctx` is OpenCode's: `agent` is the calling agent as the gateway knows it, `abort` fires at the timeout, and `directory` is the host's. A string answer is the text, `{output}` its output, and anything else is its JSON. | `parsedArgs`, `runTool` in `host.js`; `RunTool` in `tools.go` |
| Note | After every load the host notes which plugins gave which tools in `plugin-tools.json` (settings dir), written whole and only when it changed. `ToolsOn` counts the plugins that are on in plugins.json and have tools there. A note that can't be read or parsed is an error, so the plugin stays on. `ToolNames` is the note for a Plugins page whose host isn't running. | `noteTools`, `ToolsOn`, `ToolNames` in `tools.go` |
| Serve | `tools/list` names each tool `<plugin>_<tool>`: the plugin's short name, as its Plugins row names it (opencode-weather-tools → weather-tools; a plugin added from a folder, the folder's name), at most 24 characters, in `[A-Za-z0-9_-]`, then the tool. Each name is at most 64 characters, and a name two would share gets `_2`, `_3`. `tools/call` runs one; an unknown name is error -32602. It is guarded as the search MCP server is (`serveMCP`: a web page's request is refused, a remote one needs a key), with a 4 MiB body. | [`tools_mcp.go`](../../internal/gateway/tools_mcp.go) |
| Gate | `plugins/tools` ("Plugin tools", requires `gateway`, Essential) serves `gwtool.PluginTools`. `InUse` is `plugin.ToolsOn`, so it is on while a plugin that is on gives a tool. The gateway's `KeepFresh` watches `plugin-tools.json` too. | [`plugins/tools`](../../plugins/tools/tools.go), [`gwtool.go`](../../internal/gwtool/gwtool.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| GUI | Each Installed row of a plugin that is on and gives tools lists them by their MCP names, each with its description on hover, plus a button that copies the server's address (`mcpAddress`). A plugin of tools alone has no Provider chip. | `pluginEntryJSON.Tools` in [`plugins.go`](../../internal/gui/plugins.go); `toolsLine` in `plugins.js` |
| User docs | How to write a tool and add the address to an agent | [usemagpie.ai/docs/plugins#tools](https://usemagpie.ai/docs/plugins#tools) (`site/public/docs/*plugins.html`) |
plugins.json is the source of truth for which plugins are on. The host only loads those, so only their tools are listed.
## Runtime path
1. An agent's MCP client posts `tools/list` to `/mcp/magpie/tools`. `servedTools` returns nothing while the point isn't served or no plugin is on; then the plugin host (Bun) isn't started for it. Otherwise it asks the host for its plugins' tools (`plugin.Tools`, which starts the host if need be) and names them (`namedTools`).
2. `tools/call` finds the tool by its MCP name in the same list. While the point is off it answers `isError` "magpie's Plugin tools plugin is off…", without asking the host.
3. `toolsMCPRun` holds the call to the calling gateway key's limit through `reserveFor`, the same way in as the chat APIs and the search MCP server ([Plugin runtime](plugin-runtime.md), budget point). A refusal, or a limited key with the Key limits plugin off, is an `isError` answer, and the tool isn't run.
4. `plugin.RunTool` asks the host to run it. The answer, or the error (`<tool>'s arguments are wrong: …`, `<tool> took longer than 55s`, or what the tool threw), goes back to the agent as the call's text, with `isError` set on an error.
A tool's answer goes back to the agent that called it, on this computer or on a shared one with a key. It never goes to a vendor, so masking has nothing to do with it. Whatever the agent sends a model next is masked as any request is.
## Constraints and failure behavior
- Off means off: no tool is listed, a call says the plugin is off, and the host is not asked (`TestToolsMCPOff`).
- 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.
## Verification
```sh
go test ./internal/plugin/ -run Tool
go test ./internal/gateway/ -run 'ToolsMCP|ServingGates|OwnMCPRejects' -timeout 45m
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
```
The example plugin the tests load is [`internal/plugin/testdata/tools`](../../internal/plugin/testdata/tools/index.js): tools with a zod shape, a raw JSON Schema, one that sleeps past the timeout, one that throws, and two that are left out.
+3 -2
View File
@@ -512,7 +512,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
defer stopLimits()
freshCtx, stopFresh := context.WithCancel(ctx)
defer stopFresh()
go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path(), provider.Path(), plugin.ListPath(), access.Path())
go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path(), provider.Path(), plugin.ListPath(), plugin.ToolsPath(), access.Path())
srv := &http.Server{Handler: lanGuard(s.Handler()), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute}
// the magpie serving the gateway, and only it, keeps the saved accounts
// signed in, so two never refresh one sign-in at once
@@ -654,6 +654,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("/mcp/{name}", s.mcpProxy)
mux.HandleFunc(SearchMCPPath, s.searchMCP)
mux.HandleFunc(VisionMCPPath, s.visionMCP)
mux.HandleFunc(ToolsMCPPath, s.toolsMCP)
mux.HandleFunc(CodexPath+"/", s.codexBackend)
mux.HandleFunc("GET "+CodexCatalogPath, s.codexCatalog)
mux.HandleFunc("GET /v1beta/models", s.geminiModels)
@@ -681,7 +682,7 @@ func responsesOverHTTP(w http.ResponseWriter, r *http.Request) {
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version, "models": len(provider.Catalog()), "window": Window,
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", SearchMCPPath, VisionMCPPath}})
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", SearchMCPPath, VisionMCPPath, ToolsMCPPath}})
}
// quotas is what is left of every subscription, plan and key magpie has,
@@ -22,6 +22,7 @@ func TestOwnMCPRejectsOversizedBody(t *testing.T) {
}{
{"vision", VisionMCPPath, visionMCPBody},
{"search", SearchMCPPath, 1 << 20},
{"tools", ToolsMCPPath, toolsMCPBody},
} {
t.Run(tc.name, func(t *testing.T) {
s, upstream := eyed(t)
+206
View File
@@ -0,0 +1,206 @@
package gateway
import (
"context"
"encoding/json"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/plugin"
)
// The tools the user's plugins give (OpenCode's tool hook: {tool: {name:
// tool({description, args, execute})}}) are an MCP server of magpie's
// own, so every agent that takes an MCP server can call them, not only
// OpenCode: Streamable HTTP at ToolsMCPPath, guarded as the search MCP
// server is (serveMCP), each call held to the calling gateway key's limit
// (reserveFor) and run in the plugin host. plugins/tools serves it on the
// tool point (gwtool.PluginTools); off, it lists no tool and runs none.
//
// A tool's answer goes back to the agent that called it on this computer
// (or a shared one with a key), never to a vendor, so masking has nothing
// to do with it; what the agent then sends a model is masked as any
// request is.
// ToolsMCPPath is where the plugin tools MCP server is served.
const ToolsMCPPath = "/mcp/magpie/tools"
// toolsMCPBody is the longest body the server takes: a tool's arguments
// may carry a file's text.
const toolsMCPBody = 4 << 20
// pluginTools and runPluginTool are the plugin host's, a test's fakes in
// their place.
var (
pluginTools = plugin.Tools
runPluginTool = plugin.RunTool
)
// errToolsOff is what a call is answered while plugins/tools is off.
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)
}
// mcpTool is one plugin tool as the server names it.
type mcpTool struct {
spec string
plugin.Tool
name string // <plugin>_<tool>
}
var unsafeToolChars = regexp.MustCompile(`[^A-Za-z0-9_-]+`)
// toolPrefix is the plugin's part of its tools' names: its short name
// (opencode-weather-tools → weather-tools), in the characters MCP clients
// take.
func toolPrefix(spec string) string {
p := strings.Trim(unsafeToolChars.ReplaceAllString(plugin.ShortName(plugin.Name(spec)), "-"), "-_")
if p == "" {
p = "plugin"
}
if len(p) > 24 {
p = p[:24]
}
return p
}
// servedTools are the tools of the plugins that are on (namedTools). With
// no plugin on, the plugin host isn't started for it.
func servedTools(ctx context.Context) ([]mcpTool, error) {
if !gwtool.Served(gwtool.PluginTools) || !anyPluginOn() {
return nil, nil
}
pts, err := pluginTools(ctx)
if err != nil {
return nil, err
}
return namedTools(pts), nil
}
// namedTools are pts' tools, each named <plugin>_<tool> (64 characters at
// most, the limit of some clients), a name two would share told apart by
// a number.
func namedTools(pts []plugin.PluginTools) []mcpTool {
var out []mcpTool
seen := map[string]bool{}
for _, pt := range pts {
pre := toolPrefix(pt.Spec)
for _, t := range pt.Tools {
base := pre + "_" + t.Name
name := base
if len(name) > 64 {
name = name[:64]
}
for i := 2; seen[name]; i++ {
suf := "_" + strconv.Itoa(i)
b := base
if len(b)+len(suf) > 64 {
b = b[:64-len(suf)]
}
name = b + suf
}
seen[name] = true
out = append(out, mcpTool{spec: pt.Spec, Tool: t, name: name})
}
}
return out
}
// ToolNames are the names the plugin tools MCP server gives pts' tools,
// by spec and the tool's own name, as the Plugins page shows them.
func ToolNames(pts []plugin.PluginTools) map[string]map[string]string {
out := map[string]map[string]string{}
for _, t := range namedTools(pts) {
if out[t.spec] == nil {
out[t.spec] = map[string]string{}
}
out[t.spec][t.Name] = t.name
}
return out
}
// anyPluginOn is whether plugins.json has a plugin that is on: none, and
// there is no tool to list without starting Bun.
var anyPluginOn = func() bool {
for _, e := range plugin.Load().Plugins {
if !e.Off {
return true
}
}
return false
}
func (s *Server) toolsMCPCall(r *http.Request, m mcpMessage) (any, map[string]any) {
switch m.Method {
case "initialize":
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.",
}, nil
case "ping":
return map[string]any{}, nil
case "tools/list":
ts, err := servedTools(r.Context())
if err != nil {
return nil, map[string]any{"code": -32603, "message": "magpie couldn't load its plugins: " + err.Error()}
}
list := make([]any, 0, len(ts))
for _, t := range ts {
schema := t.Schema
if len(schema) == 0 || !json.Valid(schema) {
schema = json.RawMessage(`{"type":"object","properties":{}}`)
}
list = append(list, map[string]any{
"name": t.name,
"description": t.Description,
"inputSchema": schema,
})
}
return map[string]any{"tools": list}, nil
case "tools/call":
var p struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if err := json.Unmarshal(m.Params, &p); err != nil {
return nil, map[string]any{"code": -32602, "message": "invalid params: " + err.Error()}
}
if !gwtool.Served(gwtool.PluginTools) {
return toolResult(errToolsOff, true), nil
}
ts, err := servedTools(r.Context())
if err != nil {
return toolResult("magpie couldn't load its plugins: "+err.Error(), true), nil
}
for _, t := range ts {
if t.name == p.Name {
said, err := s.toolsMCPRun(r, t, p.Arguments)
if err != nil {
return toolResult(err.Error(), true), nil
}
return toolResult(said, false), nil
}
}
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}
}
// toolsMCPRun runs one plugin tool, held to the calling gateway key's
// limit.
func (s *Server) toolsMCPRun(r *http.Request, t mcpTool, args json.RawMessage) (string, error) {
release, err := reserveFor(access.Caller(r.Context()), int64(len(args)), "", limitClock())
if err != nil {
return "", err
}
defer release()
return runPluginTool(r.Context(), t.spec, t.Name, args, callerOf(r).agent)
}
+154
View File
@@ -0,0 +1,154 @@
package gateway
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/plugin"
)
// fakePluginTools has the gateway's plugin tools be pts and record the
// calls run, with no plugin host.
func fakePluginTools(t *testing.T, pts []plugin.PluginTools) *[]string {
t.Helper()
var ran []string
listed := 0
oldList, oldRun, oldOn := pluginTools, runPluginTool, anyPluginOn
pluginTools = func(context.Context) ([]plugin.PluginTools, error) { listed++; return pts, nil }
runPluginTool = func(_ context.Context, spec, name string, args json.RawMessage, agent string) (string, error) {
ran = append(ran, spec+" "+name+" "+string(args)+" "+agent)
return "ran " + name, nil
}
anyPluginOn = func() bool { return true }
t.Cleanup(func() { pluginTools, runPluginTool, anyPluginOn = oldList, oldRun, oldOn })
return &ran
}
func toolsPost(h http.Handler, body string, hdr ...string) *httptest.ResponseRecorder {
r := httptest.NewRequest(http.MethodPost, ToolsMCPPath, strings.NewReader(body))
r.RemoteAddr, r.Host = "127.0.0.1:50000", "127.0.0.1:3425"
r.Header.Set("Content-Type", "application/json")
for i := 0; i+1 < len(hdr); i += 2 {
r.Header.Set(hdr[i], hdr[i+1])
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
const toolsList = `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`
func toolsCall(name, args string) string {
return `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"` + name + `","arguments":` + args + `}}`
}
// The plugin tools MCP server lists the tools of the plugins that are on,
// each as <plugin>_<tool> with its JSON Schema, two of one name told
// apart, and runs one in the plugin that gives it with the agent's
// arguments, naming the agent. A name no plugin gives is an error, and a
// web page is turned away.
func TestToolsMCPServesPluginTools(t *testing.T) {
fresh(t)
ran := fakePluginTools(t, []plugin.PluginTools{
{Spec: "@acme/opencode-weather-tools@1.2.0", Tools: []plugin.Tool{
{Name: "now", Description: "The weather now.", Schema: json.RawMessage(`{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}`)},
}},
{Spec: "/Users/me/weather-tools", Tools: []plugin.Tool{{Name: "now", Description: "Mine."}}},
})
h := lanGuard(New().Handler())
if m := readMCP(t, toolsPost(h, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26"}}`)); m.Result.ServerInfo.Name != "magpie-tools" || m.Result.ProtocolVersion != "2025-03-26" {
t.Fatalf("initialize = %+v", m)
}
m := readMCP(t, toolsPost(h, toolsList))
var names []string
for _, x := range m.Result.Tools {
names = append(names, x.Name)
}
if strings.Join(names, " ") != "weather-tools_now weather-tools_now_2" {
t.Fatalf("tools = %v", names)
}
if r := m.Result.Tools[0].InputSchema.Required; len(r) != 1 || r[0] != "city" {
t.Errorf("schema required = %v", r)
}
m = readMCP(t, toolsPost(h, toolsCall("weather-tools_now_2", `{"city":"Oslo"}`), "User-Agent", "claude-cli/2.1.0"))
if m.Result.IsError || len(m.Result.Content) != 1 || m.Result.Content[0].Text != "ran now" {
t.Fatalf("call = %+v", m)
}
if len(*ran) != 1 || !strings.HasPrefix((*ran)[0], `/Users/me/weather-tools now {"city":"Oslo"} `) {
t.Errorf("ran %q", *ran)
}
if m := readMCP(t, toolsPost(h, toolsCall("nope_now", `{}`))); m.Error == nil || m.Error.Code != -32602 {
t.Errorf("an unknown tool: %+v", m)
}
if w := toolsPost(h, toolsList, "Origin", "https://evil.example"); w.Code != http.StatusForbidden {
t.Errorf("a web page: %d", w.Code)
}
if len(*ran) != 1 {
t.Errorf("ran %q", *ran)
}
}
// Off (plugins/tools not serving the tool point in a gateway that gates
// it), the server lists no tool and runs none, and says the plugin is off;
// the plugin host isn't asked. With no plugin on at all, it isn't started
// to list nothing.
func TestToolsMCPOff(t *testing.T) {
fresh(t)
ran := fakePluginTools(t, []plugin.PluginTools{{Spec: "opencode-x", Tools: []plugin.Tool{{Name: "y"}}}})
asked := 0
pluginTools = func(context.Context) ([]plugin.PluginTools, error) {
asked++
return []plugin.PluginTools{{Spec: "opencode-x", Tools: []plugin.Tool{{Name: "y"}}}}, nil
}
h := lanGuard(New().Handler())
stop := gwtool.Gate()
defer stop()
if m := readMCP(t, toolsPost(h, toolsList)); len(m.Result.Tools) != 0 || m.Error != nil {
t.Errorf("off, listed %+v", m)
}
m := readMCP(t, toolsPost(h, toolsCall("x_y", `{}`)))
if !m.Result.IsError || len(m.Result.Content) == 0 || !strings.Contains(m.Result.Content[0].Text, "Plugin tools plugin is off") {
t.Errorf("off, a call said %+v", m)
}
if len(*ran) != 0 || asked != 0 {
t.Errorf("off: ran %q, the host asked %d times", *ran, asked)
}
on := gwtool.Serve(gwtool.PluginTools)
if m := readMCP(t, toolsPost(h, toolsList)); len(m.Result.Tools) != 1 {
t.Errorf("on again, listed %+v", m)
}
anyPluginOn = func() bool { return false }
asked = 0
if m := readMCP(t, toolsPost(h, toolsList)); len(m.Result.Tools) != 0 || asked != 0 {
t.Errorf("no plugin on: listed %+v, the host asked %d times", m, asked)
}
on()
}
// A gateway key's limit holds each tool call: a key held to a limit
// nothing serves (the Key limits plugin off) is refused, and the tool
// isn't run.
func TestToolsMCPHeldToKeyLimit(t *testing.T) {
fresh(t)
ran := fakePluginTools(t, []plugin.PluginTools{{Spec: "opencode-x", Tools: []plugin.Tool{{Name: "y"}}}})
withoutLimits(t)
keys, _ := newCaller(t, "Capped")
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 700})
capped := access.Identity{KeyID: keys[0].ID, KeyName: "Capped", Limit: &access.Limit{Period: "day", Tokens: 700}}
s := New()
r := httptest.NewRequest("POST", ToolsMCPPath, nil).WithContext(access.WithIdentity(t.Context(), capped))
res, rpcErr := s.toolsMCPCall(r, mcpMessage{ID: json.RawMessage("1"), Method: "tools/call", Params: json.RawMessage(`{"name":"x_y","arguments":{}}`)})
b, _ := json.Marshal(res)
if rpcErr != nil || !strings.Contains(string(b), `"isError":true`) || !strings.Contains(string(b), "Key limits plugin") {
t.Errorf("a limited key with limits off: %s %v", b, rpcErr)
}
if len(*ran) != 0 {
t.Errorf("ran %q", *ran)
}
}
+28
View File
@@ -773,6 +773,13 @@ const I18N = {
"Models that can't search the web search with a provider that can, or a search API": "不能联网搜索的模型,借能搜索的提供商或搜索 API 来搜",
"1 search source set up": "已设置 1 个搜索来源",
"{n} search sources set up": "已设置 {n} 个搜索来源",
"Plugin tools": "插件工具",
"Offer the tools your plugins give to every agent, as an MCP server": "把插件提供的工具通过一个 MCP 服务器给每个智能体用",
"1 plugin gives tools": "1 个插件提供工具",
"{n} plugins give tools": "{n} 个插件提供工具",
"Tools for every agent: {names}": "给每个智能体的工具:{names}",
"MCP server address": "MCP 服务器地址",
"Copy the MCP server's address ({url}): add it to an agent as an MCP server (Streamable HTTP)": "复制 MCP 服务器地址({url}):在智能体里把它添加为 MCP 服务器(Streamable HTTP)",
"Key limits": "密钥限额",
"Hold each gateway key to the tokens or estimated cost you set for it": "让每个网关密钥只用到你为它设的 Token 数或估算费用",
"1 key with a limit": "1 个密钥设了限额",
@@ -4356,6 +4363,13 @@ const I18N = {
"Models that can't search the web search with a provider that can, or a search API": "不能聯網搜尋的模型,借能搜尋的提供商或搜尋 API 來搜",
"1 search source set up": "已設定 1 個搜尋來源",
"{n} search sources set up": "已設定 {n} 個搜尋來源",
"Plugin tools": "外掛工具",
"Offer the tools your plugins give to every agent, as an MCP server": "把外掛提供的工具透過一個 MCP 伺服器給每個代理使用",
"1 plugin gives tools": "1 個外掛提供工具",
"{n} plugins give tools": "{n} 個外掛提供工具",
"Tools for every agent: {names}": "給每個代理的工具:{names}",
"MCP server address": "MCP 伺服器位址",
"Copy the MCP server's address ({url}): add it to an agent as an MCP server (Streamable HTTP)": "複製 MCP 伺服器位址({url}):在代理中把它新增為 MCP 伺服器(Streamable HTTP)",
"Key limits": "密鑰限額",
"Hold each gateway key to the tokens or estimated cost you set for it": "讓每個閘道密鑰只用到你為它設的 Token 數或估算費用",
"1 key with a limit": "1 個密鑰設了限額",
@@ -7911,6 +7925,13 @@ const I18N = {
"Models that can't search the web search with a provider that can, or a search API": "ウェブ検索できないモデルは、検索できるプロバイダーか検索 API で検索します",
"1 search source set up": "1 個の検索元を設定済み",
"{n} search sources set up": "{n} 個の検索元を設定済み",
"Plugin tools": "プラグインのツール",
"Offer the tools your plugins give to every agent, as an MCP server": "プラグインのツールを MCP サーバーとしてすべてのエージェントに提供します",
"1 plugin gives tools": "1 個のプラグインがツールを提供",
"{n} plugins give tools": "{n} 個のプラグインがツールを提供",
"Tools for every agent: {names}": "すべてのエージェントのツール:{names}",
"MCP server address": "MCP サーバーのアドレス",
"Copy the MCP server's address ({url}): add it to an agent as an MCP server (Streamable HTTP)": "MCP サーバーのアドレス({url})をコピー:エージェントに MCP サーバー(Streamable HTTP)として追加します",
"Key limits": "キーの上限",
"Hold each gateway key to the tokens or estimated cost you set for it": "各ゲートウェイキーを、設定したトークン数か推定費用までに抑えます",
"1 key with a limit": "上限のあるキー 1 個",
@@ -11480,6 +11501,13 @@ const I18N = {
"Models that can't search the web search with a provider that can, or a search API": "Modelle, die nicht im Web suchen können, suchen über einen Anbieter, der es kann, oder eine Such-API",
"1 search source set up": "1 Suchquelle eingerichtet",
"{n} search sources set up": "{n} Suchquellen eingerichtet",
"Plugin tools": "Plugin-Werkzeuge",
"Offer the tools your plugins give to every agent, as an MCP server": "Die Werkzeuge deiner Plugins jedem Agenten als MCP-Server anbieten",
"1 plugin gives tools": "1 Plugin bietet Werkzeuge",
"{n} plugins give tools": "{n} Plugins bieten Werkzeuge",
"Tools for every agent: {names}": "Werkzeuge für jeden Agenten: {names}",
"MCP server address": "Adresse des MCP-Servers",
"Copy the MCP server's address ({url}): add it to an agent as an MCP server (Streamable HTTP)": "Adresse des MCP-Servers kopieren ({url}): in einem Agenten als MCP-Server (Streamable HTTP) hinzufügen",
"Key limits": "Schlüssel-Limits",
"Hold each gateway key to the tokens or estimated cost you set for it": "Jeden Gateway-Schlüssel auf die Tokens oder geschätzten Kosten begrenzen, die du für ihn festlegst",
"1 key with a limit": "1 Schlüssel mit Limit",
+4
View File
@@ -82,6 +82,10 @@ button.pm-chip { border: 0; font-family: inherit; cursor: pointer; }
button.pm-chip.up:hover:not(:disabled) { background: var(--accent); color: var(--accent-fg); }
button.pm-chip:disabled { cursor: default; opacity: .6; }
.pm-mw-fail { color: var(--red); }
/* a plugin's tools: the names on one line, the MCP server's address to copy */
.pm-row .sub.pm-tools { display: flex; align-items: center; gap: 6px; min-width: 0; }
.pm-tools > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pm-tools > .copy { flex: none; width: 20px; height: 20px; }
.pm-chip.bad { background: var(--red-soft); color: var(--red); }
.pm-chip.moved { gap: 4px; background: var(--accent-soft); color: var(--accent); }
.pm-chip.moved .dot { width: 5px; height: 5px; border-radius: 50%; background: currentColor; }
+20 -3
View File
@@ -1015,7 +1015,9 @@
const ag = e.agent;
if (mw || e.isMiddleware) nm.append(kindChip("mw"));
if (ag || e.isAgent) nm.append(kindChip("ag"));
if (e.providers?.length || !(e.middlewareOnly || e.inMagpieOnly || (mw && !e.isMiddleware) || (ag && !e.isAgent))) nm.append(kindChip("pv"));
// a plugin of tools alone signs in to nothing: no Provider chip
const toolsOnly = !!e.tools?.length && !e.providers?.length;
if (e.providers?.length || !(e.middlewareOnly || e.inMagpieOnly || toolsOnly || (mw && !e.isMiddleware) || (ag && !e.isAgent))) nm.append(kindChip("pv"));
who.append(nm);
const subs = subsOf(pkg);
const sub = el("div", "sub");
@@ -1046,8 +1048,8 @@
else if (!x.signedIn && subs.some((y) => y.signedIn)) s.title = t("{name} is a subscription of its own; {other} works without it", { name: x.name, other: subs.find((y) => y.signedIn).name });
sub.append(s);
}
} else if ((mw || ag) && !e.providers.length) {
// only middleware or an agent: its own line says what it does
} else if ((mw || ag || toolsOnly) && !e.providers.length) {
// only middleware, an agent or tools: its own line says what it does
} else if (clashes.length && !e.providers.length) {
// its own line below says whose it is
} else if (e.providers.length) sub.textContent = t("Signs in to {names}", { names: e.providers.join(t(", ")) });
@@ -1060,6 +1062,7 @@
if (!ask) for (const c of clashes) who.append(clashLine(e, c, nameOfSpec));
if (mw && !e.off && !ask) who.append(mwLine(mw));
if (ag && !e.off && !ask) who.append(agentLine(ag));
if (e.tools?.length && !e.off && !ask) who.append(toolsLine(e.tools));
if (mw && !e.off && !ask && editing?.pkg === pkg) who.append(optionsEditor(e));
// the plugin's own picture (package.json's magpie.icon) before its
// first provider's, which a plugin of several gives each its own (#1775)
@@ -1224,6 +1227,20 @@
return d;
}
// toolsLine is the tools a plugin gives, which magpie's plugin tools MCP
// server offers every agent: each by the name an agent sees, its
// description on hover, and the server's address to copy into an agent
function toolsLine(tools) {
const d = el("div", "sub pm-mw pm-tools");
d.append(el("span", "", t("Tools for every agent: {names}", { names: tools.map((x) => x.mcp || x.name).join(t(", ")) })));
d.title = tools.map((x) => (x.mcp || x.name) + (x.description ? " — " + x.description : "")).join("\n");
const url = mcpAddress(state.settings || {}, "/mcp/magpie/tools");
const b = copyBtn(url, t("MCP server address"));
b.title = t("Copy the MCP server's address ({url}): add it to an agent as an MCP server (Streamable HTTP)", { url });
d.append(b);
return d;
}
function mwLine(m) {
const d = el("div", "sub pm-mw");
if (m.error) {
+4 -4
View File
@@ -44,14 +44,14 @@ func TestBuiltinSwitch(t *testing.T) {
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if len(out) != 13 {
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 and key
// limits 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 == "usage") || b.On != (b.State == pluginrt.Active) {
// 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)
}
}
+38
View File
@@ -10,6 +10,7 @@ import (
"time"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/middleware"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
@@ -138,6 +139,17 @@ type pluginEntryJSON struct {
// the host runs one plugin for each, and the row says which, with a
// way to pick this one
Clashes []pluginClashJSON `json:"clashes,omitempty"`
// Tools are the tools it gives, which magpie's plugin tools MCP server
// offers every agent under MCP's name: with their descriptions while
// the host runs, by name alone from what it noted last when it doesn't
Tools []pluginToolJSON `json:"tools,omitempty"`
}
// pluginToolJSON is one tool a plugin gives, as its row lists it.
type pluginToolJSON struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
MCP string `json:"mcp"` // its name on the MCP server
}
// pluginClashJSON is a provider two plugins sign in to, as a row says it.
@@ -172,6 +184,8 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON {
names := map[string][]string{}
clashes := map[string][]plugin.Clash{}
idName := map[string]string{}
var tools []plugin.PluginTools
asked := false
if len(l.Plugins) > 0 && (plugin.Running() || plugin.HasBun()) {
loaded, err := plugin.Plugins(ctx)
if err != nil {
@@ -179,9 +193,25 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON {
}
for _, p := range loaded {
errs[p.Spec] = p.Error
if p.Error == "" && len(p.Tools) > 0 {
tools = append(tools, plugin.PluginTools{Spec: p.Spec, Tools: p.Tools})
}
}
clashes = plugin.Clashes(loaded)
asked = err == nil
}
if !asked {
for _, e := range l.Plugins {
var ts []plugin.Tool
for _, n := range plugin.ToolNames()[e.Spec] {
ts = append(ts, plugin.Tool{Name: n})
}
if len(ts) > 0 && !e.Off {
tools = append(tools, plugin.PluginTools{Spec: e.Spec, Tools: ts})
}
}
}
toolNames := gateway.ToolNames(tools)
// each plugin's subscriptions, by the names it gave last (plugin.Cached,
// which holds them without starting the host or asking anyone, and asks
// the plugins again in the background when a sign-in or the plugins
@@ -243,6 +273,14 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON {
}
j.Clashes = append(j.Clashes, pluginClashJSON{Clash: c, Name: n})
}
for _, pt := range tools {
if pt.Spec != e.Spec || e.Off {
continue
}
for _, x := range pt.Tools {
j.Tools = append(j.Tools, pluginToolJSON{Name: x.Name, Description: x.Description, MCP: toolNames[e.Spec][x.Name]})
}
}
j.Moved = provider.MovedOnto(e.Spec)
if j.Moved == nil {
j.Moved = []string{}
+6 -5
View File
@@ -30,14 +30,15 @@ const PLUGINS = [
{ id: "routing", name: "Routing", sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups", one: "1 group in use", many: "{n} groups in use" },
{ id: "search", name: "Web search", sub: "Models that can't search the web search with a provider that can, or a search API", one: "1 search source set up", many: "{n} search sources set up" },
{ id: "sessions", name: "Sessions", sub: "Your agents' past conversations: read, search, resume and export them", one: "Recording gateway conversations", many: "Recording gateway conversations" },
{ id: "tools", name: "Plugin tools", sub: "Offer the tools your plugins give to every agent, as an MCP server", one: "1 plugin gives tools", many: "{n} plugins give tools" },
{ id: "usage", name: "Usage", sub: "Your allowances, what was spent and on what, each request, and what filled the context window" },
{ id: "warmups", name: "Warm-up and check-in", sub: "Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits", one: "1 warm-up or check-in on", many: "{n} warm-ups and check-ins on" },
];
// a new install's (the Essentials preset): all off but the Gateway, Routing
// and Usage pages, the routing strategies, the gateway middleware, privacy
// masking, web search and key limits, which are essential, and two routing
// groups the user made
const START = { budget: [true, 0], gateway: [true, 0], groups: [false, 2], library: [false, 0], middleware: [true, 0], otel: [false, 0], redact: [true, 0], rotation: [true, 0], routing: [true, 0], search: [true, 0], sessions: [false, 0], usage: [true, 0], warmups: [false, 0] };
// masking, web search, key limits and plugin tools, which are essential,
// and two routing groups the user made
const START = { budget: [true, 0], gateway: [true, 0], groups: [false, 2], library: [false, 0], middleware: [true, 0], otel: [false, 0], redact: [true, 0], rotation: [true, 0], routing: [true, 0], search: [true, 0], sessions: [false, 0], tools: [true, 0], usage: [true, 0], warmups: [false, 0] };
// the Gateway page's settings, as pluginrt.SchemaOf makes them
const GATEWAY_SCHEMA = {
@@ -171,13 +172,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual([rt.on, rt.disabled], ["true", false], `${where}: the Routing page, on`);
const ro = rows.find((r) => r.id === "rotation");
assert.deepEqual([ro.on, ro.disabled], ["true", false], `${where}: the routing strategies, on`);
for (const id of ["budget", "middleware", "redact", "search"]) {
for (const id of ["budget", "middleware", "redact", "search", "tools"]) {
const r = rows.find((r) => r.id === id);
assert.deepEqual([r.on, r.disabled], ["true", false], `${where}: ${id}, on`);
}
const us = rows.find((r) => r.id === "usage");
assert.deepEqual([us.on, us.disabled], ["true", false], `${where}: the Usage page, on`);
for (const r of rows.filter((r) => !["budget", "groups", "gateway", "middleware", "redact", "rotation", "routing", "search", "usage"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
for (const r of rows.filter((r) => !["budget", "groups", "gateway", "middleware", "redact", "rotation", "routing", "search", "tools", "usage"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
await page.locator('#builtinList [data-id="groups"] [role="switch"]').click({ force: true });
await page.waitForTimeout(100);
assert.deepEqual(posts, [], `${where}: a locked switch posts nothing`);
+105
View File
@@ -0,0 +1,105 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Plugins that give tools on the Plugins page: the row lists each tool by
// the name magpie's plugin tools MCP server gives it, its description on
// hover, and a button that copies the server's address. A plugin of tools
// alone wears no Provider chip and isn't said to sign in to nothing; one
// that signs in too keeps its line; one switched off lists none. Every
// language, both engines, at a narrow width too; the API is faked here.
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 WEATHER = "/Users/x/pl/weather-tools", BOTH = "/Users/x/pl/both", OFF = "/Users/x/pl/off";
const state = { bun: true, bunVersion: "1.3.0", named: true, plugins: [
{ spec: WEATHER, providers: [], moved: [], named: true, tools: [
{ name: "now", description: "The weather now in a city.", mcp: "weather-tools_now" },
{ name: "week", description: "Seven days ahead.", mcp: "weather-tools_week" },
] },
{ spec: BOTH, providers: ["Acme"], moved: [], named: true, tools: [{ name: "lookup", mcp: "both_lookup" }] },
{ spec: OFF, off: true, providers: [], moved: [], tools: [{ name: "x", mcp: "off_x" }] },
] };
function server(lang) {
return async (route) => {
const url = new URL(route.request().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:"light",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: "light", gateway: "http://127.0.0.1:3425" } });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/gateway/trace") return json({ routes: [] });
if (url.pathname === "/api/plugins") return json(state);
if (url.pathname === "/api/plugins/listings") return json({ listings: [] });
if (url.pathname === "/api/plugins/market") return json({ listings: [], state });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const L = {
en: { installed: "Installed", tools: "Tools for every agent: weather-tools_now, weather-tools_week", nothing: "Signs in to nothing", provider: "Provider" },
zh: { installed: "已安装", tools: "给每个智能体的工具:weather-tools_now、weather-tools_week", nothing: "不能登录", provider: "供应商" },
"zh-TW": { installed: "已安裝", tools: /^給每個代理的工具:weather-tools_now/ },
ja: { installed: "インストール済み", tools: /^すべてのエージェントのツール:weather-tools_now/ },
de: { installed: "Installiert", tools: /^Werkzeuge für jeden Agenten: weather-tools_now/ },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": plugin tools in Installed", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of Object.keys(L)) for (const width of [980, 420]) {
await t.test(lang + " " + width, async () => {
const w = L[lang];
const ctx = await browser.newContext({ viewport: { width, height: 820 } });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang));
// what Copy put on the clipboard, without the system's
await page.addInitScript(() => {
window.__copied = [];
Object.defineProperty(navigator, "clipboard", { value: { writeText: async (s) => { window.__copied.push(s); } }, configurable: true });
});
await page.goto("http://magpie.test/?view=plugins");
const view = page.locator("#view-plugins");
await view.page().locator(":is(.lib-tabs .opt, .nav-s):visible", { hasText: w.installed }).click();
const row = (name) => view.locator(".pm-row").filter({ has: page.locator(".name", { hasText: name }) });
const weather = row("weather-tools");
await weather.waitFor();
const line = weather.locator(".pm-tools");
const said = (await line.locator("span").first().innerText()).trim();
if (typeof w.tools === "string") assert.equal(said, w.tools);
else assert.match(said, w.tools);
assert.match(await line.getAttribute("title"), /weather-tools_now — The weather now in a city\.\nweather-tools_week — Seven days ahead\./);
if (w.nothing) assert.ok(!(await weather.innerText()).includes(w.nothing), "a plugin of tools isn't said to sign in to nothing");
if (w.provider) assert.ok(!(await weather.locator(".pm-chip.kind").allInnerTexts()).map((x) => x.trim()).includes(w.provider), "no Provider chip on a plugin of tools alone");
await line.locator(".copy").click();
await page.waitForFunction(() => window.__copied.length > 0 || document.querySelector(".toast, #status"));
const copied = await page.evaluate(() => window.__copied);
if (copied.length) assert.equal(copied[0], "http://127.0.0.1:3425/mcp/magpie/tools");
const both = row("both");
assert.ok((await both.innerText()).includes("Acme"));
assert.ok((await both.locator(".pm-tools").innerText()).includes("both_lookup"));
assert.equal(await row("off").locator(".pm-tools").count(), 0, "a plugin off lists no tools");
const over = await page.evaluate(() => document.scrollingElement.scrollWidth - document.scrollingElement.clientWidth);
assert.ok(over <= 0, "page scrolls sideways by " + over);
const [lb, rb] = await Promise.all([line.boundingBox(), weather.boundingBox()]);
assert.ok(lb.x + lb.width <= rb.x + rb.width + 1, "the tools line overflows its row");
if (process.env.ARTIFACT_DIR) await view.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `plugin-tools-${engine}-${lang}-${width}.png`) });
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
+9 -3
View File
@@ -6,9 +6,11 @@
// serving the gateway (the CLI, the TUI) has them all, as before the
// point was there.
//
// WebSearch is the one tool now, plugins/search's: magpie's web search for
// a model that can't search by itself. Off, a vendor that searches by
// itself still does; magpie offers no search of its own.
// WebSearch is plugins/search's: magpie's web search for a model that
// can't search by itself. Off, a vendor that searches by itself still
// does; magpie offers no search of its own. PluginTools is plugins/tools':
// the tools community plugins give, served to every agent over MCP. Off,
// the server lists none and runs none.
package gwtool
import "sync"
@@ -17,6 +19,10 @@ import "sync"
// search MCP server and Codex's search when ChatGPT can't answer it.
const WebSearch = "web_search"
// PluginTools are the tools the user's plugins give (their OpenCode tool
// hook), served over magpie's plugin tools MCP server.
const PluginTools = "plugin_tools"
var gate struct {
sync.Mutex
gated int // Gate calls not yet stopped
+3
View File
@@ -499,6 +499,8 @@ type Loaded struct {
// serves, that plugin's spec: the host runs one plugin per provider
// id (Prefer)
ServedBy map[string]string `json:"servedBy,omitempty"`
// Tools are the tools its tool hook gives (tools.go)
Tools []Tool `json:"tools,omitempty"`
}
// Clash is a provider id more than one plugin signs in to. The host runs
@@ -940,6 +942,7 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) {
return nil, crashed, fmt.Errorf("starting plugins: %w", err)
}
h.loaded = res.Plugins
noteTools(res.Plugins)
for _, p := range res.Plugins {
if p.Error != "" {
log.Printf("plugin %s didn't load: %s", p.Spec, p.Error)
+161 -1
View File
@@ -1207,8 +1207,11 @@ const signsIn = (spec) => [...new Set(hooks.filter((h) => h.spec === spec && h.h
// withProviders is a loaded plugin as init tells magpie of it: the provider
// ids it signs in to, and for each one another plugin serves (two plugins
// naming one id: the host runs one), the plugin that does. magpie says so
// on the plugin's row rather than leave its provider missing.
// on the plugin's row rather than leave its provider missing. And the
// tools it gives (toolList).
function withProviders(l) {
const tools = l.error ? [] : toolList(l.spec)
if (tools.length) l = { ...l, tools }
const ids = l.error ? [] : signsIn(l.spec)
if (!ids.length) return l
const a = auths()
@@ -1216,6 +1219,162 @@ function withProviders(l) {
return { ...l, provides: ids, ...(Object.keys(servedBy).length ? { servedBy } : {}) }
}
// ---- tools ----------------------------------------------------------------
//
// A plugin's tools are OpenCode's tool hook: {tool: {name: {description,
// args, execute(args, ctx)}}}, args a zod shape (OpenCode's tool.schema is
// zod) or a JSON Schema. magpie offers them to every agent through its
// plugin tools MCP server (internal/gateway/tools_mcp.go), so each is told
// to magpie by its name, description and a JSON Schema of its arguments.
const TOOL_NAME = /^[A-Za-z0-9_-]{1,48}$/
// toolsOf are the tools the plugin spec's hooks give, the last of a name
// winning, as in OpenCode.
function toolsOf(spec) {
const m = new Map()
for (const h of hooks) {
if (h.spec !== spec) continue
const t = h.hooks.tool
if (!t || typeof t !== "object") continue
for (const [name, def] of Object.entries(t)) {
if (TOOL_NAME.test(name) && def && typeof def.execute === "function") m.set(name, def)
}
}
return m
}
// jsonSchema is a zod schema (v3 or v4) as JSON Schema, or a JSON Schema
// as it is. What it can't read is {}: any value.
function jsonSchema(z, depth = 0) {
if (!z || typeof z !== "object" || depth > 16) return {}
const desc = (o) => {
const d = typeof z.description === "string" ? z.description : z._def?.description
if (d) o.description = d
return o
}
const v4 = z._zod?.def
const v3 = z._def
if (!v4 && !v3) return z
const d = v4 ?? v3
const kind = v4 ? d.type : String(d.typeName ?? "").replace(/^Zod/, "").toLowerCase()
const inner = (x) => jsonSchema(x, depth + 1)
switch (kind) {
case "string": return desc({ type: "string" })
case "number": return desc({ type: d.format === "safeint" || d.checks?.some?.((c) => c.kind === "int" || c._zod?.def?.format === "safeint") ? "integer" : "number" })
case "int": case "bigint": return desc({ type: "integer" })
case "boolean": return desc({ type: "boolean" })
case "null": return desc({ type: "null" })
case "enum": return desc({ type: "string", enum: v4 ? Object.values(d.entries ?? {}) : [...(d.values ?? [])] })
case "literal": {
const vals = v4 ? d.values ?? [] : [d.value]
return desc(vals.length === 1 ? { const: vals[0] } : { enum: vals })
}
case "array": return desc({ type: "array", items: inner(v4 ? d.element : d.type) })
case "object": return desc(objectSchema(typeof d.shape === "function" ? d.shape() : d.shape, depth + 1))
case "optional": case "nullable": case "default": case "readonly": case "catch": case "prefault": {
const o = { ...inner(d.innerType), ...desc({}) }
if (kind === "default") try { o.default = typeof d.defaultValue === "function" ? d.defaultValue() : d.defaultValue } catch {}
return o
}
case "union": return desc({ anyOf: (d.options ?? []).map(inner) })
case "record": return desc({ type: "object", additionalProperties: inner(d.valueType) })
default: return desc({})
}
}
// optionalIn is whether a zod field may be left out.
function optionalIn(z) {
const t = z?._zod?.def?.type ?? String(z?._def?.typeName ?? "").replace(/^Zod/, "").toLowerCase()
if (z?._zod?.optin === "optional") return true
return t === "optional" || t === "default"
}
function objectSchema(shape, depth = 0) {
const properties = {}
const required = []
for (const [k, v] of Object.entries(shape ?? {})) {
properties[k] = jsonSchema(v, depth)
if (!optionalIn(v)) required.push(k)
}
return { type: "object", properties, ...(required.length ? { required } : {}) }
}
// argsSchema is a tool's arguments as JSON Schema: its args a zod shape, a
// zod object, or a JSON Schema object.
function argsSchema(args) {
if (!args || typeof args !== "object") return { type: "object", properties: {} }
if (args._zod || args._def) return jsonSchema(args)
if (typeof args.type === "string" || args.properties) return args
return objectSchema(args)
}
function toolList(spec) {
const out = []
for (const [name, def] of toolsOf(spec)) {
let schema
try {
schema = argsSchema(def.args)
} catch {
schema = { type: "object", properties: {} }
}
out.push({ name, description: shown(def.description, 2000), schema })
}
return out
}
// parsedArgs are args as the tool's zod schema parses them, as OpenCode
// does before execute: defaults filled in, a wrong argument refused. A
// JSON Schema is the tool's own to check.
function parsedArgs(name, schema, args) {
args = args && typeof args === "object" && !Array.isArray(args) ? args : {}
const fail = (r) => {
const issues = r.error?.issues ?? []
const why = issues.map((i) => `${(i.path ?? []).join(".") || "arguments"}: ${i.message}`).join("; ")
throw new Error(`${name}'s arguments are wrong: ${why || r.error?.message || "refused"}`)
}
if (!schema || typeof schema !== "object") return args
if (typeof schema.safeParse === "function") {
const r = schema.safeParse(args)
if (!r.success) fail(r)
return r.data
}
if (schema._zod || schema._def || typeof schema.type === "string" || schema.properties) return args
const out = { ...args }
for (const [k, z] of Object.entries(schema)) {
if (typeof z?.safeParse !== "function") continue
const r = z.safeParse(args[k])
if (!r.success) fail({ error: { issues: (r.error?.issues ?? [{ message: r.error?.message }]).map((i) => ({ ...i, path: [k, ...(i.path ?? [])] })) } })
if (r.data === undefined) delete out[k]
else out[k] = r.data
}
return out
}
// runTool runs the plugin spec's tool name with args, within ms: its
// answer as text (a string as it is, else JSON).
// took is ms as Go prints a duration: 300ms, 55s.
const took = (ms) => (ms % 1000 ? `${ms}ms` : `${ms / 1000}s`)
async function runTool({ spec, name, args, ms, agent }) {
const def = toolsOf(spec).get(name)
if (!def) throw new Error(`${spec} has no tool ${name}`)
args = parsedArgs(name, def.args, args)
const abort = AbortSignal.timeout(ms > 0 ? ms : 60_000)
const ctx = {
sessionID: "", messageID: "", callID: "", agent: agent ?? "",
directory, worktree: directory, abort,
metadata() {},
}
const out = await Promise.race([
Promise.resolve().then(() => def.execute(args, ctx)),
new Promise((_, reject) => abort.addEventListener("abort", () => reject(new Error(`${name} took longer than ${took(ms || 60_000)}`)), { once: true })),
])
if (typeof out === "string") return { text: out }
if (out && typeof out === "object" && typeof out.output === "string") return { text: out.output }
return { text: out === undefined ? "" : JSON.stringify(out) }
}
function authOf(provider) {
const a = auths().get(provider)
if (!a) throw new Error(`no plugin signs in to ${provider}`)
@@ -2069,6 +2228,7 @@ const handlers = {
validate: (p) => ({ error: validate(p.provider, p.method, p.key, p.value) }),
authorize,
callback,
tool: runTool,
apiKey,
load,
usage,
+66
View File
@@ -0,0 +1,66 @@
// A plugin giving tools (OpenCode's tool hook), which magpie offers every
// agent through its plugin tools MCP server. A real plugin writes
//
// import { tool } from "@opencode-ai/plugin"
// tool({ description, args: { text: tool.schema.string().describe("…") }, execute })
//
// tool.schema is zod. With no node_modules here, z below is the slice of
// zod 4 the host reads: each schema's _zod.def, its description, and
// safeParse.
const ok = (data) => ({ success: true, data })
const no = (message) => ({ success: false, error: { issues: [{ path: [], message }] } })
const base = (def, check, extra = {}) => {
const s = {
_zod: { def },
...extra,
safeParse: (v) => check(v),
describe(d) { return { ...this, description: d } },
optional() { return base({ type: "optional", innerType: this }, (v) => (v === undefined ? ok(undefined) : this.safeParse(v)), { _zod: { def: { type: "optional", innerType: this }, optin: "optional" } }) },
default(x) { return base({ type: "default", innerType: this, defaultValue: x }, (v) => (v === undefined ? ok(x) : this.safeParse(v)), { _zod: { def: { type: "default", innerType: this, defaultValue: x }, optin: "optional" } }) },
}
return s
}
const z = {
string: () => base({ type: "string" }, (v) => (typeof v === "string" ? ok(v) : no("expected string"))),
number: () => base({ type: "number" }, (v) => (typeof v === "number" ? ok(v) : no("expected number"))),
boolean: () => base({ type: "boolean" }, (v) => (typeof v === "boolean" ? ok(v) : no("expected boolean"))),
enum: (vals) => base({ type: "enum", entries: Object.fromEntries(vals.map((v) => [v, v])) }, (v) => (vals.includes(v) ? ok(v) : no("expected one of " + vals.join(", ")))),
array: (el) => base({ type: "array", element: el }, (v) => (Array.isArray(v) ? ok(v) : no("expected array"))),
}
export const ToolsExample = async () => ({
tool: {
// zod arguments: checked, defaults filled in, before execute
shout: {
description: "Says the text back in capitals.",
args: {
text: z.string().describe("What to say"),
times: z.number().default(1).describe("How many times"),
style: z.enum(["plain", "bang"]).optional(),
},
execute: async (args, ctx) => {
const one = args.text.toUpperCase() + (args.style === "bang" ? "!" : "")
return Array(args.times).fill(one).join(" ") + ` (for ${ctx.agent || "nobody"})`
},
},
// a JSON Schema, and an answer that is no string
add: {
description: "Adds numbers.",
args: { type: "object", properties: { xs: { type: "array", items: { type: "number" } } }, required: ["xs"] },
execute: async ({ xs }) => ({ sum: xs.reduce((a, b) => a + b, 0) }),
},
// one that runs past its time
sleep: {
description: "Sleeps for ms.",
args: { ms: z.number() },
execute: (args, ctx) => new Promise((res) => {
const t = setTimeout(() => res("woke"), args.ms)
ctx.abort.addEventListener("abort", () => clearTimeout(t))
}),
},
fail: { description: "Fails.", args: {}, execute: async () => { throw new Error("it broke") } },
// not tools: a name an MCP client can't take, and no execute
"bad name!": { description: "x", args: {}, execute: async () => "x" },
noexec: { description: "x", args: {} },
},
})
+6
View File
@@ -0,0 +1,6 @@
{
"name": "opencode-tools-example",
"version": "1.0.0",
"type": "module",
"main": "index.js"
}
+154
View File
@@ -0,0 +1,154 @@
package plugin
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/steady"
)
// Tool is a tool a plugin gives: OpenCode's tool hook ({tool: {name:
// tool({description, args, execute})}}), which magpie offers every agent
// through its plugin tools MCP server (internal/gateway/tools_mcp.go).
type Tool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
// Schema is its arguments as JSON Schema, made in the host from its
// zod shape
Schema json.RawMessage `json:"schema,omitempty"`
}
// PluginTools are one plugin's tools.
type PluginTools struct {
Spec string `json:"spec"`
Tools []Tool `json:"tools"`
}
// Tools are the tools the plugins the host loaded give, in plugins.json's
// order, starting the host if need be.
func Tools(ctx context.Context) ([]PluginTools, error) {
loaded, err := Plugins(ctx)
if err != nil {
return nil, err
}
var out []PluginTools
for _, l := range loaded {
if l.Error == "" && len(l.Tools) > 0 {
out = append(out, PluginTools{Spec: l.Spec, Tools: l.Tools})
}
}
return out, nil
}
// ToolTimeout is how long a tool may run before its call is answered that
// it took too long. Agents give a tool call as little as 60 s (the MCP
// SDK's request timeout), so it ends a little before that.
var ToolTimeout = 55 * time.Second
// RunTool runs the plugin spec's tool name with args (a JSON object) in
// the host: its answer as text. agent is the agent that called it, as the
// tool's context names it.
func RunTool(ctx context.Context, spec, name string, args json.RawMessage, agent string) (string, error) {
if len(args) == 0 || string(args) == "null" {
args = json.RawMessage("{}")
}
var out struct {
Text string `json:"text"`
}
err := callWithTimeout(ctx, "tool", map[string]any{
"spec": spec, "name": name, "args": args, "agent": agent,
"ms": ToolTimeout.Milliseconds(),
}, &out, ToolTimeout+5*time.Second)
if errors.Is(err, context.DeadlineExceeded) {
return "", fmt.Errorf("%s took longer than %s", name, ToolTimeout)
}
return out.Text, err
}
// toolsPath is where the tools the host last loaded are noted, by plugin:
// the Plugin tools plugin's InUse reads it, which mustn't start the host.
func toolsPath() string { return filepath.Join(settings.Dir(), "plugin-tools.json") }
// ToolsPath is the note ToolsOn reads, which the gateway watches.
func ToolsPath() string { return toolsPath() }
var toolsMu sync.Mutex
// noteTools notes which plugins the host loaded give tools, written whole.
func noteTools(loaded []Loaded) {
m := map[string][]string{}
for _, l := range loaded {
if l.Error != "" || len(l.Tools) == 0 {
continue
}
names := make([]string, 0, len(l.Tools))
for _, t := range l.Tools {
names = append(names, t.Name)
}
m[l.Spec] = names
}
b, _ := json.MarshalIndent(m, "", " ")
toolsMu.Lock()
defer toolsMu.Unlock()
old, err := steady.ReadFile(toolsPath())
if err == nil && strings.TrimSpace(string(old)) == strings.TrimSpace(string(b)) {
return
}
if len(m) == 0 && errors.Is(err, fs.ErrNotExist) {
return
}
if err := writeWhole(toolsPath(), append(b, '\n')); err != nil {
log.Printf("plugin tools: noting them: %v", err)
}
}
// ToolsOn counts the plugins on in plugins.json that gave tools when the
// host last loaded them. A note that can't be read or parsed is an error:
// not known.
func ToolsOn() (int, error) {
b, err := steady.ReadFile(toolsPath())
if errors.Is(err, fs.ErrNotExist) {
return 0, nil
}
if err != nil {
return 0, err
}
var m map[string][]string
if err := json.Unmarshal(b, &m); err != nil {
return 0, fmt.Errorf("%s: %w", toolsPath(), err)
}
n := 0
for _, e := range Load().Plugins {
if !e.Off && len(m[e.Spec]) > 0 {
n++
}
}
return n, nil
}
// ToolNames are the tools noted for each plugin, by spec, sorted: what the
// Plugins page shows for a plugin whose host isn't running.
func ToolNames() map[string][]string {
b, err := steady.ReadFile(toolsPath())
if err != nil {
return nil
}
var m map[string][]string
if json.Unmarshal(b, &m) != nil {
return nil
}
for _, v := range m {
sort.Strings(v)
}
return m
}
+116
View File
@@ -0,0 +1,116 @@
package plugin
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// A plugin's tool hook (testdata/tools): the host lists its tools, with
// zod arguments read as JSON Schema and a JSON Schema kept as it is, and
// leaves out a name an MCP client can't take and a tool with no execute.
// A tool runs with its arguments parsed as zod would (a default filled
// in, a wrong one refused), its answer as text, its error said, and one
// that runs past its time is ended. Which plugins give tools is noted for
// the Plugin tools plugin, and counted only while they are on.
func TestPluginTools(t *testing.T) {
sandbox(t)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
abs, _ := filepath.Abs("testdata/tools")
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
pts, err := Tools(ctx)
if err != nil {
t.Fatal(err)
}
if len(pts) != 1 || pts[0].Spec != abs {
t.Fatalf("tools = %+v", pts)
}
by := map[string]Tool{}
var names []string
for _, x := range pts[0].Tools {
by[x.Name] = x
names = append(names, x.Name)
}
if strings.Join(names, " ") != "shout add sleep fail" {
t.Fatalf("tool names = %v", names)
}
if by["shout"].Description != "Says the text back in capitals." {
t.Errorf("shout's description = %q", by["shout"].Description)
}
var shout map[string]any
json.Unmarshal(by["shout"].Schema, &shout)
want := `{"properties":{"style":{"enum":["plain","bang"],"type":"string"},"text":{"description":"What to say","type":"string"},"times":{"default":1,"description":"How many times","type":"number"}},"required":["text"],"type":"object"}`
if got := jsonOf(shout); got != want {
t.Errorf("shout's schema\n got %s\nwant %s", got, want)
}
if got := string(by["add"].Schema); !strings.Contains(got, `"required":["xs"]`) || !strings.Contains(got, `"items":{"type":"number"}`) {
t.Errorf("add's JSON Schema not kept: %s", got)
}
run := func(name, args string) (string, error) {
return RunTool(ctx, abs, name, json.RawMessage(args), "claude")
}
if got, err := run("shout", `{"text":"hi","style":"bang"}`); err != nil || got != "HI! (for claude)" {
t.Errorf("shout = %q, %v", got, err)
}
if got, err := run("shout", `{"text":"hi","times":2}`); err != nil || got != "HI HI (for claude)" {
t.Errorf("shout twice = %q, %v", got, err)
}
if _, err := run("shout", `{"times":2}`); err == nil || !strings.Contains(err.Error(), "text: expected string") {
t.Errorf("shout with no text: %v", err)
}
if got, err := run("add", `{"xs":[1,2,3.5]}`); err != nil || got != `{"sum":6.5}` {
t.Errorf("add = %q, %v", got, err)
}
if _, err := run("fail", `{}`); err == nil || !strings.Contains(err.Error(), "it broke") {
t.Errorf("fail: %v", err)
}
if _, err := run("noexec", `{}`); err == nil {
t.Error("a tool with no execute ran")
}
old := ToolTimeout
ToolTimeout = 300 * time.Millisecond
t0 := time.Now()
_, err = run("sleep", `{"ms":30000}`)
ToolTimeout = old
// the host answers at 300ms; Go's own backstop (ToolTimeout+5s) only
// at 5.3s, so 4s leaves room on both sides and tells the two apart
if err == nil || !strings.Contains(err.Error(), "sleep took longer than 300ms") || time.Since(t0) > 4*time.Second {
t.Errorf("a tool past its time: %v after %s", err, time.Since(t0))
}
if got, err := run("shout", `{"text":"still"}`); err != nil || !strings.HasPrefix(got, "STILL") {
t.Errorf("the host after a tool ran out of time: %q, %v", got, err)
}
// noted, and counted while on
b, err := os.ReadFile(toolsPath())
if err != nil || !strings.Contains(string(b), `"shout"`) {
t.Fatalf("noted: %s, %v", b, err)
}
if n, err := ToolsOn(); n != 1 || err != nil {
t.Errorf("ToolsOn = %d, %v", n, err)
}
if err := SetOff(abs, true); err != nil {
t.Fatal(err)
}
if n, err := ToolsOn(); n != 0 || err != nil {
t.Errorf("ToolsOn with the plugin off = %d, %v", n, err)
}
if got := ToolNames()[abs]; strings.Join(got, " ") != "add fail shout sleep" {
t.Errorf("ToolNames = %v", got)
}
// a note that can't be read is not known
if err := os.WriteFile(toolsPath(), []byte("{half"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := ToolsOn(); err == nil {
t.Error("a corrupt note counted as no tools")
}
}
+1
View File
@@ -14,6 +14,7 @@ import (
_ "github.com/yetone/magpie/plugins/routing"
_ "github.com/yetone/magpie/plugins/search"
_ "github.com/yetone/magpie/plugins/sessions"
_ "github.com/yetone/magpie/plugins/tools"
_ "github.com/yetone/magpie/plugins/usage"
_ "github.com/yetone/magpie/plugins/warmups"
)
+29
View File
@@ -0,0 +1,29 @@
// Package tools serves the tools the user's plugins give (their OpenCode
// tool hook) to every agent, over magpie's plugin tools MCP server
// (internal/gateway/tools_mcp.go, docs/subsystems/plugin-tools.md). While
// a plugin that is on gives a tool, it stays on.
//
// It serves gwtool.PluginTools on the gateway's tool point (P4 of
// docs/subsystems/plugin-runtime.md). Off, the server lists no tool and a
// call is answered that the plugin is off; the plugins' other hooks (a
// provider, auth) go on as before.
package tools
import (
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/pluginrt"
)
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "tools", API: "^1", Requires: []string{"gateway"}, Essential: true,
Name: "Plugin tools", Sub: "Offer the tools your plugins give to every agent, as an MCP server",
One: "1 plugin gives tools", Many: "{n} plugins give tools",
InUse: plugin.ToolsOn,
Apply: func(c *pluginrt.Ctx) error {
c.OnDispose(gwtool.Serve(gwtool.PluginTools))
return nil
},
})
}
+94
View File
@@ -0,0 +1,94 @@
package tools
import (
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/testenv"
)
func TestMain(m *testing.M) { testenv.Main(m) }
func manifest(t *testing.T) pluginrt.Manifest {
t.Helper()
for _, m := range pluginrt.Registered() {
if m.ID == "tools" {
return m
}
}
t.Fatal("tools not registered")
return pluginrt.Manifest{}
}
func sandbox(t *testing.T) {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, "cache"))
}
// In a process serving the gateway, on serves the plugins' tools, off
// doesn't, on again does; a process not serving it has them either way.
func TestOnServesOffDoesNot(t *testing.T) {
sandbox(t)
if !gwtool.Served(gwtool.PluginTools) {
t.Fatal("not served outside the gateway")
}
stop := gwtool.Gate()
defer stop()
rt := pluginrt.New([]pluginrt.Manifest{manifest(t)})
defer rt.Stop()
served := func(want bool) {
t.Helper()
if ok := gwtool.Served(gwtool.PluginTools); ok != want {
t.Fatalf("tools served: %v, want %v (%+v)", ok, want, rt.Statuses())
}
}
served(false)
rt.Reconcile(map[string]bool{"tools": true}, nil)
served(true)
rt.Reconcile(map[string]bool{"tools": false}, nil)
served(false)
rt.Reconcile(map[string]bool{"tools": true}, nil)
served(true)
}
// In use for each plugin on in plugins.json that gave tools when the host
// last loaded it: one off, or one that gave none, isn't counted; no note
// yet is none; a note that can't be read is not known.
func TestInUse(t *testing.T) {
sandbox(t)
inUse := manifest(t).InUse
count := func(want int) {
t.Helper()
if n, err := inUse(); err != nil || n != want {
t.Fatalf("in use %d %v, want %d", n, err, want)
}
}
count(0)
write := func(p, s string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(s), 0o600); err != nil {
t.Fatal(err)
}
}
write(plugin.ListPath(), `{"plugins":[{"spec":"opencode-a"},{"spec":"opencode-b","off":true},{"spec":"opencode-c"},{"spec":"opencode-d"}]}`)
count(0)
write(plugin.ToolsPath(), `{"opencode-a":["x"],"opencode-b":["y"],"opencode-c":[]}`)
count(1)
write(plugin.ToolsPath(), `{"opencode-a":["x"],"opencode-b":["y"],"opencode-d":["z","w"]}`)
count(2)
write(plugin.ToolsPath(), `{"opencode-a":`)
if _, err := inUse(); err == nil {
t.Fatal("a half-written note counted as known")
}
}
+30
View File
@@ -84,6 +84,7 @@
<a href="#test">テスト</a>
<a href="#publish">公開と掲載</a>
<a href="#middleware">ゲートウェイミドルウェア</a>
<a href="#tools">すべてのエージェントのツール</a>
<a href="#agents">エージェントプラグイン</a>
<a href="#pi">pi パッケージ</a>
<a href="#protocol">ホストプロトコル</a>
@@ -670,6 +671,35 @@ magpie plugin options model-map '{"mapping": {"fast": "deepseek/deepseek-chat"}}
<h3>フックが失敗したとき</h3>
<p>フックの持ち時間は、リクエストまたは応答全体で 250 ms、1 イベントで 50 ms、読み込みで 1 秒です。例外を投げたフック、時間切れになったフック、想定外の値を返したフックは、なかったものとして扱われます。つまりリクエストやイベントは元のまま送られます。設定 → プラグインには、ミドルウェアごとのフック、呼び出し回数、1 回あたりの平均時間、失敗回数と直近のエラーが表示されます。フックが見るのは、エージェントが送ったものと受け取るものそのものです。送信時は magpie のマスキングより前、受信時はマスク解除の後です。magpie 自身のリクエスト(スレッドのタイトル、ルーターの分類器)はミドルウェアを通りません。</p>
<h2 id="tools"><a class="anchor" href="#tools">すべてのエージェントのツール</a></h2>
<p>プラグインは OpenCode の <code>tool</code> フックでツールを提供でき、magpie はそれを OpenCode だけでなくすべてのエージェントに提供します。ツールは magpie 自身の MCP サーバー <code>/mcp/magpie/tools</code>(Streamable HTTP)になります。MCP サーバーを使えるエージェントにこのアドレスを追加すると、そのモデルはオンのプラグインが提供するすべてのツールを呼び出せます。名前は <code>&lt;プラグイン&gt;_&lt;ツール&gt;</code> で、プラグインの短い名前が先頭に付きます(下の例では <code>weather-tools_now</code>)。</p>
<div class="code">
<span class="lang">index.js</span>
<button class="copy" data-copy="tools-ex">コピー</button>
<pre id="tools-ex"><span class="k">import</span> { tool } <span class="k">from</span> <span class="s">"@opencode-ai/plugin"</span>
<span class="k">export const</span> WeatherTools = <span class="k">async</span> () =&gt; ({
tool: {
now: tool({
description: <span class="s">"ある都市の今の天気。"</span>,
args: { city: tool.schema.string().describe(<span class="s">"都市名(例: Berlin)"</span>) },
<span class="k">async</span> execute({ city }, ctx) {
<span class="k">const</span> r = <span class="k">await</span> fetch(<span class="s">`https://wttr.in/${encodeURIComponent(city)}?format=3`</span>, { signal: ctx.abort })
<span class="k">return</span> <span class="k">await</span> r.text() <span class="c">// テキスト。オブジェクトは JSON で返ります</span>
},
}),
},
})</pre>
</div>
<div class="code">
<span class="lang">shell</span>
<button class="copy" data-copy="tools-cli">コピー</button>
<pre id="tools-cli">magpie plugin add ./weather-tools
claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/tools <span class="c"># Claude Code。ほかのエージェントも同じアドレスを使います</span></pre>
</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>
<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>
<div class="code">
+30
View File
@@ -84,6 +84,7 @@
<a href="#test">Testing</a>
<a href="#publish">Publishing and listing</a>
<a href="#middleware">Gateway middleware</a>
<a href="#tools">Tools for every agent</a>
<a href="#agents">Agent plugins</a>
<a href="#pi">pi packages</a>
<a href="#protocol">The host protocol</a>
@@ -670,6 +671,35 @@ magpie plugin options model-map '{"mapping": {"fast": "deepseek/deepseek-chat"}}
<h3>When a hook fails</h3>
<p>A hook has 250 ms for a request or a whole reply and 50 ms for an event; loading has a second. A hook that throws, runs out of time or returns something else goes on as if it weren’t there: the request or the event is sent as it was. Settings → Plugins shows each middleware’s hooks, how many calls it had, the average time each took and how many failed, with the last error. The hooks see what the agent sent and gets back, before magpie’s redaction on the way out and after it on the way back. magpie’s own requests (thread titles, the router’s classifier) don’t go through middleware.</p>
<h2 id="tools"><a class="anchor" href="#tools">Tools for every agent</a></h2>
<p>A plugin can give tools, with OpenCode’s <code>tool</code> hook, and magpie offers them to every agent, not only OpenCode: they are an MCP server of magpie’s own at <code>/mcp/magpie/tools</code> (Streamable HTTP). Add that address to any agent that takes an MCP server, and its model can call every tool your plugins that are on give. Each is named <code>&lt;plugin&gt;_&lt;tool&gt;</code>, the plugin’s short name first: <code>weather-tools_now</code> below.</p>
<div class="code">
<span class="lang">index.js</span>
<button class="copy" data-copy="tools-ex">Copy</button>
<pre id="tools-ex"><span class="k">import</span> { tool } <span class="k">from</span> <span class="s">"@opencode-ai/plugin"</span>
<span class="k">export const</span> WeatherTools = <span class="k">async</span> () =&gt; ({
tool: {
now: tool({
description: <span class="s">"The weather now in a city."</span>,
args: { city: tool.schema.string().describe(<span class="s">"A city, e.g. Berlin"</span>) },
<span class="k">async</span> execute({ city }, ctx) {
<span class="k">const</span> r = <span class="k">await</span> fetch(<span class="s">`https://wttr.in/${encodeURIComponent(city)}?format=3`</span>, { signal: ctx.abort })
<span class="k">return</span> <span class="k">await</span> r.text() <span class="c">// text; an object is sent as its JSON</span>
},
}),
},
})</pre>
</div>
<div class="code">
<span class="lang">shell</span>
<button class="copy" data-copy="tools-cli">Copy</button>
<pre id="tools-cli">magpie plugin add ./weather-tools
claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/tools <span class="c"># Claude Code; other agents take the same address</span></pre>
</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>
<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>
<div class="code">
+30
View File
@@ -84,6 +84,7 @@
<a href="#test">测试</a>
<a href="#publish">发布与上架</a>
<a href="#middleware">网关中间件</a>
<a href="#tools">给每个智能体的工具</a>
<a href="#agents">Agent 插件</a>
<a href="#pi">pi 扩展包</a>
<a href="#protocol">宿主协议</a>
@@ -670,6 +671,35 @@ magpie plugin options model-map '{"mapping": {"fast": "deepseek/deepseek-chat"}}
<h3>钩子出错时</h3>
<p>处理请求或完整回复时,钩子有 250 毫秒;处理一个事件时有 50 毫秒;加载有 1 秒。钩子抛出异常、超时或返回了别的东西,都当作它不存在:请求或事件按原样发送。设置 → 插件会显示每个中间件的钩子、调用次数、平均每次耗时和失败次数,以及最近一次错误。钩子看到的是 agent 发出和收到的原始内容:发出时在 magpie 脱敏之前,返回时在还原之后。magpie 自己的请求(会话标题、路由分类器)不经过中间件。</p>
<h2 id="tools"><a class="anchor" href="#tools">给每个智能体的工具</a></h2>
<p>插件可以用 OpenCode 的 <code>tool</code> 钩子提供工具,magpie 把它们提供给每个智能体,不只是 OpenCode:它们组成 magpie 自己的一个 MCP 服务器,地址是 <code>/mcp/magpie/tools</code>(Streamable HTTP)。把这个地址加到任何支持 MCP 服务器的智能体里,它的模型就能调用你已开启的插件提供的每个工具。每个工具名为 <code>&lt;插件&gt;_&lt;工具&gt;</code>,插件的短名在前,例如下面的 <code>weather-tools_now</code>。</p>
<div class="code">
<span class="lang">index.js</span>
<button class="copy" data-copy="tools-ex">复制</button>
<pre id="tools-ex"><span class="k">import</span> { tool } <span class="k">from</span> <span class="s">"@opencode-ai/plugin"</span>
<span class="k">export const</span> WeatherTools = <span class="k">async</span> () =&gt; ({
tool: {
now: tool({
description: <span class="s">"某个城市现在的天气。"</span>,
args: { city: tool.schema.string().describe(<span class="s">"城市,例如 Berlin"</span>) },
<span class="k">async</span> execute({ city }, ctx) {
<span class="k">const</span> r = <span class="k">await</span> fetch(<span class="s">`https://wttr.in/${encodeURIComponent(city)}?format=3`</span>, { signal: ctx.abort })
<span class="k">return</span> <span class="k">await</span> r.text() <span class="c">// 文本;对象会以 JSON 发回</span>
},
}),
},
})</pre>
</div>
<div class="code">
<span class="lang">shell</span>
<button class="copy" data-copy="tools-cli">复制</button>
<pre id="tools-cli">magpie plugin add ./weather-tools
claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/tools <span class="c"># Claude Code;其他智能体填同一个地址</span></pre>
</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>
<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>
<div class="code">