Files
magpie/internal/gateway/mcp.go
T
yetone d55881730d gateway: a key can be held to some MCP servers and tools
wakaka on Discord (#help, 11-06) asked for gateway keys limited to some
MCP servers and tools, as keys already are to models (#882).

A key's MCP list (caller-keys.json "mcp") holds entries "server" (every
tool of it) or "server/tool"; "-" alone is no MCP server; an empty list
is every server, as before. A key issued under another is held to its
issuer's list too.

Every MCP route checks it:
- magpie's own servers (web search, vision, image, Magpie Browser, plugin
  tools) through serveMCP: initialize/tools/list/tools/call are refused
  or filtered per server and tool, and /v1/magpie/key-limits names "mcp";
- the Library hub ("magpie"): only the backing servers and tools the key
  may use are listed, and a call by name or by fallback is refused;
- /mcp/<name> and /mcp/run/<name>: the server is refused, tools/list is
  filtered in JSON and SSE replies, tools/call refused; a reply the
  filter can't read (an encoded body) is a 502, never passed through.

GUI: "MCP servers" in the key row's menu opens the app's own picker (no
native select) with All, No MCP server, each server and its tools (GET
/api/caller-keys/mcp lists magpie's own servers and the Library's). A
key held to some shows a badge saying which, that opens the same list;
a free key shows nothing more in its row, on hover either. A hover badge
was tried first: it pushed the row past 560px (gateway-caller-keys) and
squeezed the masked key under a drag at 420px (gateway-key-arrange).
CLI: magpie gateway-key mcp <id> github fs/read_file | none | all.
zh, zh-TW, ja, de strings; docs/reference.md and the gateway-routing and
library subsystem pages.

Not covered: a model's own built-in web search (a vendor tool, not MCP).

GET /api/caller-keys/mcp is named in the CLI parity test's notYet (its
list is what `magpie gateway-key mcp` takes; TestEveryRouteHasACommandOrIsNamed
caught it at the rebased head).

