Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/arch/10-virtual-mcp-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,15 @@ if the relocated backend serves a different tool set, existing sessions pick
it up via the backend's own `list_changed` or on reconnect, matching the
agreed membership-only scope.

**Embedder-triggered resync**: an embedder that wraps the core with a
per-identity view (for example, one that hides a backend whose credential a
user has lost) has a change that neither a backend `list_changed` nor a health
flip reports. `Server.ResyncTools(match)` lets it trigger the same registered
workers for the sessions whose registration-time identity satisfies `match`
(nil selects all). It purges the cache once, like the health fan-out, purges
nothing when no session matches, and is a no-op in optimizer mode. It reaches
only registered sessions, so it has the same health-monitoring requirement.

**Implementation**: `pkg/vmcp/health/change_notifier.go` (`ChangeListener`,
debounce), `pkg/vmcp/health/monitor.go` (`OnChange`, fire points),
`pkg/vmcp/health/status.go` (advertisability-transition detection),
Expand Down
44 changes: 44 additions & 0 deletions pkg/vmcp/server/serve_health_resync.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"sync"

"github.com/stacklok/toolhive-core/mcpcompat/server"
"github.com/stacklok/toolhive/pkg/auth"
)

// This file holds the backend-health-driven tools resync added by #5786 (PR1,
Expand Down Expand Up @@ -150,3 +151,46 @@ func (s *Server) resyncSessionsOnBackendHealthChange(generation uint64) {
w.trigger(false)
}
}

