diff --git a/pkgs/mcpx/TODO.md b/pkgs/mcpx/TODO.md index 63c3c59bbb..dc91171e03 100644 --- a/pkgs/mcpx/TODO.md +++ b/pkgs/mcpx/TODO.md @@ -3,5 +3,4 @@ - Replace the takeover handoff with a supervisor that owns each stdio child's pipes for the child's whole life. The current handoff is a stopgap: `mcpx upgrade` (run from the new binary) and `mcpx daemon --takeover` have the old daemon start the successor as its own child, so it stays in the service's cgroup, and pass its children's pipes to it over a unix socket. Every handoff depends on the framing, the ack sequence and the restore path working. A supervisor that outlives the daemon would make a daemon upgrade a plain restart of the front end. - Streamable HTTP upstream sessions survive a takeover; SSE upstream sessions do not, because their standalone GET stream cannot be moved between processes. Those are closed and re-initialised on the successor's first call. - A cold restart does not resume upstream sessions. The lease table is restored from `sessions.json`, but the upstream `Mcp-Session-Id` is kept only in memory and in the takeover handoff, so after a restart each HTTP upstream is initialised again. -- An upstream session whose server is removed from the configuration during a takeover is not adopted and expires upstream on its own; it is not DELETEd. - A stdio server's identity is the bytes of its executable (`ExecIdentity`, `internal/config/execid.go`). That is wrong for a program that finds its own files relative to its real location: a node script beside its `node_modules`, re-pointed at a byte-identical copy in another directory, is kept by the automatic check and keeps running with the old directory's dependencies. Only a restart (`mcpx restart `) moves it. Above `limits.execHashMax` the identity is the inode, so such a copy is restarted. Decide whether the identity should include the program's directory for scripts, or whether a re-pointed link should always restart; the test `TestReloadFollowsAForRePointedCommandByWhatItRuns` pins the current choice. diff --git a/pkgs/mcpx/internal/daemon/registry_handoff.go b/pkgs/mcpx/internal/daemon/registry_handoff.go index 7a5bdcb52f..a5832d1639 100644 --- a/pkgs/mcpx/internal/daemon/registry_handoff.go +++ b/pkgs/mcpx/internal/daemon/registry_handoff.go @@ -73,12 +73,25 @@ func (h *RegistryHandoff) Restore() { // Adoption is a successor's children, held until the handoff commits. A child // is served by the pool with the same identity; one whose pool this // configuration no longer has is closed after commit, and its server starts -// again from the new definition on its next use. +// again from the new definition on its next use. An upstream HTTP session +// whose pool is gone has no child to close: it is ended upstream after +// commit instead, from the endpoint its handoff carries. type Adoption struct { all []*pool.Adopted byPool map[*pool.Pool][]*pool.Adopted seq map[*pool.Pool]int orphans []*pool.Adopted + // orphanSessions are handed HTTP sessions no pool here adopted. Nothing + // is contacted about them until Attach, so Abort leaves them entirely + // with the predecessor, which still owns them. + orphanSessions []orphanSession +} + +// orphanSession is a handed upstream HTTP session whose pool this +// configuration no longer has, with the name of the server it belonged to. +type orphanSession struct { + server string + h pool.InstanceHandoff } // Adopt takes the children of every handed pool. Nothing reads them yet. @@ -101,6 +114,11 @@ func (r *Registry) Adopt(hs []pool.PoolHandoff) (*Adoption, error) { p, ok := byID[h.PoolID] if !ok { a.orphans = append(a.orphans, ads...) + for _, in := range h.Instances { + if in.HTTP != nil { + a.orphanSessions = append(a.orphanSessions, orphanSession{server: h.Server, h: in}) + } + } continue } sessions, err := p.AdoptSessions(h.Instances) @@ -119,15 +137,18 @@ func (r *Registry) Adopt(hs []pool.PoolHandoff) (*Adoption, error) { } // Abort gives every adopted child back, for a handoff that did not commit. +// Orphan sessions were never contacted, so there is nothing to give back: +// the predecessor keeps serving them. func (a *Adoption) Abort() { for _, ad := range a.all { ad.Abort() } a.all = nil + a.orphanSessions = nil } -// Attach serves the adopted children and closes the orphans. Call it only -// after the handoff has committed. +// Attach serves the adopted children, closes the orphans and ends the +// orphaned upstream sessions. Call it only after the handoff has committed. func (a *Adoption) Attach() { for p, ads := range a.byPool { p.Attach(ads, a.seq[p]) @@ -135,4 +156,8 @@ func (a *Adoption) Attach() { for _, o := range a.orphans { o.Close() } + for _, s := range a.orphanSessions { + pool.TerminateOrphanedSession(s.server, s.h) + } + a.orphanSessions = nil } diff --git a/pkgs/mcpx/internal/daemon/registry_handoff_test.go b/pkgs/mcpx/internal/daemon/registry_handoff_test.go new file mode 100644 index 0000000000..d89123e8e5 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/registry_handoff_test.go @@ -0,0 +1,189 @@ +package daemon + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/dezren39/mcpx/internal/config" +) + +// orphanUpstream is a legacy streamable HTTP server that issues a session id +// on initialize and counts the DELETEs that end sessions. +type orphanUpstream struct { + *httptest.Server + mu sync.Mutex + live map[string]bool + issued int + deletes int + deleted []string +} + +func newOrphanUpstream(t *testing.T) *orphanUpstream { + t.Helper() + u := &orphanUpstream{live: map[string]bool{}} + u.Server = httptest.NewServer(http.HandlerFunc(u.serve)) + t.Cleanup(u.Close) + return u +} + +func (u *orphanUpstream) serve(w http.ResponseWriter, r *http.Request) { + u.mu.Lock() + defer u.mu.Unlock() + sid := r.Header.Get("Mcp-Session-Id") + switch r.Method { + case http.MethodDelete: + u.deletes++ + u.deleted = append(u.deleted, sid) + if u.live[sid] { + delete(u.live, sid) + w.WriteHeader(http.StatusOK) + return + } + w.WriteHeader(http.StatusNotFound) + case http.MethodPost: + var req struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + switch { + case req.Method == "initialize": + u.issued++ + sid = fmt.Sprintf("sess-%d", u.issued) + u.live[sid] = true + w.Header().Set("Mcp-Session-Id", sid) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "result": map[string]any{ + "protocolVersion": "2025-03-26", + "capabilities": map[string]any{"tools": map[string]any{}}, + "serverInfo": map[string]any{"name": "upstream", "version": "1"}, + }}) + case req.Method == "notifications/initialized": + w.WriteHeader(http.StatusAccepted) + case req.Method == "server/discover": + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "error": map[string]any{"code": -32601, "message": "method not found"}}) + case !u.live[sid]: + w.WriteHeader(http.StatusNotFound) + default: + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "result": map[string]any{}}) + } + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } +} + +func (u *orphanUpstream) counts() (deletes int, deleted []string) { + u.mu.Lock() + defer u.mu.Unlock() + return u.deletes, append([]string(nil), u.deleted...) +} + +// detachRemote starts a session on a registry whose only server is the +// upstream, then detaches it for a successor. +func detachRemote(t *testing.T, url string) (*Registry, *RegistryHandoff) { + t.Helper() + dir := t.TempDir() + cfg := &config.Config{MCPServers: map[string]*config.Server{ + "remote": {Name: "remote", URL: url + "/mcp"}, + }} + old, err := NewRegistry(cfg, Paths{State: dir, Cache: dir}, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(old.Close) + p, ok := old.Pool("remote") + if !ok { + t.Fatal("no pool for remote") + } + lease, err := p.Acquire(context.Background(), "global") + if err != nil { + t.Fatal(err) + } + if err := lease.Client().Ping(context.Background()); err != nil { + lease.Release() + t.Fatalf("ping: %v", err) + } + lease.Release() + ho, err := old.Detach(time.Second) + if err != nil { + t.Fatal(err) + } + if len(ho.Pools) != 1 || len(ho.Pools[0].Instances) != 1 || ho.Pools[0].Instances[0].HTTP == nil { + t.Fatalf("want the one upstream session handed on, got %+v", ho.Pools) + } + return old, ho +} + +func emptyRegistry(t *testing.T) *Registry { + t.Helper() + dir := t.TempDir() + next, err := NewRegistry(&config.Config{MCPServers: map[string]*config.Server{}}, Paths{State: dir, Cache: dir}, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(next.Close) + return next +} + +// A server removed from the configuration during a takeover has no pool to +// adopt its upstream session. The successor must end that session upstream +// once the handoff commits: exactly one DELETE, carrying the session id. +func TestTakeoverTerminatesARemovedServersUpstreamSession(t *testing.T) { + up := newOrphanUpstream(t) + _, ho := detachRemote(t, up.URL) + next := emptyRegistry(t) + + ad, err := next.Adopt(ho.Pools) + if err != nil { + t.Fatal(err) + } + ho.Commit() + ad.Attach() + + deletes, deleted := up.counts() + if deletes != 1 { + t.Fatalf("upstream saw %d DELETE(s), want exactly 1 for the removed server's session", deletes) + } + if len(deleted) != 1 || deleted[0] != "sess-1" { + t.Fatalf("DELETE carried session ids %v, want [sess-1]", deleted) + } +} + +// On the abort path the predecessor still owns the session: no DELETE, and +// the predecessor goes on serving it. +func TestAbortedTakeoverLeavesARemovedServersSessionAlone(t *testing.T) { + up := newOrphanUpstream(t) + old, ho := detachRemote(t, up.URL) + next := emptyRegistry(t) + + ad, err := next.Adopt(ho.Pools) + if err != nil { + t.Fatal(err) + } + ad.Abort() + ho.Restore() + + if deletes, _ := up.counts(); deletes != 0 { + t.Fatalf("an aborted handoff ended the upstream session with %d DELETE(s)", deletes) + } + p, _ := old.Pool("remote") + lease, err := p.Acquire(context.Background(), "global") + if err != nil { + t.Fatal(err) + } + defer lease.Release() + if err := lease.Client().Ping(context.Background()); err != nil { + t.Fatalf("the predecessor no longer serves the session after an abort: %v", err) + } + if deletes, _ := up.counts(); deletes != 0 { + t.Fatalf("serving after an abort ended the upstream session with %d DELETE(s)", deletes) + } +} diff --git a/pkgs/mcpx/internal/mcpclient/http.go b/pkgs/mcpx/internal/mcpclient/http.go index 3d3f4ce557..c203d83f4a 100644 --- a/pkgs/mcpx/internal/mcpclient/http.go +++ b/pkgs/mcpx/internal/mcpclient/http.go @@ -562,39 +562,93 @@ func (t *HTTPTransport) RecvContext() ([]byte, context.Context, error) { } } -// Close releases the session. +// Close releases the session. A failed DELETE is not reported: closing is +// best-effort everywhere it is called, and the session expires upstream on +// its own when the DELETE cannot be delivered. TerminateHTTPSession is the +// path that reports the failure, for a session nobody else will release. func (t *HTTPTransport) Close() error { + _ = t.closeSession() + return nil +} + +// closeSession ends the upstream session with a DELETE and reports whether +// that succeeded. A 404 means the upstream has already forgotten the +// session, which is the state the DELETE was for, so it is not a failure. +func (t *HTTPTransport) closeSession() error { + var out error t.closeOnce.Do(func() { close(t.closed) t.sessionMu.RLock() sid := t.sessionID t.sessionMu.RUnlock() - if sid != "" { - ctx, cancel := context.WithTimeout(context.Background(), defaults.UpstreamSessionDeleteTimeout) - defer cancel() - req, err := http.NewRequestWithContext(ctx, http.MethodDelete, t.url, nil) - if err == nil { - t.setHeaders(req) - if resp, err := t.hc.Do(req); err == nil { - resp.Body.Close() - } - } + if sid == "" { + return + } + ctx, cancel := context.WithTimeout(context.Background(), defaults.UpstreamSessionDeleteTimeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodDelete, t.url, nil) + if err != nil { + out = err + return + } + t.setHeaders(req) + resp, err := t.hc.Do(req) + if err != nil { + out = err + return + } + resp.Body.Close() + if resp.StatusCode >= http.StatusBadRequest && resp.StatusCode != http.StatusNotFound { + out = fmt.Errorf("delete %s: http %d", t.url, resp.StatusCode) } }) - return nil + return out +} + +// TerminateHTTPSession ends the session a handoff describes, for a successor +// that will not serve it: the server was removed from the configuration, so +// no pool of its own will ever close the session. It reports why the DELETE +// could not be delivered, including a handoff from a predecessor too old to +// carry the endpoint, so the caller can log the session it is leaving to +// expire upstream instead of dropping it silently. +func TerminateHTTPSession(h HTTPHandoff) error { + if h.SessionID == "" { + return errors.New("the handoff carries no session id") + } + if h.URL == "" { + return errors.New("the handoff carries no endpoint for the session") + } + tr, err := NewHTTP(HTTPOptions{URL: h.URL, Headers: h.Headers}) + if err != nil { + return err + } + tr.Resume(h) + return tr.closeSession() } -// HTTPHandoff is an upstream session as a successor process resumes it. +// HTTPHandoff is an upstream session as a successor process resumes it. The +// endpoint and headers travel with it, over the takeover's unix socket only, +// so a successor can still end the session when the server is no longer in +// its configuration and it has no endpoint of its own to dial. type HTTPHandoff struct { - SessionID string `json:"sessionId"` - Negotiated string `json:"negotiated,omitempty"` + SessionID string `json:"sessionId"` + Negotiated string `json:"negotiated,omitempty"` + URL string `json:"url,omitempty"` + Headers map[string]string `json:"headers,omitempty"` } // Handoff reports the session this transport holds, if the upstream issued one. func (t *HTTPTransport) Handoff() HTTPHandoff { t.sessionMu.RLock() defer t.sessionMu.RUnlock() - return HTTPHandoff{SessionID: t.sessionID, Negotiated: t.negotiated} + var headers map[string]string + if len(t.headers) > 0 { + headers = make(map[string]string, len(t.headers)) + for k, v := range t.headers { + headers[k] = v + } + } + return HTTPHandoff{SessionID: t.sessionID, Negotiated: t.negotiated, URL: t.url, Headers: headers} } // Resume continues a session a predecessor process established. Nothing is diff --git a/pkgs/mcpx/internal/pool/handoff.go b/pkgs/mcpx/internal/pool/handoff.go index 5c5ed70397..61ad4bd64e 100644 --- a/pkgs/mcpx/internal/pool/handoff.go +++ b/pkgs/mcpx/internal/pool/handoff.go @@ -35,8 +35,11 @@ type InstanceHandoff struct { // PoolHandoff is one pool's children in transit. PoolID names the process // definition, so a successor matches it to its own pool of the same identity. +// Server is the pool's server name, carried so a successor can name the +// server in what it reports about a handed session it cannot adopt. type PoolHandoff struct { PoolID string `json:"poolId"` + Server string `json:"server,omitempty"` Seq int `json:"seq"` Instances []InstanceHandoff `json:"instances"` } @@ -108,7 +111,7 @@ func (p *Pool) Detach() (*PoolHandoff, error) { p.mu.Lock() p.handed = handed p.mu.Unlock() - return &PoolHandoff{PoolID: p.PoolID(), Seq: seq, Instances: out}, nil + return &PoolHandoff{PoolID: p.PoolID(), Server: p.cfg.Name, Seq: seq, Instances: out}, nil } // Commit finishes a detach the successor accepted: handed children now belong @@ -238,6 +241,30 @@ func (p *Pool) AdoptSessions(hs []InstanceHandoff) ([]*Adopted, error) { return out, nil } +// TerminateOrphanedSession ends a handed upstream HTTP session that no pool +// in the successor's configuration adopted — its server was removed, or its +// definition changed enough to be a different pool. Call it only after the +// handoff has committed: before that the predecessor still owns the session. +// A session that cannot be terminated is not dropped silently: the lifecycle +// event names the server and the session left to expire upstream. +func TerminateOrphanedSession(server string, h InstanceHandoff) { + if h.HTTP == nil { + return + } + if err := mcpclient.TerminateHTTPSession(*h.HTTP); err != nil { + lifecycle("upstream.session.orphaned", map[string]any{ + "server": server, + "session": h.HTTP.SessionID, + "reason": err.Error(), + }) + return + } + lifecycle("upstream.session.terminated", map[string]any{ + "server": server, + "session": h.HTTP.SessionID, + }) +} + // Abort releases an adopted instance that will not be served. func (a *Adopted) Abort() { switch tr := a.tr.(type) { diff --git a/pkgs/mcpx/internal/pool/upstream_session_test.go b/pkgs/mcpx/internal/pool/upstream_session_test.go index 9ba5b70436..9198307bf1 100644 --- a/pkgs/mcpx/internal/pool/upstream_session_test.go +++ b/pkgs/mcpx/internal/pool/upstream_session_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/dezren39/mcpx/internal/config" + "github.com/dezren39/mcpx/internal/mcpclient" "github.com/dezren39/mcpx/internal/pool" ) @@ -164,6 +165,53 @@ func TestAnUpstreamSessionSurvivesATakeover(t *testing.T) { } } +// A handed session nobody adopted is ended upstream by +// TerminateOrphanedSession, once the predecessor has committed. +func TestTerminateOrphanedSessionEndsTheUpstreamSession(t *testing.T) { + terminated := lifecycleEvents(t, "upstream.session.terminated") + up := newSessionUpstream(t) + old := upstreamPool(t, up.URL) + pingThrough(t, old, "k") + ph, err := old.Detach() + if err != nil { + t.Fatal(err) + } + old.Commit() + pool.TerminateOrphanedSession("remote", ph.Instances[0]) + + up.mu.Lock() + defer up.mu.Unlock() + if up.deletes != 1 { + t.Fatalf("the orphaned session saw %d DELETE(s), want exactly 1", up.deletes) + } + events := terminated() + if len(events) != 1 || events[0]["server"] != "remote" || events[0]["session"] != "sess-1" { + t.Fatalf("terminated events = %v, want one naming remote/sess-1", events) + } +} + +// A session that cannot be terminated — the endpoint is already gone — is +// reported, not dropped silently. +func TestTerminateOrphanedSessionReportsAnUnreachableEndpoint(t *testing.T) { + orphaned := lifecycleEvents(t, "upstream.session.orphaned") + dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + url := dead.URL + dead.Close() + + pool.TerminateOrphanedSession("remote", pool.InstanceHandoff{ + ID: "i1", + HTTP: &mcpclient.HTTPHandoff{SessionID: "sess-9", Negotiated: "2025-03-26", URL: url + "/mcp"}, + }) + + events := orphaned() + if len(events) != 1 { + t.Fatalf("orphaned events = %v, want one", events) + } + if events[0]["server"] != "remote" || events[0]["session"] != "sess-9" || events[0]["reason"] == "" { + t.Fatalf("orphaned event = %v, want server, session and a reason", events[0]) + } +} + func TestAnExpiredUpstreamSessionIsReinitialised(t *testing.T) { up := newSessionUpstream(t) old := upstreamPool(t, up.URL)