Run on mote (mote-run), at the pushed head:
- go test ./internal/access ./internal/cli ./internal/gui
  ./internal/library ./internal/gateway at a9c40186d (this change on
  2ce44dc28): ok except internal/gui's TestMainWindowCorners/macOS_26_SDK
  (#3949, the same message on macOS 27). After the rebase onto a9667daad
  (no file in common): TestCoreScriptBudget, TestCallerKey*,
  TestEveryRoute*, TestGatewayKey*, TestKeyMCP*, internal/access and
  go vet ./internal/... at d36f89224's tree: ok.
- gateway-caller-keys chromium en reads wider than 560px 4 of 6 runs
  alone on this branch and 4 of 6 on origin/main a9667daad: #3797,
  recorded there.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: clean; darwin, linux (nogui) and windows builds ok; gofmt -l
  clean.
- GUI: gateway-key-mcp.test.cjs in chromium and webkit, widths 1100 and
  420, en/zh/zh-TW/ja/de: 20/20. Every gateway-key*, gateway-keys* and
  i18n* file in both engines: ok except gateway-key-models en (red on
  origin/main ecc26a339 too, #4081/#5233) and i18n-keys "a plugin's words
  are its own" (red on main, #5332).
- The whole GUI suite (both engines, every language) with the hover
  badge: 91 reds in 25 files. Rerun alone on this branch and on
  origin/main 54dc257f1: only gateway-caller-keys (560px sideways),
  gateway-key-readonly, models-fold and models-select-all-api were red
  on the branch alone; the badge moved into the row menu for the first
  two. After it, every gateway-key*, gateway-caller-keys, gateway-card,
  gateway-connect-keys, api-key-theme and i18n* file passes in both
  engines, except i18n-keys "a plugin's words are its own" (red on main,
  #5332, none of the three strings are this change's) and 1 of 20
  models-select-all-api "the click scrolled" (#4389; models-fold is
  #4071). The rest are red on origin/main too and each has an issue:
  account-weight #4644, codex-auto-reset #2360, header-centre #3479,
  images-codex-one #4618, key-replace #4126, menu-input-scroll #3402,
  mobile-web #3952, model-chip-steady #4388, model-copy-id #4621,
  models-works-only #4391, nav-timeout #4787, omarchy #4624,
  page-width-steady #5013, phone-connect-menu #4706/#4707,
  plugin-move-unserved #4392.

Broken by hand, each went red: the serveMCP server gate, call check and
list filter, the own-server list filter and key-limits "mcp"
(TestKeyMCPOwnServer); hubTools, hubServersOf, the hubToolNamed
fallback and hubMCPRun (TestKeyMCPHub); /mcp/run (TestKeyMCPRun); the
/mcp/<name> guard and filter (TestKeyMCPProxy); the GUI's "No MCP
server" being exclusive (gateway-key-mcp).
gateway-key-readonly chromium 420 ja was red with the hover badge (the
sibling run, the whole suite and its rerun; green on origin/main) and
passes with the badge in the row menu.

Not tried: a real Library server through a live gateway, the hub with a
real agent, and running on Windows or Linux (vet and build only).

Reported-by: wakaka
2026-11-07 03:21:57 +08:00

217 lines
6.9 KiB
Go

package gateway
import (
"bytes"
"errors"
"io"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/yetone/magpie/internal/mcpauth"
"github.com/yetone/magpie/internal/netproxy"
)
// mcpClient relays the agents' requests to a remote MCP server magpie is
// signed in to. It has no timeout: a GET's event stream stays open for as
// long as the agent keeps it.
var mcpClient = &http.Client{Transport: mcpTransport()}
func mcpTransport() http.RoundTripper {
t := http.DefaultTransport.(*http.Transport).Clone()
t.Proxy = netproxy.Func
t.ResponseHeaderTimeout = 2 * time.Minute
return netproxy.Dispatch(t)
}
// mcpHop are the headers a relay doesn't pass on.
var mcpHop = map[string]bool{
"Authorization": true, "Host": true, "Connection": true, "Keep-Alive": true,
"Proxy-Authorization": true, "Proxy-Connection": true, "Te": true, "Trailer": true,
"Transfer-Encoding": true, "Upgrade": true, "Content-Length": true, "Accept-Encoding": true,
}
// RunMCP serves /mcp/run/<server>: a server magpie runs by its command,
// for an agent on this computer given it that way (library's ServeRun);
// nil until the library sets it.
var RunMCP func(w http.ResponseWriter, r *http.Request, name string)
// runMCP is RunMCP, for this computer's agents alone: it starts a command
// the user gave their agents, and no other machine, and no web page (one
// posting a form, or of a name pointed at 127.0.0.1), may have it started.
func runMCP(w http.ResponseWriter, r *http.Request) {
if !local(r) || r.Header.Get("Origin") != "" || !loopbackHost(r.Host) {
http.Error(w, "magpie runs the Library's MCP servers for the agents on this computer alone", http.StatusForbidden)
return
}
if RunMCP == nil {
http.Error(w, "magpie runs no MCP server here", http.StatusNotFound)
return
}
// a gateway key held to some MCP servers or tools (access.Key.MCP)
w, r, done, ok := mcpKeyGuard(w, r, r.PathValue("name"))
if !ok {
return
}
defer done()
RunMCP(w, r, r.PathValue("name"))
}
// mcpProxy is /mcp/<server>: a remote MCP server magpie signed in to once,
// for every agent the Library gives it to (#615). The agent speaks to it as
// to the server itself (streamable HTTP: a POST answered with JSON or an
// event stream, a GET's event stream, a DELETE that ends the session, with
// Mcp-Session-Id), and magpie sends it on with its own token, renewing it
// when it runs out or the server says it has.
func (s *Server) mcpProxy(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
if !local(r) && !sharedWith(r) {
http.Error(w, "magpie lends its MCP sign-ins to another machine only when magpie is shared on the local network and the request carries its API key", http.StatusForbidden)
return
}
// a web page can make the browser send a request here too (a form, or
// a hostname of its own pointed at 127.0.0.1), and magpie would carry
// it to the server with the user's sign-in; agents send no Origin and
// name this computer, as the MCP spec has servers check
if r.Header.Get("Origin") != "" || !sharedWith(r) && !loopbackHost(r.Host) {
http.Error(w, "magpie lends its MCP sign-ins to agents, not to web pages", http.StatusForbidden)
return
}
// a gateway key held to some MCP servers or tools (access.Key.MCP)
w, r, done, held := mcpKeyGuard(w, r, name)
if !held {
return
}
defer done()
rec, ok := mcpauth.Get(name)
if !ok {
http.Error(w, "magpie isn't signed in to an MCP server called "+name+": sign in to it in magpie's Library", http.StatusNotFound)
return
}
// a body cut at the limit would go to the server as a shorter message
body, ok := readMCPBody(w, r, 32<<20)
if !ok {
return
}
target, err := url.Parse(rec.URL)
if err != nil {
http.Error(w, "the server's URL isn't one: "+err.Error(), http.StatusBadGateway)
return
}
if r.URL.RawQuery != "" {
q := target.Query()
for k, v := range r.URL.Query() {
q[k] = v
}
target.RawQuery = q.Encode()
}
token, err := mcpauth.Token(r.Context(), name)
if err != nil {
mcpRefused(w, name, err)
return
}
send := func(token string) (*http.Response, error) {
req, err := http.NewRequestWithContext(r.Context(), r.Method, target.String(), bytes.NewReader(body))
if err != nil {
return nil, err
}
for k, v := range r.Header {
// nor what a proxy in front of magpie says of the caller
if mcpHop[http.CanonicalHeaderKey(k)] || proxyIdentity(k) {
continue
}
// the gateway's own key, which the caller check put there
if strings.EqualFold(k, "x-api-key") && len(v) == 1 && v[0] == Token {
continue
}
req.Header[k] = v
}
req.Header.Set("Authorization", "Bearer "+token)
if body == nil {
req.ContentLength = 0
}
return mcpClient.Do(req)
}
resp, err := send(token)
if err == nil && resp.StatusCode == http.StatusUnauthorized {
io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<16))
resp.Body.Close()
fresh, rerr := mcpauth.Renew(r.Context(), name, token)
if rerr != nil {
mcpRefused(w, name, rerr)
return
}
resp, err = send(fresh)
if err == nil && resp.StatusCode == http.StatusUnauthorized {
// a token just renewed and refused all the same: the sign-in
// has run out, as the Library then says (新v学员 on Discord)
mcpauth.Rejected(name, fresh)
}
}
if err != nil {
if r.Context().Err() == nil {
log.Printf("mcp %s: %v", name, err)
}
http.Error(w, "couldn't reach the MCP server "+name+": "+err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
// the agent would start a sign-in of its own, at magpie's address
io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<16))
mcpRefused(w, name, mcpauth.ErrExpired)
return
}
for k, v := range resp.Header {
if mcpHop[http.CanonicalHeaderKey(k)] || strings.EqualFold(k, "WWW-Authenticate") {
continue
}
w.Header()[k] = v
}
w.WriteHeader(resp.StatusCode)
flusher, _ := w.(http.Flusher)
buf := make([]byte, 32<<10)
for {
n, err := resp.Body.Read(buf)
if n > 0 {
if _, werr := w.Write(buf[:n]); werr != nil {
return
}
if flusher != nil {
flusher.Flush()
}
}
if err != nil {
return
}
}
}
// mcpRefused answers an agent whose request magpie has no token for. It is
// not a 401, which would set the agent signing in itself.
func mcpRefused(w http.ResponseWriter, name string, err error) {
status := http.StatusBadGateway
msg := err.Error()
if errors.Is(err, mcpauth.ErrExpired) || errors.Is(err, mcpauth.ErrNotSignedIn) {
msg = "magpie's sign-in to the MCP server " + name + " has run out: sign in to it again in magpie's Library"
}
http.Error(w, msg, status)
}
// loopbackHost: a Host header naming this computer, localhost or a loopback
// address, with or without a port.
func loopbackHost(host string) bool {
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
host = strings.Trim(host, "[]")
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}