magpie-image was the one MCP server the hub left out, because it saves what it makes on disk and needs to know whose project that is. The hub now serves its tools like any other server's and tells it where the caller works: 1. the hub answers a tools/call as SSE and asks the agent roots/list on that stream (3s), as Claude Code answers; 2. else Codex's _meta x-codex-turn-metadata.workspaces (git repos only); 3. else the Codex thread's cwd from its session file (sessions.CodexThreadCwd), only with session consent; 4. else none, and the image goes to ~/Pictures/Magpie as before. The hub passes `magpie/roots` and `magpie/client` in the call's _meta; imagemcp saves into the first root and names the agent on its usage row. Its result carries `magpie/model`, which the hub's own usage row takes, so the row says which image model drew it. A WSL agent keeps magpie-image as its own entry (the hub can't reach a path inside the distro). docs/subsystems/mcp-hub.md (mcp-router.md after the next commit), gateway-routing.md and gateway-sessions.md say so. It is rebased on #4382 (b889ffe81), which lets the user keep a server out of the hub (Server.Hub = direct). inHub now asks both: a server kept direct is out, and magpie-image is in unless the agent is in WSL, so the user can keep magpie-image direct too; the editor's switch shows for it like any server, and the hub's line counts it with the others (mcp-hub-direct.test.cjs follows). Run at e2583df31 (this stack on86fef947e), on mote: gofmt -l clean; go vet for darwin, linux (-tags nogui) and windows; go build ./...; go test -tags nogui ./... -timeout 45m, 81 packages ok, 0 FAIL; library, gateway, imagemcp, sessions, cli and gui again alone, ok; site's node --test, 49 of 49. GUI on xiaomi-gpu (Windows; mote's browsers crashed under other sessions' suites): library-*, image*, mcp-hub-direct, i18n-keys, list-sort and plugin-tools, both engines and every language, 1055 of 1056: i18n-keys found "{name} is given to each agent directly" dropped from the library's strings in the rebase. Put back in the first commit; at the pushed head i18n-keys, mcp-hub-direct and library-mcp-hub are 48 of 48. That is the only difference from e2583df31. Broken by hand at e2583df31: imagemcp ignoring magpie/roots fails TestHubCallSavesInTheCallersProject; the router asking anything but roots/list fails TestHubAsksTheAgentItsRoots and TestHubRootsUnasked; inHub leaving magpie-image out fails TestHubGivesMagpieImage. Real use, sandbox HOME and gateway, at 62421e570 (before the rebase): Claude Code saved into its project via roots/list; Codex in a git repo via its workspaces _meta; Codex outside a repo with session consent via the thread's cwd. At 62421e570 the whole GUI suite ran on WSL magpie-desktop at load 116 to 135 from other runs: 504 of 15757 red in 118 files, WebKit timeouts, none in a file this change touches; filed as #4471 with the list. Rebased once more onto2570efb5f, which changed library-mcp-hub, list-sort, mcp-hub-direct and gateway-routing.md. Run at the pushed head: go build; gateway, library, cli and imagemcp tests ok; the GUI budget tests ok; on xiaomi-gpu i18n-keys, mcp-hub-direct, library-mcp-hub and list-sort, 51 of 54. The three reds were WebKit 420px library-mcp-hub cases with no Connect sheet after a reload. origin/maind77da5bffgoes red the same way (de 420px, 9 of 11). In a second run of library-mcp-hub on WebKit at this head, 11 of 11 passed. Filed as #4483. Not tried: Codex outside a git repo without consent (it saves to ~/Pictures/Magpie, #4435); agents on Windows and in WSL with real use.
360 lines
12 KiB
Go
360 lines
12 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"maps"
|
|
"net/http"
|
|
"net/url"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/access"
|
|
"github.com/yetone/magpie/internal/sessions"
|
|
)
|
|
|
|
// The MCP hub (#2679): with the Library's switch on, magpie is the one MCP
|
|
// server an agent is given, at HubMCPPath<agent>, and it hands each call
|
|
// on to the Library server behind it, as Composio does. Its tools are
|
|
// those of the Library servers ticked for that agent, each named
|
|
// <server>__<tool>; the servers themselves (a command started once for
|
|
// every agent, a URL reached with magpie's sign-in) are the library's to
|
|
// run (library/mcp_hub.go), which sets MCPHub. It is guarded as
|
|
// magpie's other MCP servers are (serveMCP), and each call is held to the
|
|
// calling gateway key's limit (reserveFor). Tools only, for now: no
|
|
// resources or prompts.
|
|
|
|
// HubMCPPath is where the hub is served, the agent's id after it.
|
|
const HubMCPPath = "/mcp/magpie/hub/"
|
|
|
|
// HubMCPAll is the hub for any other app (Cursor, VS Code, a script): one
|
|
// address with every server in the Library, ticked for an agent or not.
|
|
// It is the agent "" to Hub.
|
|
const HubMCPAll = "/mcp/magpie/hub"
|
|
|
|
// HubTool is one tool a Library server lists, as the hub gives it.
|
|
type HubTool struct {
|
|
Server string // the Library server's name
|
|
Tool string // the tool's name on that server
|
|
// Spec is the tool as the server listed it: its description,
|
|
// inputSchema and the rest go to the agent as they are, its name
|
|
// replaced
|
|
Spec map[string]json.RawMessage
|
|
// Roots: the server writes into the agent's project (magpie-image),
|
|
// so a call is made with the agent's folders (HubCaller)
|
|
Roots bool
|
|
}
|
|
|
|
// HubCaller is who a call of a Roots tool is for: the folders the agent
|
|
// said are its, as file URIs (none for an agent on another machine, whose
|
|
// folders aren't here), and its User-Agent's product, the name the
|
|
// server's own requests go under.
|
|
type HubCaller struct {
|
|
Roots []string
|
|
Client string
|
|
}
|
|
|
|
// The _meta keys a call of magpie's image server carries its caller in:
|
|
// the roots, a list of file URIs (an empty one when the agent has none
|
|
// here), and the client; and the one its result says the model it drew
|
|
// with in (provider/model), for the hub's row of the call.
|
|
const (
|
|
HubRootsMeta = "magpie/roots"
|
|
HubClientMeta = "magpie/client"
|
|
HubModelMeta = "magpie/model"
|
|
)
|
|
|
|
type hubCallerKey struct{}
|
|
|
|
// WithHubCaller is ctx carrying caller c.
|
|
func WithHubCaller(ctx context.Context, c HubCaller) context.Context {
|
|
return context.WithValue(ctx, hubCallerKey{}, c)
|
|
}
|
|
|
|
// HubCallerOf is the caller a hub call's ctx carries.
|
|
func HubCallerOf(ctx context.Context) HubCaller {
|
|
c, _ := ctx.Value(hubCallerKey{}).(HubCaller)
|
|
return c
|
|
}
|
|
|
|
// Hub is the servers behind the hub: the library's.
|
|
type Hub interface {
|
|
// On is whether the Library's switch is on: off, the hub lists no
|
|
// tool and runs none
|
|
On() bool
|
|
// Tools are the tools of the servers ticked for agent (every server
|
|
// in the Library for agent "", HubMCPAll's), but those turned off; a
|
|
// server that couldn't be reached by ctx's end is left out
|
|
Tools(ctx context.Context, agent string) []HubTool
|
|
// Call runs one tool of server for agent, and is its result as the
|
|
// server gave it; an error is why it couldn't be run
|
|
Call(ctx context.Context, agent, server, tool string, args json.RawMessage) (json.RawMessage, error)
|
|
// Stop ends every server the hub started
|
|
Stop()
|
|
// Prune ends each server the hub started that the Library no longer
|
|
// gives: the switch turned off, the server removed or edited, here or
|
|
// by another magpie (the window, the CLI)
|
|
Prune()
|
|
}
|
|
|
|
// MCPHub is set by the library; nil, the hub has no server.
|
|
var MCPHub Hub
|
|
|
|
// The hub's budgets: tools/list waits for the servers this long (a server
|
|
// still starting is left out, and listed once it has), and a call this
|
|
// long, under the 60s an MCP client waits for an answer, for the agent to
|
|
// be told which server didn't answer rather than its own timeout.
|
|
var (
|
|
hubListWait = 40 * time.Second
|
|
hubCallWait = 50 * time.Second
|
|
)
|
|
|
|
const hubBody = 4 << 20
|
|
|
|
const errHubOff = "magpie's MCP hub is off, so it runs no server's tools: turn it on in magpie's Library → MCP"
|
|
|
|
func (s *Server) hubMCP(w http.ResponseWriter, r *http.Request) {
|
|
agent := r.PathValue("agent")
|
|
serveMCP(w, r, "magpie's MCP hub", "magpie", hubBody, func(r *http.Request, m mcpMessage) (any, map[string]any) {
|
|
return s.hubMCPCall(r, agent, m)
|
|
})
|
|
}
|
|
|
|
// hubTool is one tool as the hub names it.
|
|
type hubTool struct {
|
|
HubTool
|
|
name string
|
|
}
|
|
|
|
// hubSep is between a server's name and its tool's in the hub's names.
|
|
const hubSep = "__"
|
|
|
|
// hubNamed names ts <server>__<tool>, in the characters MCP clients take
|
|
// and 64 of them at most, a name two would share told apart by a number.
|
|
func hubNamed(ts []HubTool) []hubTool {
|
|
out := make([]hubTool, 0, len(ts))
|
|
seen := map[string]bool{}
|
|
for _, t := range ts {
|
|
base := unsafeToolChars.ReplaceAllString(t.Server, "-") + hubSep + unsafeToolChars.ReplaceAllString(t.Tool, "-")
|
|
name := cutName(base, 64)
|
|
for i := 2; seen[name]; i++ {
|
|
suf := "_" + strconv.Itoa(i)
|
|
name = cutName(base, 64-len(suf)) + suf
|
|
}
|
|
seen[name] = true
|
|
out = append(out, hubTool{HubTool: t, name: name})
|
|
}
|
|
return out
|
|
}
|
|
|
|
func hubTools(ctx context.Context, agent string) []hubTool {
|
|
if MCPHub == nil || !MCPHub.On() {
|
|
return nil
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, hubListWait)
|
|
defer cancel()
|
|
return hubNamed(MCPHub.Tools(ctx, agent))
|
|
}
|
|
|
|
func (s *Server) hubMCPCall(r *http.Request, agent string, m mcpMessage) (any, map[string]any) {
|
|
switch m.Method {
|
|
case "initialize":
|
|
say := "The tools of the MCP servers in magpie's Library that are switched on for this agent, each named <server>__<tool>. Add servers, or switch them on for an agent, in magpie's Library → MCP."
|
|
if agent == "" {
|
|
say = "The tools of every MCP server in magpie's Library, each named <server>__<tool>. Add servers in magpie's Library → MCP."
|
|
}
|
|
if MCPHub == nil || !MCPHub.On() {
|
|
say = errHubOff
|
|
}
|
|
return map[string]any{
|
|
"protocolVersion": mcpVersion(m),
|
|
"capabilities": map[string]any{"tools": map[string]any{}},
|
|
"serverInfo": map[string]any{"name": "magpie", "title": "Magpie MCP hub", "version": Version},
|
|
"instructions": say,
|
|
}, nil
|
|
case "ping":
|
|
return map[string]any{}, nil
|
|
case "tools/list":
|
|
ts := hubTools(r.Context(), agent)
|
|
list := make([]any, 0, len(ts))
|
|
for _, t := range ts {
|
|
spec := make(map[string]json.RawMessage, len(t.Spec)+1)
|
|
for k, v := range t.Spec {
|
|
spec[k] = v
|
|
}
|
|
name, _ := json.Marshal(t.name)
|
|
spec["name"] = name
|
|
if s, ok := spec["inputSchema"]; !ok || !json.Valid(s) {
|
|
spec["inputSchema"] = json.RawMessage(`{"type":"object","properties":{}}`)
|
|
}
|
|
list = append(list, spec)
|
|
}
|
|
return map[string]any{"tools": list}, nil
|
|
case "tools/call":
|
|
var p struct {
|
|
Name string `json:"name"`
|
|
Arguments json.RawMessage `json:"arguments"`
|
|
Meta hubCallMeta `json:"_meta"`
|
|
}
|
|
if err := json.Unmarshal(m.Params, &p); err != nil {
|
|
return nil, map[string]any{"code": -32602, "message": "invalid params: " + err.Error()}
|
|
}
|
|
if MCPHub == nil || !MCPHub.On() {
|
|
return toolResult(errHubOff, true), nil
|
|
}
|
|
for _, t := range hubTools(r.Context(), agent) {
|
|
if t.name == p.Name {
|
|
if t.Roots {
|
|
r = r.WithContext(WithHubCaller(r.Context(), HubCaller{Roots: hubRoots(r, p.Meta), Client: hubClient(r)}))
|
|
}
|
|
return s.hubMCPRun(r, agent, t, p.Arguments), nil
|
|
}
|
|
}
|
|
if agent == "" {
|
|
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": no MCP server in magpie's Library gives it"}
|
|
}
|
|
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": no MCP server switched on for " + agent + " in magpie's Library gives it"}
|
|
}
|
|
return nil, map[string]any{"code": -32601, "message": "method not found: " + m.Method}
|
|
}
|
|
|
|
// hubMCPRun runs one tool on its server, held to the calling gateway key's
|
|
// limit. A server that is down or doesn't answer in time is an error
|
|
// result naming it, never a wait past the client's.
|
|
func (s *Server) hubMCPRun(r *http.Request, agent string, t hubTool, args json.RawMessage) any {
|
|
// the request log names the Library's server, and the agent the hub is mounted for
|
|
use := mcpUseOf(r.Context())
|
|
use.on(t.Server)
|
|
use.as(agent)
|
|
release, err := reserveFor(access.Caller(r.Context()), int64(len(args)), "", limitClock())
|
|
if err != nil {
|
|
return toolResult(err.Error(), true)
|
|
}
|
|
defer release()
|
|
if len(args) == 0 || string(args) == "null" {
|
|
args = json.RawMessage(`{}`)
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), hubCallWait)
|
|
defer cancel()
|
|
res, err := MCPHub.Call(ctx, agent, t.Server, t.Tool, args)
|
|
if err != nil {
|
|
why := err.Error()
|
|
if ctx.Err() != nil && r.Context().Err() == nil {
|
|
why = "it didn't answer in " + hubCallWait.String()
|
|
}
|
|
return toolResult("The MCP server "+t.Server+" couldn't run "+t.Tool+": "+why, true)
|
|
}
|
|
if t.Roots {
|
|
// magpie's image server draws through the gateway on its own
|
|
// connection, so its result names the model for this call's row
|
|
var m struct {
|
|
Meta struct {
|
|
Model string `json:"magpie/model"`
|
|
} `json:"_meta"`
|
|
}
|
|
json.Unmarshal(res, &m)
|
|
use.usedRef(m.Meta.Model)
|
|
}
|
|
return res
|
|
}
|
|
|
|
// hubCallMeta is what of a tool call's _meta the hub reads: the thread
|
|
// Codex names its calls by, and the workspaces its turn metadata names
|
|
// (the git repositories it works in, keyed by their folder).
|
|
type hubCallMeta struct {
|
|
ThreadID string `json:"threadId"`
|
|
Turn struct {
|
|
Workspaces map[string]json.RawMessage `json:"workspaces"`
|
|
} `json:"x-codex-turn-metadata"`
|
|
}
|
|
|
|
// hubRootsWait is how long the agent is given to say its roots.
|
|
var hubRootsWait = 3 * time.Second
|
|
|
|
// hubRoots are the folders of the agent calling, as file URIs: what it
|
|
// answers roots/list with, asked on the call's own stream (Claude Code
|
|
// answers), else the workspaces of Codex's turn the call names, else the
|
|
// folder of the Codex thread it names (Codex declares no roots, and
|
|
// answers none). An agent on another machine has none here.
|
|
func hubRoots(r *http.Request, meta hubCallMeta) []string {
|
|
if !local(r) {
|
|
return nil
|
|
}
|
|
var roots []string
|
|
if m, err := askClient(r.Context(), "roots/list", nil, hubRootsWait); err == nil && len(m.Result) > 0 {
|
|
var res struct {
|
|
Roots []struct {
|
|
URI string `json:"uri"`
|
|
} `json:"roots"`
|
|
}
|
|
json.Unmarshal(m.Result, &res)
|
|
for _, root := range res.Roots {
|
|
if strings.HasPrefix(root.URI, "file:") {
|
|
roots = append(roots, root.URI)
|
|
}
|
|
}
|
|
}
|
|
if len(roots) == 0 {
|
|
// what the call says itself first; a thread's rollout is read
|
|
// only when it says no workspace (a folder that isn't a repository)
|
|
for _, dir := range slices.Sorted(maps.Keys(meta.Turn.Workspaces)) {
|
|
if filepath.IsAbs(dir) {
|
|
roots = append(roots, fileURI(dir))
|
|
}
|
|
}
|
|
}
|
|
if len(roots) == 0 && meta.ThreadID != "" {
|
|
if dir := sessions.CodexThreadCwd(meta.ThreadID); dir != "" {
|
|
roots = append(roots, fileURI(dir))
|
|
}
|
|
}
|
|
return roots
|
|
}
|
|
|
|
// fileURI is the file:// URI of folder dir: file:///C:/p for C:\p.
|
|
func fileURI(dir string) string {
|
|
p := filepath.ToSlash(dir)
|
|
if !strings.HasPrefix(p, "/") {
|
|
p = "/" + p
|
|
}
|
|
return (&url.URL{Scheme: "file", Path: p}).String()
|
|
}
|
|
|
|
// hubClient is the product a request's User-Agent starts with
|
|
// (claude-code/2.1.314, codex-mcp-client/0.165.0).
|
|
func hubClient(r *http.Request) string {
|
|
c, _, _ := strings.Cut(strings.TrimSpace(r.Header.Get("User-Agent")), " ")
|
|
return c
|
|
}
|
|
|
|
// hubPruneEvery is how often the gateway ends the servers the hub no
|
|
// longer gives. An agent given the servers' own entries again never asks
|
|
// the hub, so it is looked for, not waited for.
|
|
var hubPruneEvery = 5 * time.Second
|
|
|
|
// keepHubPruned prunes the hub's servers while ctx lasts.
|
|
func keepHubPruned(ctx context.Context) {
|
|
tick := time.NewTicker(hubPruneEvery)
|
|
defer tick.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-tick.C:
|
|
if MCPHub != nil {
|
|
MCPHub.Prune()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// StopHub ends the servers the hub started: magpie is stopping.
|
|
func StopHub() {
|
|
if MCPHub != nil {
|
|
MCPHub.Stop()
|
|
}
|
|
}
|