Files
magpie/internal/gateway/busy.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

81 lines
2.3 KiB
Go

package gateway
import (
"net/http"
"strings"
"sync/atomic"
"time"
)
// Busy is what a restart of the magpie serving the gateway would cut
// short (#577): the agents' requests in flight — a reply streaming, an
// image being made — and the turns of Claude Code run through the
// subscription bridge waiting on their caller's tool results, whose
// Claude Code lives only in this process. A request in flight is one
// that does work (not a GET: the model lists, the info another magpie
// asks for every 15 s); the bridge's own helper calls are not counted
// apart, a turn waiting on them being in Tools. Last is when the last
// counted request ended, so a caller can tell a tool chain's gap — the
// agent running a tool between two requests — from the end of its turn.
type Busy struct {
Requests int `json:"requests"`
Tools int `json:"tools"`
Last time.Time `json:"-"`
}
// Any is whether there is anything in flight.
func (b Busy) Any() bool { return b.Requests > 0 || b.Tools > 0 }
// Busy says what is in flight at the gateway now.
func (s *Server) Busy() Busy {
b := Busy{Requests: int(s.inFlight.Load()), Tools: s.subscription.parked()}
if n := s.lastDone.Load(); n != 0 {
b.Last = time.Unix(0, n)
}
return b
}
// counted is h with its requests counted for Busy.
func (s *Server) counted(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions || strings.HasPrefix(r.URL.Path, "/_magpie/") || strings.HasPrefix(r.URL.Path, "/mcp/") {
h.ServeHTTP(w, r)
return
}
s.inFlight.Add(1)
defer func() {
s.lastDone.Store(time.Now().UnixNano())
s.inFlight.Add(-1)
}()
h.ServeHTTP(w, r)
})
}
// busyCounters are the Server's counts for Busy.
type busyCounters struct {
inFlight atomic.Int64
lastDone atomic.Int64 // unix ns
}
// parked is how many runs wait on their caller's tool results.
func (b *subscriptionBridge) parked() int {
if b == nil {
return 0
}
b.mu.Lock()
runs := make([]*subscriptionRun, 0, len(b.runs))
for _, run := range b.runs {
runs = append(runs, run)
}
b.mu.Unlock()
n := 0
for _, run := range runs {
run.mu.Lock()
if !run.closed && !run.parkedAt.IsZero() {
n++
}
run.mu.Unlock()
}
return n
}