diff --git a/cmd/mcpproxy/review_cmd.go b/cmd/mcpproxy/review_cmd.go
index 93e8fec69..1be524772 100644
--- a/cmd/mcpproxy/review_cmd.go
+++ b/cmd/mcpproxy/review_cmd.go
@@ -211,6 +211,9 @@ func runReviewWrite(server, operation string, value interface{}) error {
return err
}
warnApprovalHolds(os.Stderr, server, response)
+ if operation == "security/approve" || operation == "tools/approve" {
+ fmt.Fprintf(os.Stderr, "Approval updates policy; it does not confirm upstream connection or tool discovery. Check server.readiness with: mcpproxy review show %s -o json. Retry only after the upstream is connected and tools have been discovered.\n", server)
+ }
return nil
}
@@ -634,6 +637,9 @@ func formatReviewResponse(format string, raw []byte, full bool) error {
}
server, _ := value["server"].(map[string]interface{})
fmt.Printf("Server: %v\n", server["name"])
+ if readiness, ok := server["readiness"].(string); ok {
+ fmt.Printf("Readiness: %s (approval is separate from connection and discovery)\n", readiness)
+ }
if line := reviewScanLine(server); line != "" {
fmt.Println(line)
}
diff --git a/cmd/mcpproxy/review_cmd_test.go b/cmd/mcpproxy/review_cmd_test.go
index b2530243b..6a651b7b4 100644
--- a/cmd/mcpproxy/review_cmd_test.go
+++ b/cmd/mcpproxy/review_cmd_test.go
@@ -224,6 +224,15 @@ func TestReviewApproveReportsAppliedCountsAndWarnsOnHolds(t *testing.T) {
require.Contains(t, unknown.String(), "could not be read back")
}
+func TestReviewShowTable_SeparatesReadinessFromApproval(t *testing.T) {
+ for _, tc := range []struct{ readiness string }{{"connecting"}, {"connected"}, {"disabled"}} {
+ output := captureReviewOutput(t, func() error {
+ return formatReviewResponse("table", []byte(`{"data":{"server":{"name":"fixture","readiness":"`+tc.readiness+`"},"tools":[]}}`), false)
+ })
+ require.Contains(t, output, "Readiness: "+tc.readiness+" (approval is separate from connection and discovery)")
+ }
+}
+
func TestFormatReviewResponseTableQueueColumns(t *testing.T) {
raw := []byte(`{"data":{"servers":[{"server":"github","kind":"server_review","quarantined":true,"pending":2,"changed":1,"tier_counts":{"write":2},"scan":{"verdict":"warnings"}}]}}`)
diff --git a/frontend/src/components/ReviewScreen.vue b/frontend/src/components/ReviewScreen.vue
index 7758770cd..1456aa91b 100644
--- a/frontend/src/components/ReviewScreen.vue
+++ b/frontend/src/components/ReviewScreen.vue
@@ -243,9 +243,40 @@ function invalidateForceRetry() { if (lastBlock.value === null) return; lastBloc
// Explicit choices are bound to the reviewed incarnation (Spec 116 FR-017, review round 2): a refresh onto a same-name replacement drops them, so the replacement starts from its own defaults.
// Each load takes a generation; only the newest response may replace the review, so an older refresh that resolves late cannot resurrect an allow the newer definitions invalidated.
let loadGeneration = 0
+let readinessTimer: ReturnType | null = null
+let readinessEventTimer: ReturnType | null = null
+let readinessChecks = 0
+let readinessRequestGeneration = 0
+let active = true
+function scheduleReadinessRefresh() {
+ if (readinessTimer) { clearTimeout(readinessTimer); readinessTimer = null }
+ if (!active || review.value?.server.readiness !== 'connecting' || readinessChecks >= 15) return
+ readinessTimer = setTimeout(() => {
+ readinessTimer = null
+ readinessChecks++
+ void refreshReadiness()
+ }, 2000)
+}
+async function refreshReadiness() {
+ if (!review.value || refreshing.value || approving.value) { scheduleReadinessRefresh(); return }
+ const server = props.serverName
+ const visit = visitGeneration
+ const request = ++readinessRequestGeneration
+ const incarnation = review.value.server.incarnation
+ let res
+ try { res = await api.getServerReview(server) }
+ catch { if (isCurrent(server, visit) && request === readinessRequestGeneration) scheduleReadinessRefresh(); return }
+ if (!isCurrent(server, visit) || request !== readinessRequestGeneration || !review.value) return
+ if (!res.success || !res.data) { scheduleReadinessRefresh(); return }
+ // Poll only the connection hint. Never replace the reviewed tool definitions
+ // or an operator's pending selection with a background response.
+ if (res.data.server.incarnation !== incarnation) return
+ review.value = { ...review.value, server: { ...review.value.server, readiness: res.data.server.readiness, connected: res.data.server.connected } }
+ scheduleReadinessRefresh()
+}
// Each visit (a serverName change) takes a generation too: a response that started in an earlier visit is dropped even when the screen is back on the same server name (A -> B -> A).
let visitGeneration = 0
-async function load() { if (typeof api.getServerReview !== 'function') return; const server = props.serverName; const generation = ++loadGeneration; if (!review.value) loading.value = true; refreshing.value = true; invalidateForceRetry(); if (confirmOpen.value) { closeConfirm(); notice.value = STALE_FORCE_NOTICE }; error.value = ''; const res = await api.getServerReview(server); if (server !== props.serverName || generation !== loadGeneration) return; loading.value = false; refreshing.value = false; if (!res.success || !res.data) { error.value = res.error || 'Failed to load review'; return }; if (review.value && review.value.server.incarnation !== res.data.server.incarnation) choices.clear(); review.value = res.data; allowedTools.value = mergeSelection(res.data.tools, choices); invalidateForceRetry(); if (confirmOpen.value && blindReview !== res.data) { closeConfirm(); notice.value = STALE_FORCE_NOTICE }; emit('refreshed') }
+async function load() { if (typeof api.getServerReview !== 'function') return; readinessChecks = 0; readinessRequestGeneration++; const server = props.serverName; const generation = ++loadGeneration; if (!review.value) loading.value = true; refreshing.value = true; invalidateForceRetry(); if (confirmOpen.value) { closeConfirm(); notice.value = STALE_FORCE_NOTICE }; error.value = ''; const res = await api.getServerReview(server); if (server !== props.serverName || generation !== loadGeneration) return; loading.value = false; refreshing.value = false; if (!res.success || !res.data) { error.value = res.error || 'Failed to load review'; return }; if (review.value && review.value.server.incarnation !== res.data.server.incarnation) choices.clear(); review.value = res.data; allowedTools.value = mergeSelection(res.data.tools, choices); invalidateForceRetry(); if (confirmOpen.value && blindReview !== res.data) { closeConfirm(); notice.value = STALE_FORCE_NOTICE }; scheduleReadinessRefresh(); emit('refreshed') }
async function rescan() {
const server = props.serverName
const visit = visitGeneration
@@ -369,6 +400,14 @@ async function reloadAfterStaleReview(server: string, visit: number, message: st
}
async function blockTool(name: string) { const server = props.serverName; const visit = visitGeneration; toolNotice.value = ''; const res = await api.blockTools(server, [name], ...incarnationArgs(review.value?.server.incarnation)); if (!isCurrent(server, visit)) return; await load(); if (!res.success && isCurrent(server, visit)) toolNotice.value = res.error || 'Block failed' }
function refreshAfterReviewChange() { scanning.value = false; rescanning.value = false; void load() }
+function refreshAfterServersChange() {
+ if (readinessEventTimer) clearTimeout(readinessEventTimer)
+ readinessEventTimer = setTimeout(() => {
+ readinessEventTimer = null
+ readinessChecks = 0
+ void refreshReadiness()
+ }, 150)
+}
async function refreshAfterScanSettled(event: Event) {
const serverName = (event as CustomEvent<{ server_name?: string }>).detail?.server_name
if (serverName && serverName !== props.serverName) return
@@ -377,14 +416,21 @@ async function refreshAfterScanSettled(event: Event) {
void load()
}
// Component reuse across /review/A -> /review/B: scan state and any pending force retry belong to the old server.
-watch(() => props.serverName, () => { visitGeneration++; choices.clear(); review.value = null; allowedTools.value = []; clearFilters(); stateFilter.value = initialStateFilter(props.change); lastBlock.value = null; notice.value = ''; toolNotice.value = ''; approving.value = false; requarantining.value = false; refreshing.value = false; forceDialog.value?.close?.(); closeConfirm(); scanning.value = false; rescanning.value = false; error.value = ''; void load() })
+watch(() => props.serverName, () => { visitGeneration++; readinessChecks = 0; if (readinessTimer) clearTimeout(readinessTimer); readinessTimer = null; choices.clear(); review.value = null; allowedTools.value = []; clearFilters(); stateFilter.value = initialStateFilter(props.change); lastBlock.value = null; notice.value = ''; toolNotice.value = ''; approving.value = false; requarantining.value = false; refreshing.value = false; forceDialog.value?.close?.(); closeConfirm(); scanning.value = false; rescanning.value = false; error.value = ''; void load() })
onMounted(() => {
void load()
window.addEventListener('mcpproxy:review-changed', refreshAfterReviewChange)
window.addEventListener('mcpproxy:scan-settled', refreshAfterScanSettled)
+ window.addEventListener('mcpproxy:servers-changed', refreshAfterServersChange)
})
onUnmounted(() => {
+ active = false
+ visitGeneration++ // invalidate a readiness request already in flight
+ readinessRequestGeneration++
+ if (readinessTimer) clearTimeout(readinessTimer)
+ if (readinessEventTimer) clearTimeout(readinessEventTimer)
window.removeEventListener('mcpproxy:review-changed', refreshAfterReviewChange)
window.removeEventListener('mcpproxy:scan-settled', refreshAfterScanSettled)
+ window.removeEventListener('mcpproxy:servers-changed', refreshAfterServersChange)
})
diff --git a/frontend/src/components/profiles/ProfileCard.vue b/frontend/src/components/profiles/ProfileCard.vue
index 7ae172816..69f454657 100644
--- a/frontend/src/components/profiles/ProfileCard.vue
+++ b/frontend/src/components/profiles/ProfileCard.vue
@@ -14,10 +14,11 @@
{{ tierPhrase(profile.max_tier, profile.tool_counts) || 'No cap' }}
- - Read
- {{ profile.tool_counts.read }}
- - Write
- {{ profile.tool_counts.write }}
- - Destructive
- {{ profile.tool_counts.destructive }}
+ - Read allowed by profile
- {{ profile.tool_counts.read }}
+ - Write allowed by profile
- {{ profile.tool_counts.write }}
+ - Destructive allowed by profile
- {{ profile.tool_counts.destructive }}
+ {{ accessCounts.callable }} callable now · {{ Math.max(0, accessCounts.visible - accessCounts.callable) }} held · {{ accessCounts.hidden }} hidden
{{ profile.tool_counts.unannotated_hidden }} unannotated hidden
@@ -65,12 +66,12 @@ import { computed, ref } from 'vue'
import { useClientsStore } from '@/stores/clients'
import { isScopeParamAvailable, useScopeQuery } from '@/composables/useScopeQuery'
import { tierPhrase } from '@/utils/profiles'
-import type { ProfileView } from '@/types/api'
+import type { EffectiveToolsResult, ProfileView } from '@/types/api'
// Spec 108-i I17 / FR-040: one profile on the Profiles page. The four links go
// through Spec 109's link map (`linkTo`), so the profile travels as the
// `profile` URL filter and the target pages read it the same way everywhere.
-const props = defineProps<{ profile: ProfileView; tenant?: boolean }>()
+const props = defineProps<{ profile: ProfileView; tenant?: boolean; accessCounts?: EffectiveToolsResult['counts'] }>()
const emit = defineEmits<{ (e: 'assign'): void; (e: 'delete'): void }>()
const scope = useScopeQuery('profiles')
const menuOpen = ref(false)
diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts
index 8beeeb48d..d836af293 100644
--- a/frontend/src/types/api.ts
+++ b/frontend/src/types/api.ts
@@ -1509,7 +1509,7 @@ export interface ServerReviewResponse {
name: string; transport: string; command?: string; url?: string
/** Launch identity, already redacted by the core (UX-10); never read from the raw server config. */
args?: string[]; working_dir?: string
- quarantined: boolean; trust_mode?: string; source_registry_id?: string; source_registry_provenance?: string; scan?: ReviewScan
+ quarantined: boolean; enabled?: boolean; connected?: boolean; readiness?: 'disabled' | 'quarantined' | 'connecting' | 'connected' | 'disconnected' | 'auth_required' | 'error'; trust_mode?: string; source_registry_id?: string; source_registry_provenance?: string; scan?: ReviewScan
definitions_captured: boolean
/** Spec 116 FR-017: the reviewed server's identity; sent back as expected_incarnation. */
generation?: number; incarnation?: number
diff --git a/frontend/src/utils/reviewPresentation.ts b/frontend/src/utils/reviewPresentation.ts
index 2fb3c5e71..714b2b147 100644
--- a/frontend/src/utils/reviewPresentation.ts
+++ b/frontend/src/utils/reviewPresentation.ts
@@ -1,8 +1,7 @@
import type { ReviewScan, ReviewTool, ServerReviewResponse } from '@/types'
-// Pure presentation rules for the review screen. The strings are the shared
-// vocabulary of Spec 109 (fix-review-screen): the macOS app (ReviewPresentation
-// in ReviewQueueView.swift) and `mcpproxy review show` use the same sentences.
+// Pure presentation rules for the web review screen. The native app maintains
+// its own presentation and should be updated separately for wording parity.
export type ScanBannerSeverity = 'error' | 'warning' | 'success' | 'info'
export type ScanBannerAction = 'rescan' | 'scan-now' | 'none'
@@ -70,20 +69,27 @@ export function reviewHeadline(review: ServerReviewResponse): ReviewHeadline {
}
const tools = review.tools
const pending = tools.filter(needsReview).length
+ const approvedUnblocked = tools.filter(t => t.approval_status === 'approved' && !t.disabled).length
+ const blocked = tools.filter(t => t.disabled).length
+ const readiness = review.server.readiness === 'disabled' ? 'Server disabled.'
+ : review.server.readiness === 'connecting' ? 'Upstream connecting; retry after discovery.'
+ : review.server.readiness === 'connected' ? 'Upstream connected; tool discovery may still be in progress.'
+ : review.server.readiness === 'auth_required' ? 'Upstream authentication required.'
+ : review.server.readiness === 'error' ? 'Upstream connection error; check the server status.'
+ : review.server.readiness === 'disconnected' ? 'Upstream disconnected; check the server status.'
+ : 'Approval does not confirm upstream readiness.'
if (pending > 0) {
return {
state: 'review',
title: `Review ${name}`,
- subtitle: `${pending} ${plural(pending, 'tool needs', 'tools need')} review. Agents cannot call ${plural(pending, 'it', 'them')} until approved.`,
+ subtitle: `${pending} ${plural(pending, 'tool needs', 'tools need')} review · ${approvedUnblocked} approved and unblocked · ${blocked} blocked. ${readiness}`,
}
}
if (tools.length === 0) {
// Approved without seeing tools: still an approved server, just with nothing captured yet.
- return { state: 'approved', title: `${name} is approved`, subtitle: 'No tool definitions have been captured yet. New or changed tools come back here for review.' }
+ return { state: 'approved', title: `${name} is approved`, subtitle: `No tool definitions have been captured yet. ${readiness}` }
}
- const blocked = tools.filter(t => t.disabled).length
- const summary = `All ${tools.length} ${plural(tools.length, 'tool', 'tools')} approved${blocked > 0 ? ` (${blocked} blocked)` : ''}.`
- return { state: 'approved', title: `${name} is approved`, subtitle: `${summary} New or changed tools come back here for review.` }
+ return { state: 'approved', title: `${name} is approved`, subtitle: `${approvedUnblocked} approved and unblocked · ${blocked} blocked of ${tools.length}. ${readiness}` }
}
export type ToolControl = 'allow-toggle' | 'approve-reject' | 'approved' | 'blocked'
diff --git a/frontend/src/views/Profiles.vue b/frontend/src/views/Profiles.vue
index 895ae8b97..bc22bd041 100644
--- a/frontend/src/views/Profiles.vue
+++ b/frontend/src/views/Profiles.vue
@@ -35,6 +35,7 @@
v-for="profile in store.profiles"
:key="profile.name"
:profile="profile"
+ :access-counts="accessCounts[profile.name]"
:tenant="tenant"
@assign="assignTo = profile.name"
@delete="deleting = profile"
@@ -55,7 +56,7 @@
diff --git a/frontend/tests/unit/profiles-page.spec.ts b/frontend/tests/unit/profiles-page.spec.ts
index 5470888fa..6a1f38309 100644
--- a/frontend/tests/unit/profiles-page.spec.ts
+++ b/frontend/tests/unit/profiles-page.spec.ts
@@ -12,6 +12,7 @@ vi.mock('@/services/api', () => ({
default: {
hasAPIKey: vi.fn(() => true),
getProfiles: vi.fn(),
+ getProfileEffectiveTools: vi.fn(),
createProfile: vi.fn(),
getServers: vi.fn(),
getClients: vi.fn(),
@@ -62,6 +63,7 @@ describe('Profiles page (Spec 108-i T090, FR-040)', () => {
;(api.hasAPIKey as any).mockReturnValue(true)
setAvailableFeatures(['scope_filters'])
;(api.getProfiles as any).mockResolvedValue({ profiles: [work, legacy], anonymous_profile: 'work-ro' })
+ ;(api.getProfileEffectiveTools as any).mockResolvedValue({ counts: { visible: 25, callable: 1, hidden: 225 } })
;(api.getServers as any).mockResolvedValue({ success: true, data: { servers: [{ name: 'github' }, { name: 'notion' }] } })
;(api.getClients as any).mockResolvedValue({ success: true, data: { clients: [makeClient('cursor'), makeClient('claude-code', { display_name: 'Claude Code' })], warnings: [] } })
})
@@ -80,7 +82,8 @@ describe('Profiles page (Spec 108-i T090, FR-040)', () => {
const card = wrapper.get('[data-test="profile-card-work-ro"]')
expect(card.text()).toContain('Work')
expect(card.text()).toContain('work-ro')
- expect(card.get('[data-test="profile-counts"]').text()).toMatch(/Read\s*4.*Write\s*2.*Destructive\s*1/)
+ expect(card.get('[data-test="profile-counts"]').text()).toMatch(/Read allowed by profile\s*4.*Write allowed by profile\s*2.*Destructive allowed by profile\s*1/)
+ expect(card.get('[data-test="profile-access-counts"]').text()).toContain('1 callable now · 24 held · 225 hidden')
expect(card.get('[data-test="profile-unannotated"]').text()).toBe('3 unannotated hidden')
expect(card.get('[data-test="profile-used-by"]').text()).toContain('Cursor')
expect(card.get('[data-test="profile-used-by"]').text()).toContain('\u{1F512}')
@@ -91,6 +94,31 @@ describe('Profiles page (Spec 108-i T090, FR-040)', () => {
expect(wrapper.get('[data-test="profile-legacy-legacy"]').text()).toBe('Servers only')
})
+ it('keeps the last callable count visible while debouncing server change refreshes', async () => {
+ const { wrapper } = await mountAt()
+ const count = () => wrapper.get('[data-test="profile-card-work-ro"]').get('[data-test="profile-access-counts"]').text()
+ expect(count()).toContain('1 callable now')
+ let finish!: (value: unknown) => void
+ const delayed = new Promise(resolve => { finish = resolve })
+ ;(api.getProfileEffectiveTools as any).mockReturnValueOnce(delayed)
+ vi.useFakeTimers()
+ try {
+ const initialCalls = (api.getProfileEffectiveTools as any).mock.calls.length
+ window.dispatchEvent(new Event('mcpproxy:servers-changed'))
+ window.dispatchEvent(new Event('mcpproxy:servers-changed'))
+ expect(count()).toContain('1 callable now')
+ await vi.advanceTimersByTimeAsync(150)
+ expect((api.getProfileEffectiveTools as any).mock.calls.length).toBe(initialCalls + 2)
+ expect(count()).toContain('1 callable now')
+ finish({ counts: { visible: 0, callable: 0, hidden: 0 } })
+ await flushPromises()
+ expect(count()).toContain('0 callable now')
+ wrapper.unmount()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it('omits the Used by line when used_by is absent (non-administrator)', async () => {
;(api.getProfiles as any).mockResolvedValue({ profiles: [makeProfile('work-ro')] })
const { wrapper } = await mountAt()
diff --git a/frontend/tests/unit/review-screen-approved-state.spec.ts b/frontend/tests/unit/review-screen-approved-state.spec.ts
index 963a725f0..2dad5a650 100644
--- a/frontend/tests/unit/review-screen-approved-state.spec.ts
+++ b/frontend/tests/unit/review-screen-approved-state.spec.ts
@@ -11,11 +11,11 @@ vi.mock('@/services/api', () => ({ default: {
type Tool = { name: string; approval_status: string; disabled?: boolean }
-function payload(quarantined: boolean, tools: Tool[]) {
+function payload(quarantined: boolean, tools: Tool[], readiness: 'connecting' | 'connected' | 'disconnected' | 'auth_required' | 'error' = 'connected') {
return {
success: true,
data: {
- server: { name: 'fixture', transport: 'stdio', quarantined, definitions_captured: true, scan: { verdict: 'clean', risk_score: 0, coverage: 'current', tools_scanned: tools.length } },
+ server: { name: 'fixture', transport: 'stdio', quarantined, readiness, definitions_captured: true, scan: { verdict: 'clean', risk_score: 0, coverage: 'current', tools_scanned: tools.length } },
tools: tools.map(t => ({ description: t.name, tier: 'read', disabled: false, scan_verdict: 'clean', ...t })),
},
}
@@ -53,14 +53,121 @@ describe('ReviewScreen approved state', () => {
expect(wrapper.get('[data-test="review-tool-state-a"]').text()).toBe('Approved')
expect(wrapper.get('[data-test="review-tool-state-c"]').text()).toBe('Blocked')
expect(wrapper.get('[data-test="review-heading"]').text()).toBe('fixture is approved')
- expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('All 3 tools approved (1 blocked)')
+ expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('2 approved and unblocked · 1 blocked of 3')
expect(wrapper.text()).not.toContain('Review tool definitions before changing what agents can call')
expect(wrapper.get('[data-test="review-manage-tools"]').attributes('data-to')).toBe('/servers/fixture?tab=tools')
})
it('omits the blocked count when nothing is blocked', async () => {
const wrapper = await mountScreen(false, approvedTools.slice(0, 2))
- expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('All 2 tools approved.')
+ expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('2 approved and unblocked · 0 blocked of 2')
+ })
+
+ it('explains selective approval and connecting without promising a callable tool', async () => {
+ const tools = Array.from({ length: 25 }, (_, i) => ({ name: `tool_${i}`, approval_status: 'approved', disabled: i > 0 }))
+ ;(api.getServerReview as any).mockResolvedValue(payload(false, tools, 'connecting'))
+ const wrapper = mount(ReviewScreen, {
+ props: { serverName: 'fixture' },
+ global: { stubs: { RouterLink: { props: ['to'], template: '' } } },
+ })
+ await flushPromises()
+ expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('1 approved and unblocked · 24 blocked of 25. Upstream connecting')
+ wrapper.unmount()
+ })
+
+ it('stops readiness polling when an in-flight response resolves after unmount', async () => {
+ vi.useFakeTimers()
+ try {
+ let finishPoll!: (result: ReturnType) => void
+ const pendingPoll = new Promise>(resolve => { finishPoll = resolve })
+ ;(api.getServerReview as any)
+ .mockResolvedValueOnce(payload(false, approvedTools, 'connecting'))
+ .mockReturnValueOnce(pendingPoll)
+ const wrapper = mount(ReviewScreen, {
+ props: { serverName: 'fixture' },
+ global: { stubs: { RouterLink: { props: ['to'], template: '' } } },
+ })
+ await flushPromises()
+ expect(api.getServerReview).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(api.getServerReview).toHaveBeenCalledTimes(2)
+ wrapper.unmount()
+ finishPoll(payload(false, approvedTools, 'connecting'))
+ await flushPromises()
+ await vi.advanceTimersByTimeAsync(4000)
+ expect(api.getServerReview).toHaveBeenCalledTimes(2)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('retries a transient readiness failure and stops once connected', async () => {
+ vi.useFakeTimers()
+ try {
+ ;(api.getServerReview as any)
+ .mockResolvedValueOnce(payload(false, approvedTools, 'connecting'))
+ .mockRejectedValueOnce(new Error('temporary'))
+ .mockResolvedValueOnce(payload(false, approvedTools, 'connected'))
+ const wrapper = mount(ReviewScreen, {
+ props: { serverName: 'fixture' },
+ global: { stubs: { RouterLink: { props: ['to'], template: '' } } },
+ })
+ await flushPromises()
+ await vi.advanceTimersByTimeAsync(4000)
+ await flushPromises()
+ expect(api.getServerReview).toHaveBeenCalledTimes(3)
+ expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('Upstream connected')
+ await vi.advanceTimersByTimeAsync(4000)
+ expect(api.getServerReview).toHaveBeenCalledTimes(3)
+ wrapper.unmount()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('caps background checks and grants a fresh budget after an explicit review refresh', async () => {
+ vi.useFakeTimers()
+ try {
+ ;(api.getServerReview as any).mockResolvedValue(payload(false, approvedTools, 'connecting'))
+ const wrapper = mount(ReviewScreen, {
+ props: { serverName: 'fixture' },
+ global: { stubs: { RouterLink: { props: ['to'], template: '' } } },
+ })
+ await flushPromises()
+ await vi.advanceTimersByTimeAsync(32000)
+ expect(api.getServerReview).toHaveBeenCalledTimes(16) // first load and 15 bounded polls
+ await vi.advanceTimersByTimeAsync(4000)
+ expect(api.getServerReview).toHaveBeenCalledTimes(16)
+ window.dispatchEvent(new Event('mcpproxy:review-changed'))
+ await flushPromises()
+ expect(api.getServerReview).toHaveBeenCalledTimes(17)
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(api.getServerReview).toHaveBeenCalledTimes(18)
+ wrapper.unmount()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('distinguishes authentication and errors from a connection attempt', async () => {
+ vi.useFakeTimers()
+ try {
+ ;(api.getServerReview as any).mockResolvedValue(payload(false, approvedTools, 'auth_required'))
+ const wrapper = mount(ReviewScreen, {
+ props: { serverName: 'fixture' },
+ global: { stubs: { RouterLink: { props: ['to'], template: '' } } },
+ })
+ await flushPromises()
+ expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('Upstream authentication required')
+ ;(api.getServerReview as any).mockResolvedValue(payload(false, approvedTools, 'error'))
+ window.dispatchEvent(new Event('mcpproxy:servers-changed'))
+ await vi.advanceTimersByTimeAsync(150)
+ await flushPromises()
+ expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('Upstream connection error')
+ wrapper.unmount()
+ } finally {
+ vi.useRealTimers()
+ }
})
it('confirms before quarantining to review again, then reloads', async () => {
@@ -99,6 +206,7 @@ describe('ReviewScreen approved state', () => {
])
expect(wrapper.get('[data-test="review-heading"]').text()).toBe('Review fixture')
expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('1 tool needs review')
+ expect(wrapper.get('[data-test="review-subtitle"]').text()).toContain('1 approved and unblocked')
expect(wrapper.get('[data-test="review-tool-a"]').findAll('button').map(b => b.text())).toEqual([])
expect(wrapper.get('[data-test="review-tool-a"]').get('[data-test="review-tool-state-a"]').text()).toBe('Approved')
expect(wrapper.get('[data-test="review-tool-b"]').findAll('button').map(b => b.text())).toEqual(['Approve', 'Reject'])
diff --git a/internal/runtime/review.go b/internal/runtime/review.go
index 48d58953b..97cfbac26 100644
--- a/internal/runtime/review.go
+++ b/internal/runtime/review.go
@@ -16,10 +16,24 @@ import (
"github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/security/scanner"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/storage"
+ upstreamtypes "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/types"
)
var ErrReviewServerNotFound = errors.New("review server not found")
+func reviewConnectionReadiness(state upstreamtypes.ConnectionState) string {
+ switch state {
+ case upstreamtypes.StateConnecting, upstreamtypes.StateAuthenticating, upstreamtypes.StateDiscovering:
+ return "connecting"
+ case upstreamtypes.StatePendingAuth:
+ return "auth_required"
+ case upstreamtypes.StateError:
+ return "error"
+ default:
+ return "disconnected"
+ }
+}
+
// ReviewQueue is the composed, server-level review list shared by REST, CLI,
// MCP and native clients.
type ReviewQueue struct {
@@ -88,20 +102,26 @@ type ServerReview struct {
}
type ReviewServer struct {
- Name string `json:"name"`
- Transport string `json:"transport"`
- Command string `json:"command,omitempty"`
- Args []string `json:"args,omitempty"`
- WorkingDir string `json:"working_dir,omitempty"`
- URL string `json:"url,omitempty"`
- Env map[string]string `json:"env,omitempty"`
- Headers map[string]string `json:"headers,omitempty"`
- Quarantined bool `json:"quarantined"`
- TrustMode string `json:"trust_mode"`
- SourceRegistryID string `json:"source_registry_id,omitempty"`
- SourceRegistryProvenance string `json:"source_registry_provenance,omitempty"`
- Scan *ReviewScan `json:"scan,omitempty"`
- DefinitionsCaptured bool `json:"definitions_captured"`
+ Name string `json:"name"`
+ Transport string `json:"transport"`
+ Command string `json:"command,omitempty"`
+ Args []string `json:"args,omitempty"`
+ WorkingDir string `json:"working_dir,omitempty"`
+ URL string `json:"url,omitempty"`
+ Env map[string]string `json:"env,omitempty"`
+ Headers map[string]string `json:"headers,omitempty"`
+ Quarantined bool `json:"quarantined"`
+ Enabled bool `json:"enabled"`
+ Connected bool `json:"connected"`
+ // Readiness is a conservative connection hint, not a callable verdict.
+ // "connected" may still precede tool discovery; effective-tools supplies
+ // the canonical per-tool callable projection.
+ Readiness string `json:"readiness"`
+ TrustMode string `json:"trust_mode"`
+ SourceRegistryID string `json:"source_registry_id,omitempty"`
+ SourceRegistryProvenance string `json:"source_registry_provenance,omitempty"`
+ Scan *ReviewScan `json:"scan,omitempty"`
+ DefinitionsCaptured bool `json:"definitions_captured"`
// LiveToolCount and LastCaptureAt are the fresh-capture proof: how many of
// the stored records the upstream listed in its most recent capture, and
// when that capture ran. They are separate from the stored-record
@@ -252,12 +272,33 @@ func (r *Runtime) GetServerReview(ctx context.Context, serverName string) (*Serv
Name: contractServer.Name, Transport: reviewTransport(server.Protocol),
Command: contractServer.Command, Args: contractServer.Args, WorkingDir: contractServer.WorkingDir,
URL: contractServer.URL, Env: contractServer.Env, Headers: contractServer.Headers,
- Quarantined: server.Quarantined, TrustMode: string(server.EffectiveTrustMode()),
+ Quarantined: server.Quarantined, Enabled: server.Enabled, TrustMode: string(server.EffectiveTrustMode()),
SourceRegistryID: server.SourceRegistryID, SourceRegistryProvenance: server.SourceRegistryProvenance,
}
if hasGen {
reviewServer.Generation, reviewServer.Incarnation = gen.Gen, gen.Incarnation
}
+ // Approval commits policy; it does not wait for an upstream connection or
+ // discovery. Keep readiness separate so an approved review never promises an
+ // immediately successful call.
+ switch {
+ case !server.Enabled:
+ reviewServer.Readiness = "disabled"
+ case server.Quarantined:
+ reviewServer.Readiness = "quarantined"
+ default:
+ reviewServer.Readiness = "disconnected"
+ if r.upstreamManager != nil {
+ if client, ok := r.upstreamManager.GetClient(serverName); ok && client != nil {
+ if client.IsConnected() {
+ reviewServer.Connected = true
+ reviewServer.Readiness = "connected"
+ } else {
+ reviewServer.Readiness = reviewConnectionReadiness(client.GetConnectionInfo().State)
+ }
+ }
+ }
+ }
// Stored records and the live capture state are published by different
// writers. A capture holds captureSnapMu for persist + prune + stamp, so
// reading both under the read lock yields one generation, never a mix.
diff --git a/internal/runtime/review_test.go b/internal/runtime/review_test.go
index b76d77a3f..d2c0afe09 100644
--- a/internal/runtime/review_test.go
+++ b/internal/runtime/review_test.go
@@ -14,6 +14,7 @@ import (
"github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/security/scanner"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/storage"
+ upstreamtypes "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/types"
)
func TestReviewFixtureContract(t *testing.T) {
@@ -89,6 +90,7 @@ func TestReviewFixtureContract(t *testing.T) {
review, err := rt.GetServerReview(context.Background(), "filesystem")
require.NoError(t, err)
require.True(t, review.Server.DefinitionsCaptured)
+ require.Equal(t, "quarantined", review.Server.Readiness)
require.Len(t, review.Tools, fixture.Expected.ToolCount)
gotByName := make(map[string]ReviewTool, len(review.Tools))
for _, got := range review.Tools {
@@ -175,6 +177,35 @@ func TestReviewPayload_ClassifiesCapturedAndLegacyAnnotations(t *testing.T) {
require.Contains(t, byName["safe"].Diff.Annotations, "Old title")
}
+func TestReviewReadiness_DoesNotTreatApprovalAsConnection(t *testing.T) {
+ rt := setupQuarantineRuntime(t, nil, []*config.ServerConfig{
+ {Name: "approved", Enabled: true},
+ {Name: "parked", Enabled: false},
+ })
+ for _, tc := range []struct{ name, want string }{{"approved", "disconnected"}, {"parked", "disabled"}} {
+ review, err := rt.GetServerReview(context.Background(), tc.name)
+ require.NoError(t, err)
+ require.Equal(t, tc.want, review.Server.Readiness)
+ require.False(t, review.Server.Connected)
+ }
+}
+
+func TestReviewConnectionReadiness(t *testing.T) {
+ for _, tc := range []struct {
+ state upstreamtypes.ConnectionState
+ want string
+ }{
+ {upstreamtypes.StateDisconnected, "disconnected"},
+ {upstreamtypes.StateConnecting, "connecting"},
+ {upstreamtypes.StateAuthenticating, "connecting"},
+ {upstreamtypes.StateDiscovering, "connecting"},
+ {upstreamtypes.StatePendingAuth, "auth_required"},
+ {upstreamtypes.StateError, "error"},
+ } {
+ require.Equal(t, tc.want, reviewConnectionReadiness(tc.state))
+ }
+}
+
func TestReviewPayload_QueueAndUncapturedDefinitions(t *testing.T) {
rt := setupQuarantineRuntime(t, nil, []*config.ServerConfig{
{Name: "filesystem", Enabled: true, Quarantined: true},