The router keeps one backend per Library server for every agent, so all agents behind it shared one `magpie mcp browser`, one browser session and so one tab (packinggoodsllc_07668 on Discord: two agents through a remote router fought over one tab). - serveMCP gives a client that initializes an Mcp-Session-Id (nothing is kept or checked by it). - hubSession names each tools/call's caller: _meta magpie/session from a router in front, else hub-<agent>-<Mcp-Session-Id>. - The router passes it in _meta magpie/session to `magpie mcp browser` and to another magpie's router only (keepsSession); the bridge sends it as that call's X-Magpie-Browser-Session (callerSession). A call naming none goes as the bridge's own session, as before. Run (mote-run): go test ./internal/browsermcp; ./internal/gateway -run 'MCP|Hub'; ./internal/library -run 'TestHubTellsMagpieBrowser|TestKeepsSession|TestHubGivesMagpieImage'. ok. Broken by hand, each red: no meta from the library (library test), no Mcp-Session-Id from serveMCP and ignoring _meta in hubSession (gateway test). Not tried: a real remote router chain between two machines.
432 lines
15 KiB
Go
432 lines
15 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"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"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// 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.
|
|
//
|
|
// Session is which of the hub's callers the call is from (hubSession), for
|
|
// a server that keeps something per caller: Magpie Browser's tab, which
|
|
// two agents behind one router would otherwise share, the router running
|
|
// one `magpie mcp browser` for all of them.
|
|
type HubCaller struct {
|
|
Roots []string
|
|
Client string
|
|
Session 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"
|
|
// HubSessionMeta is the _meta key a call carries its caller's session
|
|
// in (HubCaller.Session), to Magpie Browser and to another magpie's
|
|
// router, which passes it on as its own caller's
|
|
HubSessionMeta = "magpie/session"
|
|
)
|
|
|
|
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."
|
|
}
|
|
title := "Magpie MCP hub"
|
|
if w := hubWhere(r); w != "" {
|
|
say += " This router: " + w + ". Each of its tools' descriptions starts with [" + w + "]; when another MCP server gives the same tools, choose between them by this."
|
|
title += " · " + w
|
|
}
|
|
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": title, "version": Version},
|
|
"instructions": say,
|
|
}, nil
|
|
case "ping":
|
|
return map[string]any{}, nil
|
|
case "tools/list":
|
|
ts := hubTools(r.Context(), agent)
|
|
where := hubWhere(r)
|
|
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":{}}`)
|
|
}
|
|
if where != "" {
|
|
var d string
|
|
json.Unmarshal(spec["description"], &d)
|
|
d, _ = strings.CutPrefix(d, "["+where+"]")
|
|
d = strings.TrimSpace("[" + where + "] " + strings.TrimSpace(d))
|
|
spec["description"], _ = json.Marshal(d)
|
|
}
|
|
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 {
|
|
c := HubCaller{Session: hubSession(r, agent, p.Meta)}
|
|
if t.Roots {
|
|
c.Roots, c.Client = hubRoots(r, p.Meta), hubClient(r)
|
|
}
|
|
r = r.WithContext(WithHubCaller(r.Context(), c))
|
|
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"`
|
|
// Session is the caller's session as another magpie's router passed
|
|
// it on (HubSessionMeta)
|
|
Session string `json:"magpie/session"`
|
|
Turn struct {
|
|
Workspaces map[string]json.RawMessage `json:"workspaces"`
|
|
} `json:"x-codex-turn-metadata"`
|
|
}
|
|
|
|
// hubSession is which caller of the hub r is: the session another
|
|
// magpie's router names, which is its own caller's (that router reaches
|
|
// this one on one connection for all of them), else the session this
|
|
// client was given at initialize (serveMCP), else none, and the server
|
|
// then keeps one thing for every caller, as before clients were told
|
|
// apart. A caller can name any session, but each is only a tab of the
|
|
// user's browser, which a caller can pick by its id anyway.
|
|
func hubSession(r *http.Request, agent string, meta hubCallMeta) string {
|
|
if v := boundedSession(meta.Session); v != "" {
|
|
return v
|
|
}
|
|
if v := boundedSession(r.Header.Get("Mcp-Session-Id")); v != "" {
|
|
return "hub-" + agent + "-" + v
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// newMCPSession is a session id for a client of one of magpie's MCP
|
|
// servers.
|
|
func newMCPSession() string { return "magpie-" + rand.Text() }
|
|
|
|
// hubWhere is what the router says of itself to the agent of r, for an
|
|
// agent given the same tools by two routers (one in China, one in Los
|
|
// Angeles) to tell them apart: the user's own words (settings'
|
|
// RouterNote, set under the router's switch), else this computer's name
|
|
// to an agent on another computer. An agent on this computer with no
|
|
// words set is told nothing: there it is the router at hand, and the
|
|
// computer's name stays off its prompts.
|
|
func hubWhere(r *http.Request) string {
|
|
if n := settings.CleanRouterNote(settings.Shared().RouterNote); n != "" {
|
|
return n
|
|
}
|
|
if !local(r) {
|
|
return hostName()
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// HostName is this computer's name, what the router says of itself to an
|
|
// agent on another computer when the user set no words of their own.
|
|
func HostName() string { return hostName() }
|
|
|
|
// 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()
|
|
}
|
|
}
|