// ResyncTools asks every live session whose captured identity satisfies match to
// re-derive its advertised tools, and returns how many sessions it scheduled. A nil
// match selects every session. Each selected session's tool store is replaced and the
// SDK then sends the client notifications/tools/list_changed.
//
// An embedder that wraps the core with a per-identity view calls this when that view
// changes for an identity while the backends themselves have not: neither a backend
// list_changed notification nor a backend health change fires then, so a connected
// client would otherwise keep the tool list it was given at registration. match is
// called with the identity the session was registered for, or nil for an anonymous
// session. It must not block or modify the identity.
//
// The call purges the shared capability cache once, before scheduling, like a health
// change does: the cached aggregation for an identity can predate the change. It
// purges nothing when match selects no session. Per-session coalescing bounds the
// work, so a burst of calls costs each session at most one in-flight re-derivation
// plus one queued follow-up. The resync runs on the session's own worker, off the
// caller's goroutine, so a caller does not wait for it.
//
// Only sessions registered for health-driven fan-out are reachable: passthrough mode
// with backend health monitoring enabled. In optimizer mode the advertised set is the
// find_tool and call_tool meta-tools, which a per-identity change does not alter, so
// the call does nothing and returns 0.
func (s *Server) ResyncTools(match func(*auth.Identity) bool) int {
if s.optimizerFactory != nil {
return 0
}
var selected []*listChangedResyncWorker
for _, w := range s.healthResync.snapshot() {
if match == nil || match(w.identity) {
selected = append(selected, w)
}
}
if len(selected) == 0 {
return 0
}
s.core.InvalidateCapabilityCache()
for _, w := range selected {
w.trigger(false)
}
return len(selected)
}
7 changes: 6 additions & 1 deletion pkg/vmcp/server/serve_list_changed.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ type listChangedResyncWorker struct {
// baseCtx bounds every run to the server lifetime (cancelled on Stop) so a
// late notification cannot start work that outlives the server.
baseCtx context.Context
// identity is the principal the session was registered for, captured at
// registration like the one run re-derives under. ResyncTools matches on it
// to select sessions. It is nil for an anonymous session and read-only.
identity *auth.Identity

mu sync.Mutex
running bool
Expand Down Expand Up @@ -159,7 +163,8 @@ func (s *Server) buildListChangedSink(
) (vmcpsession.ListChangedSink, *listChangedResyncWorker) {
newWorker := func(kind vmcpsession.ChangeKind) *listChangedResyncWorker {
return &listChangedResyncWorker{
baseCtx: s.resyncBaseCtx,
baseCtx: s.resyncBaseCtx,
identity: identity,
run: func(ctx context.Context, purge bool) {
s.runListChangedResync(ctx, sessionID, session, identity, forwardedHeaders, kind, purge)
},
Expand Down
130 changes: 130 additions & 0 deletions pkg/vmcp/server/serve_session_resync_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

package server

import (
"context"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/stacklok/toolhive/pkg/auth"
"github.com/stacklok/toolhive/pkg/vmcp"
)

// registerResyncSession registers a live session for identity with srv's resync registry,
// the way session registration does, and returns its fake SDK session.
func registerResyncSession(srv *Server, id string, identity *auth.Identity) *fakeToolsSession {
sess := &fakeToolsSession{id: id}
_, toolsWorker := srv.buildListChangedSink(id, sess, identity, nil)
srv.healthResync.add(id, toolsWorker)
return sess
}

func newResyncTestServer(fc *fakeCore) *Server {
return &Server{
core: fc,
vmcpSessionMgr: &stubSessionManager{alive: true},
resyncBaseCtx: context.Background(),
}
}

// TestResyncSessionTools_ResyncsOnlyMatchingSessions verifies an embedder can resync the
// sessions of one identity after a change only that identity sees: the matching session's
// tool store is replaced with the core's current view, the other session is untouched, and
// the shared capability cache is purged once for the call.
func TestResyncTools_ResyncsOnlyMatchingSessions(t *testing.T) {
t.Parallel()

fc := &fakeCore{tools: []vmcp.Tool{{Name: "recovered"}}}
srv := newResyncTestServer(fc)
alice := registerResyncSession(srv, "alice-session", &auth.Identity{Subject: "alice"})
bob := registerResyncSession(srv, "bob-session", &auth.Identity{Subject: "bob"})

triggered := srv.ResyncTools(func(id *auth.Identity) bool {
return id != nil && id.Subject == "alice"
})

assert.Equal(t, 1, triggered)
require.Eventually(t, func() bool { return alice.setToolsCalls() > 0 },
2*time.Second, 10*time.Millisecond, "the matching session must be resynced")
assert.Contains(t, alice.GetSessionTools(), "recovered")
assert.Equal(t, 0, bob.setToolsCalls(), "a session whose identity did not match must not be resynced")
assert.Equal(t, int32(1), fc.invalidateCacheCalls.Load(),
"the call must purge the capability cache once, so the re-derivation re-sweeps backends")
}

// TestResyncSessionTools_NilMatchResyncsEverySession verifies a nil match selects every
// registered session, including one with no captured identity.
func TestResyncTools_NilMatchResyncsEverySession(t *testing.T) {
t.Parallel()

fc := &fakeCore{tools: []vmcp.Tool{{Name: "t"}}}
srv := newResyncTestServer(fc)
sessions := []*fakeToolsSession{
registerResyncSession(srv, "alice-session", &auth.Identity{Subject: "alice"}),
registerResyncSession(srv, "anonymous-session", nil),
}

triggered := srv.ResyncTools(nil)

assert.Equal(t, 2, triggered)
for _, sess := range sessions {
require.Eventually(t, func() bool { return sess.setToolsCalls() > 0 },
2*time.Second, 10*time.Millisecond, "every registered session must be resynced")
}
}

// TestResyncSessionTools_MatchReceivesNilForAnAnonymousSession verifies the match function is
// called with nil, not skipped, for a session registered without an identity, so the embedder
// decides whether such a session is in scope.
func TestResyncTools_MatchReceivesNilForAnAnonymousSession(t *testing.T) {
t.Parallel()

fc := &fakeCore{tools: []vmcp.Tool{{Name: "t"}}}
srv := newResyncTestServer(fc)
anonymous := registerResyncSession(srv, "anonymous-session", nil)

triggered := srv.ResyncTools(func(id *auth.Identity) bool { return id == nil })

assert.Equal(t, 1, triggered)
require.Eventually(t, func() bool { return anonymous.setToolsCalls() > 0 },
2*time.Second, 10*time.Millisecond, "an anonymous session the match function accepts must be resynced")
}

// TestResyncSessionTools_NoMatchDoesNothing verifies a call that selects no session neither
// triggers a resync nor purges the capability cache.
func TestResyncTools_NoMatchDoesNothing(t *testing.T) {
t.Parallel()

fc := &fakeCore{tools: []vmcp.Tool{{Name: "t"}}}
srv := newResyncTestServer(fc)
alice := registerResyncSession(srv, "alice-session", &auth.Identity{Subject: "alice"})

triggered := srv.ResyncTools(func(*auth.Identity) bool { return false })

assert.Equal(t, 0, triggered)
assert.Equal(t, 0, alice.setToolsCalls())
assert.Equal(t, int32(0), fc.invalidateCacheCalls.Load(), "a call that selects nothing must not purge the cache")
}

// TestResyncSessionTools_OptimizerModeDoesNothing verifies optimizer mode is a no-op: the
// advertised set is the find_tool/call_tool meta-tools, which a per-identity change does not
// alter.
func TestResyncTools_OptimizerModeDoesNothing(t *testing.T) {
t.Parallel()

fc := &fakeCore{tools: []vmcp.Tool{{Name: "t"}}}
srv := newResyncTestServer(fc)
srv.optimizerFactory = stubOptimizerFactory
alice := registerResyncSession(srv, "alice-session", &auth.Identity{Subject: "alice"})

triggered := srv.ResyncTools(nil)

assert.Equal(t, 0, triggered)
assert.Equal(t, 0, alice.setToolsCalls())
assert.Equal(t, int32(0), fc.invalidateCacheCalls.Load())
}
Loading