Files
magpie/internal/gateway/mcp.go
T
yetone bf0f3e3f73 library: a remote MCP server signed in once in magpie is used by every agent without signing in again (#615) — a streamable-HTTP server behind OAuth (Neon, Notion, Supabase) had each agent run its own sign-in. The server's editor now has Sign in: magpie finds the authorization server from the server's 401 (RFC 9728 protected-resource metadata, RFC 8414/OIDC metadata, else the 2025-03 /authorize, /token, /register at its origin), registers itself (RFC 7591, a 127.0.0.1 redirect), opens the browser with PKCE S256 and the resource, and keeps the tokens in mcp-signins.json beside its other account secrets (0600, never the keychain). While signed in, the agents are given the gateway's /mcp/<name> for that server, without the Authorization the library has for it; the gateway passes POST (JSON or event stream), the GET stream and DELETE on with the Mcp-Session-Id and magpie's token, renews it 2 minutes before it runs out and once on a 401, one renewal per server at a time, and a sign-in the server won't renew is answered 502 "sign in to it again" (never a 401 the agent would act on). Signing out, a new URL or an SSE server gives the agents the server's own address as before; a rename keeps the sign-in and removing the server drops it. /mcp/ is local-only or LAN-shared with the key, and refuses a request with an Origin or a Host not naming this computer, so a web page can't borrow the sign-in through the browser (form posts, DNS rebinding), and isn't counted as busy or key-limited. WSL agents are given their distro's gateway address. The row says Signed in or Sign-in ran out; zh strings added. Tests: TestSignIn, TestSignInWithoutMetadata, TestSignInPage, TestNothingToSignIn, TestTokenRenewsBeforeItRunsOut (8 calls, 1 renewal), TestRenewRefused, TestRenewRefusedForGood, TestMCPProxy, TestMCPProxyStaysHere, TestMCPProxyNotForWebPages (fails without the Origin/Host check), TestSignedInServerGoesThroughMagpie against a local fake OAuth+MCP server; mcp-signin.test.cjs (webkit, en and zh). Not tried against a real Neon/Notion/Supabase sign-in. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass.
2026-10-03 09:37:39 +08:00

183 lines
5.5 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,
}
// 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
}
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
}
var body []byte
if r.Body != nil {
b, err := io.ReadAll(io.LimitReader(r.Body, 32<<20))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
body = b
}
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 {
if mcpHop[http.CanonicalHeaderKey(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 {
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()
}