Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(connectors): tri-state read-model + mcp-connectors endpoint (U1)
Diego Zacarias5d9b22902343
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 7c4508c9e..a08b64823 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.498",+ "version": "0.1.499","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.498",+ "version": "0.1.499","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --git a/control-api/package.json b/control-api/package.jsonindex 994945d9e..842aace95 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.498",+ "version": "0.1.499","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/rpc-access/users.ts b/control-api/src/routes/rpc-access/users.tsindex 9fa68f163..234b1297c 100644--- a/control-api/src/routes/rpc-access/users.ts+++ b/control-api/src/routes/rpc-access/users.ts@@ -9,7 +9,10 @@ import {requireValidRpcAccessTokenAny,} from '../../middleware/rpcAccessAuth.js'import type { RpcAccessClaims } from '../../profileTypes.js'-import { resolveInvocableMcpServersForContexts } from '../../services/access/mcpInvocable.js'+import {+ resolveConnectorsForAgents,+ resolveInvocableMcpServersForContexts,+} from '../../services/access/mcpInvocable.js'import {type RpcHostAccessDenialReason,type RpcHostAccessDirectory,@@ -140,6 +143,35 @@ export function createRpcAccessUsersRouter(})+ // Proactive connectors panel read-model (spec 11 U1): the CLASSIFIED fleet+ // per agent — `authorized` / `requires_setup` / `no_oauth`. Same gate as+ // `/mcp-servers`; `req.params.userId` is authoritative (bound to the RPC+ // token subject by `requireRpcTokenUserMatch()`) and flows only into the+ // grant-presence key, never from a body. Agents derive from `getUserAgents`.+ router.get(+ '/rpc/access/users/:userId/mcp-connectors',+ requireValidRpcAccessToken(),+ requireRpcTokenUserMatch(),+ async (req, res, next) => {+ try {+ const { agentNames } = await getUserAgents(req.params.userId)+ const agents = await resolveConnectorsForAgents(+ gateway,+ {+ mcpServersNamespace: config.mcpServersNamespace,+ hostsNamespace: config.hostsNamespace,+ agentNames,+ userId: req.params.userId,+ },+ { query: (text, values) => pool.query(text, values) }+ )+ res.status(200).json({ userId: req.params.userId, agents })+ } catch (error) {+ next(error)+ }+ }+ )+// One control-plane authority serves both read-only Host resolution and the// message-path resolve+bind operation. Access requires the signed subject and// host claim, a live user/team directory grant, and an enabled Host CR.diff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.tsindex 8689e9d0d..e46b996e3 100644--- a/control-api/src/services/access/mcpInvocable.ts+++ b/control-api/src/services/access/mcpInvocable.ts@@ -26,13 +26,16 @@*/import type { DbClient } from '../../db.js'import type { K8sGateway } from '../../k8s.js'-import { resolveServerOAuth } from '../../oauth/mcpServerOAuthSpec.js'+import { type GrantScope, resolveServerOAuth } from '../../oauth/mcpServerOAuthSpec.js'import { oauthGrantExists } from '../../oauth/store.js'+import { rootLogger } from '../../observability/logger.js'import {type AgentDirectoryEntry,buildAgentDirectoryEntry,} from '../directory/accessReconciliation.js'+const connectorsLog = rootLogger.child({ module: 'mcp-connectors' })+export interface InvocableMcpServer {name: stringurl: string@@ -43,6 +46,38 @@ export interface AgentWithMcpServers extends AgentDirectoryEntry {mcpServers: Array<{ name: string }>}+/**+ * Tri-state authorization status of one connector for the proactive panel+ * (spec 11 U1). Derived, never invented:+ * - `no_oauth` — the server is not governed by this OAuth rail+ * (`resolveServerOAuth` = null, i.e. static/none/no id).+ * - `authorized` — an OAuth server WITH a valid grant by its flavor.+ * - `requires_setup` — an OAuth server WITHOUT a grant (the "needs-connect").+ * The `authorized`/`requires_setup` split comes SOLELY from `oauthGrantExists`+ * over `oauth_grants` (the same authoritative source the LLM rail reads for+ * `no_grant`, D4) — there is no parallel "connected" computation.+ */+export type ConnectorStatus = 'authorized' | 'requires_setup' | 'no_oauth'++/**+ * One connector row: a READ-MODEL projection that classifies instead of+ * filtering, so a `requires_setup` server NEVER disappears from the list.+ * Carries only NON-SECRET policy (`authKind`, `provider`, `grantScope`) — never+ * `auth`/`secretRef`/tokens (spec §1.4).+ */+export interface ConnectorEntry {+ name: string+ provider?: string+ authKind?: 'static' | 'oauth-user' | 'oauth-context'+ grantScope?: GrantScope+ status: ConnectorStatus+}++export interface AgentWithConnectors extends AgentDirectoryEntry {+ contextRef: string | null+ connectors: ConnectorEntry[]+}+interface ContextCR {spec?: { contextId?: string; mcpServers?: unknown[] }}@@ -59,6 +94,9 @@ interface McpServerCR {oauth?: {id?: unknowngrantScope?: unknown+ // Non-secret provider label (e.g. 'google'). Surfaced verbatim to the+ // panel; never gates oauth-ness (that is `id` via `resolveServerOAuth`).+ provider?: unknown}contextRef?: unknown}@@ -423,3 +461,174 @@ export async function resolveMcpServersForAgents(}})}++/**+ * The non-OAuth `authKind` label. Mirrors host-context-controller's+ * `deriveAuthKind` for the non-oauth branch (mini-spec 10): a static auth type+ * (`bearer`/`basic`/`apiKey`) maps to `static`; absent/`none` (implicit no-auth)+ * carries no label. Cosmetic for the panel — all of these classify `no_oauth`.+ */+function deriveNonOauthAuthKind(server: McpServerCR): 'static' | undefined {+ const authType = server.spec?.auth?.type+ return authType === 'bearer' || authType === 'basic' || authType === 'apiKey'+ ? 'static'+ : undefined+}++/**+ * Classify ONE server into the tri-state, given the authoritative grant-presence+ * set (`grantPresent`, computed by `computeGrantPresence` — the SAME flavored+ * key construction the rpc-proxy gate uses, D4). FAIL-CLOSED: a server that is+ * not an OAuth connector (not `auth.type==='oauth'`, or no usable oauth id) is+ * `no_oauth`, never `authorized`; an OAuth server absent from `grantPresent`+ * (no grant OR a grant-read error, both swallowed fail-closed upstream) is+ * `requires_setup`, never `authorized`.+ */+function classifyConnector(server: McpServerCR, grantPresent: ReadonlySet<string>): ConnectorEntry {+ const name = String(server.metadata?.name)+ // Gate on `auth.type==='oauth'` to stay aligned with `computeGrantPresence`,+ // which only ever considers (and thus admits into `grantPresent`) oauth+ // servers. A server carrying `spec.oauth` but a non-oauth auth type is NOT an+ // oauth connector on this rail.+ const resolved = server.spec?.auth?.type === 'oauth' ? resolveServerOAuth(server) : null+ if (!resolved) {+ return { name, status: 'no_oauth', authKind: deriveNonOauthAuthKind(server) }+ }+ // Provider is the non-secret panel label. Derive it directly from+ // `spec.oauth.provider`, consistent with the oauth-ness gate above — NOT via+ // `resolveServerOAuthSubject`, which additionally requires clientIdRef/+ // clientSecretRef and would drop the label for an oauth server missing them.+ const providerRaw = server.spec?.oauth?.provider+ const provider =+ typeof providerRaw === 'string' && providerRaw.length > 0 ? providerRaw : undefined+ return {+ name,+ ...(provider ? { provider } : {}),+ authKind: resolved.grantScope === 'context' ? 'oauth-context' : 'oauth-user',+ grantScope: resolved.grantScope,+ status: grantPresent.has(name) ? 'authorized' : 'requires_setup',+ }+}++/**+ * For each agent (Host), return its Host's contextRef and the CLASSIFIED+ * connector fleet of its Context (spec 11 U1). This is the panel read-model: it+ * CLASSIFIES the whole allowlist into `{authorized | requires_setup | no_oauth}`+ * rather than FILTERING the un-granted ones out (which is what the rpc-proxy+ * rail's `resolveInvocableMcpServersForContexts` does, and precisely what a+ * panel must NOT do). `filterInvocable` is left untouched.+ *+ * Authorization model is identical to `resolveMcpServersForAgents`: agent access+ * IS the gate. The caller MUST only pass `agentNames` the principal is+ * authorized to use (e.g. from `getUserAgents`). `userId` is the authenticated+ * session subject — it flows ONLY into the grant-presence key, never from a body.+ *+ * Returns valid, active entries in the same order as `agentNames`.+ */+export async function resolveConnectorsForAgents(+ gateway: K8sGateway,+ opts: {+ mcpServersNamespace: string+ hostsNamespace: string+ agentNames: readonly string[]+ userId: string+ },+ db: DbClient+): Promise<AgentWithConnectors[]> {+ const { mcpServersNamespace, hostsNamespace, agentNames, userId } = opts+ if (agentNames.length === 0) return []++ const resolvedHosts = await Promise.all(+ agentNames.map(async requestedName => {+ try {+ const host = (await gateway.getResource('hosts', requestedName, hostsNamespace)) as HostCR+ const directoryEntry = buildAgentDirectoryEntry(host, hostsNamespace)+ if (!directoryEntry || directoryEntry.name !== requestedName) return null+ return { host, directoryEntry }+ } catch (error) {+ if (isK8sResourceNotFound(error)) return null+ // A non-404 failure says nothing about whether this already-authorized+ // Host still exists — propagate rather than silently dropping the agent.+ throw error+ }+ })+ )++ let serverList: McpServerCR[] = []+ try {+ serverList = asArray<McpServerCR>(await gateway.listResource('mcpservers', mcpServersNamespace))+ } catch (err) {+ // Degrade loudly: an mcpservers-list outage yields empty connector lists,+ // distinguishable in logs from "this agent genuinely exposes no tools".+ connectorsLog.error(+ { err },+ 'mcpservers list failed; connectors served without catalog classification'+ )+ }++ const byName = new Map<string, McpServerCR>()+ for (const s of serverList) {+ const n = s.metadata?.name+ if (n) byName.set(n, s)+ }++ const visibleHosts = resolvedHosts.filter(+ (item): item is { host: HostCR; directoryEntry: AgentDirectoryEntry } => item !== null+ )++ const scopedContextIds = new Set<string>()+ for (const { host } of visibleHosts) {+ const contextRef = host.spec?.contextRef+ if (contextRef) scopedContextIds.add(contextRef)+ }++ let allowedByContext = new Map<string, Set<string>>()+ if (scopedContextIds.size > 0) {+ try {+ allowedByContext = await loadAllowedNamesByContext(+ gateway,+ mcpServersNamespace,+ scopedContextIds+ )+ } catch (err) {+ // Preserve the authorized directory DTOs with empty connector lists —+ // loudly, so a Context-read outage is distinguishable from "no tools".+ connectorsLog.error(+ { err },+ 'context allowlist load failed; connectors served with empty lists'+ )+ }+ }++ // Union of every allowlisted name across the visible agents' contexts, so the+ // authoritative grant-presence check runs ONCE per unique oauth server.+ const union = new Set<string>()+ for (const names of allowedByContext.values()) {+ for (const name of names) union.add(name)+ }+ const grantPresent = await computeGrantPresence(+ db,+ mcpServersNamespace,+ userId,+ serverList,+ union+ )++ return visibleHosts.map(({ host, directoryEntry }) => {+ const contextRef = host?.spec?.contextRef ?? null+ if (!contextRef) {+ return { ...directoryEntry, contextRef, connectors: [] }+ }+ const allowed = allowedByContext.get(contextRef)+ if (!allowed || allowed.size === 0) {+ return { ...directoryEntry, contextRef, connectors: [] }+ }+ const connectors: ConnectorEntry[] = []+ for (const name of [...allowed].sort((a, b) => a.localeCompare(b))) {+ const server = byName.get(name)+ if (!server) continue // allowlisted name with no live McpServer CR+ connectors.push(classifyConnector(server, grantPresent))+ }+ return { ...directoryEntry, contextRef, connectors }+ })+}diff --git a/control-api/test/routes.rpcAccessUsersMcpConnectors.test.ts b/control-api/test/routes.rpcAccessUsersMcpConnectors.test.tsnew file mode 100644index 000000000..a0c1105ef--- /dev/null+++ b/control-api/test/routes.rpcAccessUsersMcpConnectors.test.ts@@ -0,0 +1,88 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'+import type { K8sGateway } from '../src/k8s.js'+import { createRpcAccessUsersRouter } from '../src/routes/rpc-access/users.js'++// HTTP-level wiring test for GET /rpc/access/users/:userId/mcp-connectors+// (spec 11 U1). The security-relevant invariant: `userId` comes from the+// token-bound route param (requireRpcTokenUserMatch), the agents come from+// getUserAgents, and the resolver is called with that session userId — never a+// client-supplied value. Middleware validity has its own suite; here it is a+// pass-through so the handler contract is isolated.++const svc = vi.hoisted(() => ({+ getUserAgents: vi.fn(),+ getUserContexts: vi.fn(),+ getCurrentTeam: vi.fn(),+ getTeamAgents: vi.fn(),+}))+const resolvers = vi.hoisted(() => ({+ resolveConnectorsForAgents: vi.fn(),+ resolveInvocableMcpServersForContexts: vi.fn(),+}))++vi.mock('../src/services/directory/index.js', () => svc)+vi.mock('../src/services/access/mcpInvocable.js', () => resolvers)+vi.mock('../src/middleware/rpcAccessAuth.js', () => ({+ requireValidRpcAccessToken: () => (_req: unknown, _res: unknown, next: () => void) => next(),+ requireValidRpcAccessTokenAny: () => (_req: unknown, _res: unknown, next: () => void) => next(),+ requireRpcTokenUserMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),+}))++function buildApp() {+ const gatewayStub = {} as unknown as K8sGateway+ const app = express()+ app.use(express.json())+ app.use(+ createRpcAccessUsersRouter(gatewayStub, {+ bindingService: { bind: vi.fn() },+ })+ )+ return app+}++beforeEach(() => {+ svc.getUserAgents.mockReset()+ resolvers.resolveConnectorsForAgents.mockReset()+})++describe('GET /rpc/access/users/:userId/mcp-connectors', () => {+ it('resolves connectors for the session user agents and returns {userId, agents}', async () => {+ svc.getUserAgents.mockResolvedValue({ userId: 'user-9', agentNames: ['agent-a'] })+ const agents = [+ {+ name: 'agent-a',+ namespace: 'mcp-host',+ contextRef: 'ctx-1',+ connectors: [+ { name: 'gdrive', authKind: 'oauth-user', grantScope: 'user', status: 'requires_setup' },+ ],+ },+ ]+ resolvers.resolveConnectorsForAgents.mockResolvedValue(agents)++ const res = await request(buildApp()).get('/rpc/access/users/user-9/mcp-connectors')++ expect(res.status).toBe(200)+ expect(res.body).toEqual({ userId: 'user-9', agents })+ // getUserAgents is keyed by the route userId.+ expect(svc.getUserAgents).toHaveBeenCalledWith('user-9')+ // The resolver receives that same session userId + the derived agent names.+ const call = resolvers.resolveConnectorsForAgents.mock.calls[0]+ expect(call[1]).toMatchObject({ agentNames: ['agent-a'], userId: 'user-9' })+ })++ it('propagates resolver failure as 500', async () => {+ svc.getUserAgents.mockResolvedValue({ userId: 'user-9', agentNames: ['agent-a'] })+ resolvers.resolveConnectorsForAgents.mockRejectedValue(new Error('boom'))+ const app = buildApp()+ app.use(+ (err: unknown, _req: express.Request, res: express.Response, _n: express.NextFunction) => {+ res.status(500).json({ error: err instanceof Error ? err.message : 'x' })+ }+ )+ const res = await request(app).get('/rpc/access/users/user-9/mcp-connectors')+ expect(res.status).toBe(500)+ })+})diff --git a/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts b/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.tsnew file mode 100644index 000000000..6a142786f--- /dev/null+++ b/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts@@ -0,0 +1,162 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { randomUUID } from 'node:crypto'+import { Pool } from 'pg'+import { config } from '../src/config.js'+import type { DbClient } from '../src/db.js'+import { initDb } from '../src/db.js'+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { bootstrapSharedOAuthGrant, upsertOAuthGrant } from '../src/oauth/store.js'+import { resolveConnectorsForAgents } from '../src/services/access/mcpInvocable.js'+import { MockGateway } from './mockGateway.js'++// T1 — the connectors classifier exercised end-to-end against grant state built+// by the REAL producers (`upsertOAuthGrant` / `bootstrapSharedOAuthGrant`) and+// read by the REAL `oauthGrantExists` inside the resolver. No hand-built+// oauth_grants rows. Gated on a real Postgres, like the store integration test:+// CONTROL_API_REAL_PG_ADMIN_URL=postgres://user:pass@host:5432 npm test -- \+// test/services.access.mcpConnectors.realPostgres.integration.test.ts+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+const describeRealPostgres = adminUrl ? describe : describe.skip++function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+}++const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)+const NS = config.mcpServersNamespace+const HOSTS_NS = config.hostsNamespace+const CLIENT_PREFIX = 'client'++describeRealPostgres('resolveConnectorsForAgents tri-state (real Postgres)', () => {+ const database = `control_api_mcpconnectors_${randomUUID().replace(/-/g, '')}`+ let adminPool: Pool+ let dbPool: Pool+ let db: DbClient++ beforeAll(async () => {+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })+ await initDb({ connect: () => dbPool.connect() })+ db = { query: (text, values) => dbPool.query(text, values) }+ })++ afterAll(async () => {+ await dbPool?.end()+ if (adminPool) {+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)+ await adminPool.end()+ }+ })++ function gatewayWith(+ servers: Array<{ name: string; grantScope: 'user' | 'context'; contextRef: string }>+ ): MockGateway {+ const g = new MockGateway(NS)+ void g.createResource(+ 'hosts',+ { metadata: { name: 'agent-a', namespace: HOSTS_NS }, spec: { contextRef: 'ctx-1' } },+ HOSTS_NS+ )+ void g.createResource(+ 'contexts',+ {+ metadata: { name: 'ctx-1' },+ spec: { contextId: 'ctx-1', mcpServers: servers.map(s => s.name) },+ },+ NS+ )+ for (const s of servers) {+ void g.createResource(+ 'mcpservers',+ {+ metadata: { name: s.name },+ spec: {+ enabled: true,+ auth: { type: 'oauth' },+ transport: { url: `http://${s.name}.${NS}.svc:3000/mcp` },+ contextRef: s.contextRef,+ oauth: {+ id: `${CLIENT_PREFIX}-${s.name}`,+ provider: 'google',+ clientIdRef: { name: `${s.name}-secret`, key: 'client-id' },+ clientSecretRef: { name: `${s.name}-secret`, key: 'client-secret' },+ grantScope: s.grantScope,+ },+ },+ },+ NS+ )+ }+ return g+ }++ const statusOf = async (g: MockGateway, userId: string, serverName: string) => {+ const agents = await resolveConnectorsForAgents(+ g,+ { mcpServersNamespace: NS, hostsNamespace: HOSTS_NS, agentNames: ['agent-a'], userId },+ db+ )+ return agents[0]?.connectors.find(c => c.name === serverName)?.status+ }++ it('user-flavor: requires_setup without a grant, authorized after the caller upserts one', async () => {+ const g = gatewayWith([{ name: 'gdrive-u', grantScope: 'user', contextRef: 'ctx-1' }])+ expect(await statusOf(g, 'alice', 'gdrive-u')).toBe('requires_setup')++ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: 'gdrive-u',+ userId: 'alice',+ oauthClientId: 'client-gdrive-u',+ provider: 'google',+ accessToken: 'A',+ })+ expect(await statusOf(g, 'alice', 'gdrive-u')).toBe('authorized')+ // Another user without their own grant still sees requires_setup (never dropped).+ expect(await statusOf(g, 'bob', 'gdrive-u')).toBe('requires_setup')+ })++ it('context-flavor: authorized for EVERY member once the shared grant is bootstrapped', async () => {+ const g = gatewayWith([{ name: 'gdrive-s', grantScope: 'context', contextRef: 'ctx-1' }])+ expect(await statusOf(g, 'alice', 'gdrive-s')).toBe('requires_setup')++ await bootstrapSharedOAuthGrant(db, KEY, {+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: 'gdrive-s',+ contextId: 'ctx-1',+ oauthClientId: 'client-gdrive-s',+ bootstrappedByUserId: 'bob',+ provider: 'google',+ accessToken: 'S',+ })+ expect(await statusOf(g, 'alice', 'gdrive-s')).toBe('authorized')+ expect(await statusOf(g, 'bob', 'gdrive-s')).toBe('authorized')+ })++ it('a user grant does NOT authorize a context-flavor server (disjoint keyspaces)', async () => {+ const g = gatewayWith([{ name: 'gdrive-x', grantScope: 'context', contextRef: 'ctx-1' }])+ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: 'gdrive-x',+ userId: 'carol',+ oauthClientId: 'client-gdrive-x',+ provider: 'google',+ accessToken: 'A',+ })+ expect(await statusOf(g, 'carol', 'gdrive-x')).toBe('requires_setup')+ })+})diff --git a/control-api/test/services.access.mcpConnectors.test.ts b/control-api/test/services.access.mcpConnectors.test.tsnew file mode 100644index 000000000..b5b05e100--- /dev/null+++ b/control-api/test/services.access.mcpConnectors.test.ts@@ -0,0 +1,310 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import fc from 'fast-check'+import type { DbClient } from '../src/db.js'+import type { K8sGateway } from '../src/k8s.js'+import type { GetOAuthGrantInput } from '../src/oauth/store.js'++// The classifier reads grant PRESENCE through the real `oauthGrantExists`+// (whose SQL has its own store suites + the real-Postgres integration test+// alongside this one). Here we mock ONLY that boolean so grant presence is+// deterministic, exactly as the sibling `grantGate.test.ts` does — the fixture+// that stands for the grant store is the boolean it returns, never a hand-built+// oauth_grants row. Server/Host/Context CRs are built in the real CR shape.+const grantExists = vi.fn<(db: unknown, input: GetOAuthGrantInput) => Promise<boolean>>()+vi.mock('../src/oauth/store.js', async importActual => {+ const actual = await importActual<typeof import('../src/oauth/store.js')>()+ return {+ ...actual,+ oauthGrantExists: (db: unknown, input: GetOAuthGrantInput) => grantExists(db, input),+ }+})++const { resolveConnectorsForAgents } = await import('../src/services/access/mcpInvocable.js')++const NS = 'mcp-server'+const HOSTS_NS = 'mcp-host'+const USER = 'user-caller'+const DB: DbClient = { query: async () => ({ rows: [], rowCount: 0 }) }++type Resource = Record<string, unknown>++function gateway(resources: {+ contexts?: Resource[]+ mcpservers?: Resource[]+ hosts?: Resource[]+}): K8sGateway {+ const listResource = vi.fn(async (plural: string) => {+ if (plural === 'contexts') return resources.contexts ?? []+ if (plural === 'mcpservers') return resources.mcpservers ?? []+ if (plural === 'hosts') return resources.hosts ?? []+ return []+ })+ const getResource = vi.fn(async (plural: string, name: string) => {+ if (plural !== 'hosts') return undefined+ const found = resources.hosts?.find(+ r => (r.metadata as { name?: string } | undefined)?.name === name+ )+ if (!found) throw Object.assign(new Error('not-found'), { statusCode: 404 })+ return found+ })+ return {+ listResource,+ getResource,+ createResource: vi.fn(),+ updateResource: vi.fn(),+ deleteResource: vi.fn(),+ } as unknown as K8sGateway+}++const host = (name: string, contextRef: string | null) => ({+ metadata: { name, namespace: HOSTS_NS },+ spec: contextRef ? { contextRef } : {},+})++const ctx = (contextId: string, servers: string[]) => ({+ spec: { contextId, mcpServers: servers },+})++const oauthServer = (+ name: string,+ grantScope: 'user' | 'context',+ contextRef: string,+ provider = 'google'+) => ({+ metadata: { name },+ spec: {+ enabled: true,+ auth: { type: 'oauth' },+ transport: { url: `http://${name}.${NS}.svc:3000/mcp` },+ contextRef,+ oauth: {+ id: `${name}-client`,+ provider,+ clientIdRef: { name: `${name}-secret`, key: 'client-id' },+ clientSecretRef: { name: `${name}-secret`, key: 'client-secret' },+ grantScope,+ },+ },+})++const noneServer = (name: string) => ({+ metadata: { name },+ spec: {+ enabled: true,+ auth: { type: 'none' },+ transport: { url: `http://${name}.${NS}.svc:3000/mcp` },+ },+})++const staticServer = (name: string) => ({+ metadata: { name },+ spec: {+ enabled: true,+ auth: { type: 'bearer' },+ transport: { url: `http://${name}.${NS}.svc:3000/mcp` },+ },+})++beforeEach(() => {+ grantExists.mockReset()+})++async function connectorsFor(g: K8sGateway, agentNames: string[]) {+ const agents = await resolveConnectorsForAgents(+ g,+ { mcpServersNamespace: NS, hostsNamespace: HOSTS_NS, agentNames, userId: USER },+ DB+ )+ return agents+}++describe('resolveConnectorsForAgents — property: classify, never filter', () => {+ it('every allowlisted server appears exactly once with the correct tri-state', async () => {+ await fc.assert(+ fc.asyncProperty(+ fc.array(+ fc.record({+ kind: fc.constantFrom('oauth-user', 'oauth-context', 'none', 'static'),+ granted: fc.boolean(),+ }),+ { minLength: 0, maxLength: 8 }+ ),+ async specs => {+ const names = specs.map((_, i) => `srv-${i}`)+ const grantedNames = new Set(+ specs+ .map((s, i) => ({ s, name: names[i] }))+ .filter(({ s }) => s.granted && s.kind.startsWith('oauth'))+ .map(({ name }) => name)+ )+ grantExists.mockImplementation(async (_db, input) => grantedNames.has(input.recipeName))++ const mcpservers = specs.map((s, i) => {+ const name = names[i]+ if (s.kind === 'oauth-user') return oauthServer(name, 'user', 'ctx-1')+ if (s.kind === 'oauth-context') return oauthServer(name, 'context', 'ctx-auth')+ if (s.kind === 'static') return staticServer(name)+ return noneServer(name)+ })++ const g = gateway({+ hosts: [host('agent-a', 'ctx-1')],+ contexts: [ctx('ctx-1', names)],+ mcpservers,+ })++ const [agent] = await connectorsFor(g, ['agent-a'])+ const connectors = agent?.connectors ?? []++ // Invariant 1 — nothing is filtered out or duplicated.+ expect(connectors.map(c => c.name).sort()).toEqual([...names].sort())++ for (let i = 0; i < specs.length; i++) {+ const s = specs[i]+ const c = connectors.find(x => x.name === names[i])+ expect(c).toBeDefined()+ if (s.kind === 'none' || s.kind === 'static') {+ // Invariant 3 — non-oauth is always no_oauth, never authorized.+ expect(c!.status).toBe('no_oauth')+ expect(c!.grantScope).toBeUndefined()+ } else {+ const scope = s.kind === 'oauth-context' ? 'context' : 'user'+ expect(c!.grantScope).toBe(scope)+ expect(c!.authKind).toBe(s.kind)+ // Invariant 1 (needs-connect) + 2 (authorized) driven ONLY by grant.+ expect(c!.status).toBe(s.granted ? 'authorized' : 'requires_setup')+ }+ }+ }+ ),+ { numRuns: 200 }+ )+ })+})++describe('resolveConnectorsForAgents — concrete tri-state + fail-closed', () => {+ it('an oauth server WITHOUT a grant is requires_setup and stays in the list', async () => {+ grantExists.mockResolvedValue(false)+ const g = gateway({+ hosts: [host('agent-a', 'ctx-1')],+ contexts: [ctx('ctx-1', ['gdrive'])],+ mcpservers: [oauthServer('gdrive', 'user', 'ctx-1')],+ })+ const [agent] = await connectorsFor(g, ['agent-a'])+ expect(agent.connectors).toEqual([+ {+ name: 'gdrive',+ provider: 'google',+ authKind: 'oauth-user',+ grantScope: 'user',+ status: 'requires_setup',+ },+ ])+ })++ it('an oauth server with a provider but WITHOUT clientSecretRef still carries provider (H3)', async () => {+ // Oauth-ness is gated on `spec.oauth.id` (resolveServerOAuth), so this server+ // classifies as an oauth connector. The panel `provider` label must be derived+ // from `spec.oauth.provider` directly — NOT via resolveServerOAuthSubject, which+ // additionally demands clientIdRef/clientSecretRef and would drop the label.+ grantExists.mockResolvedValue(false)+ const g = gateway({+ hosts: [host('agent-a', 'ctx-1')],+ contexts: [ctx('ctx-1', ['gdrive'])],+ mcpservers: [+ {+ metadata: { name: 'gdrive' },+ spec: {+ enabled: true,+ auth: { type: 'oauth' },+ transport: { url: `http://gdrive.${NS}.svc:3000/mcp` },+ contextRef: 'ctx-1',+ // id + provider present; clientIdRef/clientSecretRef ABSENT.+ oauth: { id: 'gdrive-client', provider: 'google', grantScope: 'user' },+ },+ },+ ],+ })+ const [agent] = await connectorsFor(g, ['agent-a'])+ expect(agent.connectors).toEqual([+ {+ name: 'gdrive',+ provider: 'google',+ authKind: 'oauth-user',+ grantScope: 'user',+ status: 'requires_setup',+ },+ ])+ })++ it('an oauth server WITH a grant (by its flavor) is authorized', async () => {+ grantExists.mockResolvedValue(true)+ const g = gateway({+ hosts: [host('agent-a', 'ctx-1')],+ contexts: [ctx('ctx-1', ['gdrive'])],+ mcpservers: [oauthServer('gdrive', 'user', 'ctx-1')],+ })+ const [agent] = await connectorsFor(g, ['agent-a'])+ expect(agent.connectors[0]).toMatchObject({ name: 'gdrive', status: 'authorized' })+ })++ it('a context-flavor server is keyed by its OWN spec.contextRef, decoupled from userId', async () => {+ grantExists.mockResolvedValue(true)+ const g = gateway({+ hosts: [host('agent-a', 'ctx-scope')],+ contexts: [ctx('ctx-scope', ['shared'])],+ mcpservers: [oauthServer('shared', 'context', 'ctx-authoritative')],+ })+ await connectorsFor(g, ['agent-a'])+ const key = grantExists.mock.calls[0][1]+ expect(key).toMatchObject({+ grantKind: 'shared',+ ownerKind: 'mcpserver',+ recipeName: 'shared',+ contextId: 'ctx-authoritative',+ })+ expect(key).not.toHaveProperty('userId')+ })++ it('a server with no usable oauth (resolveServerOAuth=null) is no_oauth, never queried', async () => {+ const g = gateway({+ hosts: [host('agent-a', 'ctx-1')],+ contexts: [ctx('ctx-1', ['plain'])],+ mcpservers: [noneServer('plain')],+ })+ const [agent] = await connectorsFor(g, ['agent-a'])+ expect(agent.connectors[0]).toEqual({ name: 'plain', status: 'no_oauth' })+ expect(grantExists).not.toHaveBeenCalled()+ })++ it('fail-closed: a grant-read error yields requires_setup, NEVER authorized', async () => {+ grantExists.mockRejectedValue(new Error('db down'))+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ const g = gateway({+ hosts: [host('agent-a', 'ctx-1')],+ contexts: [ctx('ctx-1', ['gdrive'])],+ mcpservers: [oauthServer('gdrive', 'user', 'ctx-1')],+ })+ const [agent] = await connectorsFor(g, ['agent-a'])+ expect(agent.connectors[0].status).toBe('requires_setup')+ errSpy.mockRestore()+ })++ it('preserves agent order and returns empty connectors for an agent with no context', async () => {+ grantExists.mockResolvedValue(false)+ const g = gateway({+ hosts: [host('agent-a', 'ctx-1'), host('agent-b', null)],+ contexts: [ctx('ctx-1', ['gdrive'])],+ mcpservers: [oauthServer('gdrive', 'user', 'ctx-1')],+ })+ const agents = await connectorsFor(g, ['agent-a', 'agent-b'])+ expect(agents.map(a => a.name)).toEqual(['agent-a', 'agent-b'])+ expect(agents[1].connectors).toEqual([])+ })++ it('returns [] for no agents without touching the gateway or DB', async () => {+ const g = gateway({})+ expect(await connectorsFor(g, [])).toEqual([])+ expect(grantExists).not.toHaveBeenCalled()+ })+})diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.tsindex 37e2bd371..c3976d9b5 100644--- a/external-rest-api/src/releaseManifest.ts+++ b/external-rest-api/src/releaseManifest.ts@@ -9,7 +9,7 @@ export type ReleaseManifest = {export const releaseManifest: ReleaseManifest = {releaseId: 'v0.7.0',externalRestApiVersion: '0.1.81',- rpcProxyVersion: '0.1.66',+ rpcProxyVersion: '0.1.67',desktopVersion: '0.7.0',minimumDesktopVersion: '0.1.252',}diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex 38afc5704..2c80408a8 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.65",+ "version": "0.1.67","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.65",+ "version": "0.1.67","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex cc9f7db9c..60d3cc078 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.66",+ "version": "0.1.67","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --git a/rpc-proxy/src/__tests__/controlApiRestService.connectors.test.ts b/rpc-proxy/src/__tests__/controlApiRestService.connectors.test.tsnew file mode 100644index 000000000..007388d73--- /dev/null+++ b/rpc-proxy/src/__tests__/controlApiRestService.connectors.test.ts@@ -0,0 +1,123 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { fetchUserConnectorsFromControlApi } from '../services/controlApiRestService.js'++// spec 11 U1 — unit test for the connectors SANEADOR. Unlike the route test+// (rpc-connectors-route.test.ts) which mocks this function whole, here we stub+// only global `fetch` so `sanitizeConnector`/`sanitizeAgentConnectors` actually+// run. The invariant under test: the read-model projects the control-api payload+// down to the NON-SECRET allowlist ({name, provider?, authKind?, grantScope?,+// status}) and NEVER transports `auth`/`secretRef`/tokens, whatever the upstream+// sends. A change that let a spurious field through must turn this red.++function jsonResponse(body: unknown, ok = true, status = 200): Response {+ return { ok, status, json: async () => body } as unknown as Response+}++afterEach(() => {+ vi.unstubAllGlobals()+})++describe('fetchUserConnectorsFromControlApi — non-secret projection', () => {+ it('strips secret/spurious fields and returns only the allowlisted shape', async () => {+ const serverPayload = {+ // The server echoes a DIFFERENT userId — it must be ignored in favor of+ // the local (param) subject; the panel identity is never the server's echo.+ userId: 'server-echoed-other-user',+ agents: [+ {+ name: 'agent-a',+ contextRef: 'ctx-1',+ // Spurious agent-level fields must not survive.+ secretRef: { name: 'agent-secret', key: 'k' },+ bogus: true,+ connectors: [+ {+ name: 'gdrive',+ provider: 'google',+ authKind: 'oauth-user',+ grantScope: 'user',+ status: 'requires_setup',+ // Secret / spurious fields the saneador MUST drop:+ auth: { type: 'oauth', accessToken: 'sekret' },+ secretRef: { name: 'gdrive-secret', key: 'client-secret' },+ token: 'access-tok',+ clientSecret: 'cs',+ },+ {+ // Invalid status → the whole connector is dropped.+ name: 'bad-status',+ status: 'totally-not-valid',+ token: 'leak-me',+ },+ // A connector that is not an object → dropped.+ 'not-an-object',+ null,+ {+ // Invalid authKind/grantScope → those OPTIONALS are dropped, but+ // the connector itself stays (name + valid status).+ name: 'slack',+ provider: 'slack',+ authKind: 'nope',+ grantScope: 'galaxy',+ status: 'authorized',+ clientSecret: 'nope',+ },+ ],+ },+ ],+ }+ const fetchMock = vi.fn((..._args: Parameters<typeof fetch>) =>+ Promise.resolve(jsonResponse(serverPayload))+ )+ vi.stubGlobal('fetch', fetchMock)++ const result = await fetchUserConnectorsFromControlApi('local-user', 'rpc-tok')++ // Exact equality — no `auth`/`secretRef`/`token`/`clientSecret` may leak, and+ // `userId` is the local param, NOT the server echo.+ expect(result).toEqual({+ userId: 'local-user',+ agents: [+ {+ name: 'agent-a',+ contextRef: 'ctx-1',+ connectors: [+ {+ name: 'gdrive',+ provider: 'google',+ authKind: 'oauth-user',+ grantScope: 'user',+ status: 'requires_setup',+ },+ {+ name: 'slack',+ provider: 'slack',+ status: 'authorized',+ },+ ],+ },+ ],+ })++ // Defense in depth: the serialized output carries none of the secret tokens.+ const serialized = JSON.stringify(result)+ for (const leak of ['secretRef', 'accessToken', 'access-tok', 'clientSecret', 'cs', 'sekret']) {+ expect(serialized).not.toContain(leak)+ }++ // The lookup is keyed by the local (param) userId, url-encoded, with the+ // rpc access token forwarded — not the server-echoed identity.+ const [url] = fetchMock.mock.calls[0]+ expect(String(url)).toContain('/users/local-user/mcp-connectors')+ })++ it('throws on a non-ok control-api response', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => jsonResponse({}, false, 502))+ )+ await expect(fetchUserConnectorsFromControlApi('local-user', 'rpc-tok')).rejects.toThrow(+ /connectors lookup failed \(502\)/+ )+ })+})diff --git a/rpc-proxy/src/__tests__/rpc-connectors-route.test.ts b/rpc-proxy/src/__tests__/rpc-connectors-route.test.tsnew file mode 100644index 000000000..26f45e5aa--- /dev/null+++ b/rpc-proxy/src/__tests__/rpc-connectors-route.test.ts@@ -0,0 +1,120 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'+import { createRpcRouter } from '../routes/rpc.js'++// spec 11 U1 — the proactive connectors read-model route. It REUSES the+// `mcp:servers:list` scope, derives `userId` from the signed session subject+// (`auth.sub`), and passes the control-api payload through. These tests prove+// the scope gate, the session-derived identity, and passthrough.++const authTokenMock = vi.hoisted(() => ({ verifyRpcToken: vi.fn() }))+const controlApiMock = vi.hoisted(() => ({+ fetchUserConnectorsFromControlApi: vi.fn(),+ fetchHostConnectionFromControlApi: vi.fn(),+ requestHostWakeFromControlApi: vi.fn(),+}))+// createRpcRouter also imports the proxy service barrel; stub it so the module+// graph loads without real upstreams.+const serviceMock = vi.hoisted(() => ({+ listAllowedServersForUser: vi.fn(),+ resolveServerConnectionForUser: vi.fn(),+ resolveHostConnectionForUser: vi.fn(),+ validateRpcRequest: vi.fn(),+ forwardRpcToServer: vi.fn(),+ forwardHostMessageToHost: vi.fn(),+ forwardHostActivity: vi.fn(),+ forwardHostStatus: vi.fn(),+ forwardHostHealth: vi.fn(),+ forwardTaskResultFromHost: vi.fn(),+ forwardCancelToHost: vi.fn(),+ UpstreamHostError: class extends Error {},+}))++vi.mock('../authToken.js', () => authTokenMock)+vi.mock('../services/controlApiRestService.js', () => controlApiMock)+vi.mock('../services/mcpProxyService.js', () => serviceMock)++function claims(scopes: string[], sub = 'user-uuid-123') {+ return {+ sub,+ typ: 'user' as const,+ accessScope: 'team' as const,+ teamId: 'team-1',+ scopes,+ hostRefs: ['agent-a'],+ jti: 'j1',+ iat: 1,+ exp: 9999999999,+ }+}++function makeApp() {+ const app = express()+ app.use(express.json())+ app.use(createRpcRouter())+ app.use(+ (err: unknown, _req: express.Request, res: express.Response, _n: express.NextFunction) => {+ res.status(500).json({ error: err instanceof Error ? err.message : 'Internal error' })+ }+ )+ return app+}++beforeEach(() => {+ authTokenMock.verifyRpcToken.mockReset()+ controlApiMock.fetchUserConnectorsFromControlApi.mockReset()+})+afterEach(() => vi.clearAllMocks())++describe('GET /rpc/connectors', () => {+ it('401 without a bearer token', async () => {+ const res = await request(makeApp()).get('/rpc/connectors')+ expect(res.status).toBe(401)+ expect(controlApiMock.fetchUserConnectorsFromControlApi).not.toHaveBeenCalled()+ })++ it('403 when the token lacks mcp:servers:list', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['mcp:server:invoke']))+ const res = await request(makeApp()).get('/rpc/connectors').set('authorization', 'Bearer tok')+ expect(res.status).toBe(403)+ expect(controlApiMock.fetchUserConnectorsFromControlApi).not.toHaveBeenCalled()+ })++ it('derives userId from the session subject and passes the payload through', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['mcp:servers:list'], 'user-abc'))+ const payload = {+ userId: 'user-abc',+ agents: [+ {+ name: 'agent-a',+ contextRef: 'ctx-1',+ connectors: [+ {+ name: 'gdrive',+ provider: 'google',+ authKind: 'oauth-user',+ grantScope: 'user',+ status: 'requires_setup',+ },+ ],+ },+ ],+ }+ controlApiMock.fetchUserConnectorsFromControlApi.mockResolvedValue(payload)++ const res = await request(makeApp()).get('/rpc/connectors').set('authorization', 'Bearer tok')++ expect(res.status).toBe(200)+ expect(res.body).toEqual(payload)+ // userId is the signed subject — NOT any client-supplied value.+ expect(controlApiMock.fetchUserConnectorsFromControlApi).toHaveBeenCalledWith('user-abc', 'tok')+ })++ it('surfaces a control-api failure as 500 (route next(error))', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['mcp:servers:list']))+ controlApiMock.fetchUserConnectorsFromControlApi.mockRejectedValue(new Error('boom'))+ const res = await request(makeApp()).get('/rpc/connectors').set('authorization', 'Bearer tok')+ expect(res.status).toBe(500)+ })+})diff --git a/rpc-proxy/src/routes/rpc.ts b/rpc-proxy/src/routes/rpc.tsindex 91a7b9363..0846a1e81 100644--- a/rpc-proxy/src/routes/rpc.ts+++ b/rpc-proxy/src/routes/rpc.ts@@ -11,6 +11,7 @@ import {import { rpcInvocationContext } from '../rpcAccessContext.js'import {type HostWakeApiResponse,+ fetchUserConnectorsFromControlApi,requestHostWakeFromControlApi,} from '../services/controlApiRestService.js'import {@@ -222,6 +223,27 @@ export function createRpcRouter(): Router {})+ // Proactive connectors panel read-model (spec 11 U1): per-agent classified+ // fleet (`authorized`/`requires_setup`/`no_oauth`). Read of the same catalog+ // rail as `/rpc/servers`, so it REUSES the `mcp:servers:list` scope (no new+ // scope minted). `userId` is the signed session subject (`auth.sub`), never a+ // body/query param.+ router.get(+ '/rpc/connectors',+ requireRpcAuth,+ requireScope('mcp:servers:list'),+ async (req: AuthedRequest, res, next) => {+ try {+ const auth = req.auth!+ const rpcAccessToken = extractAuthToken(req)+ const result = await fetchUserConnectorsFromControlApi(auth.sub, rpcAccessToken)+ res.status(200).json(result)+ } catch (error) {+ next(error)+ }+ }+ )+router.post('/rpc/:serverName',requireRpcAuth,diff --git a/rpc-proxy/src/services/controlApiRestService.ts b/rpc-proxy/src/services/controlApiRestService.tsindex a361e412e..ca30150e6 100644--- a/rpc-proxy/src/services/controlApiRestService.ts+++ b/rpc-proxy/src/services/controlApiRestService.ts@@ -83,6 +83,96 @@ export async function fetchUserAllowedServersFromControlApi(}}+export type UserConnector = {+ name: string+ provider?: string+ authKind?: 'static' | 'oauth-user' | 'oauth-context'+ grantScope?: 'user' | 'context'+ status: 'authorized' | 'requires_setup' | 'no_oauth'+}++export type UserAgentConnectors = {+ name: string+ contextRef: string | null+ connectors: UserConnector[]+}++export type UserConnectorsResponse = {+ userId: string+ agents: UserAgentConnectors[]+}++const CONNECTOR_STATUSES = new Set(['authorized', 'requires_setup', 'no_oauth'])+const CONNECTOR_AUTH_KINDS = new Set(['static', 'oauth-user', 'oauth-context'])+const CONNECTOR_GRANT_SCOPES = new Set(['user', 'context'])++function sanitizeConnector(raw: unknown): UserConnector | null {+ if (!raw || typeof raw !== 'object') return null+ const entry = raw as Record<string, unknown>+ const name = typeof entry.name === 'string' ? entry.name.trim() : ''+ const status = entry.status+ if (!name || typeof status !== 'string' || !CONNECTOR_STATUSES.has(status)) return null+ const connector: UserConnector = { name, status: status as UserConnector['status'] }+ if (typeof entry.provider === 'string' && entry.provider.trim()) {+ connector.provider = entry.provider.trim()+ }+ if (typeof entry.authKind === 'string' && CONNECTOR_AUTH_KINDS.has(entry.authKind)) {+ connector.authKind = entry.authKind as UserConnector['authKind']+ }+ if (typeof entry.grantScope === 'string' && CONNECTOR_GRANT_SCOPES.has(entry.grantScope)) {+ connector.grantScope = entry.grantScope as UserConnector['grantScope']+ }+ return connector+}++function sanitizeAgentConnectors(raw: unknown): UserAgentConnectors | null {+ if (!raw || typeof raw !== 'object') return null+ const agent = raw as Record<string, unknown>+ const name = typeof agent.name === 'string' ? agent.name.trim() : ''+ if (!name) return null+ const contextRef =+ typeof agent.contextRef === 'string' && agent.contextRef.trim() ? agent.contextRef.trim() : null+ const connectors = Array.isArray(agent.connectors)+ ? agent.connectors+ .map(sanitizeConnector)+ .filter((entry): entry is UserConnector => entry !== null)+ : []+ return { name, contextRef, connectors }+}++/**+ * Fetch the proactive connectors read-model for a user (spec 11 U1). Projects+ * the control-api payload down to the declared, NON-SECRET shape and drops any+ * unexpected field — the inventory never transports `auth`/`secretRef`/tokens.+ * Deliberately UNCACHED: the tri-state must reflect a just-completed+ * connect/disconnect, unlike the server catalog (`fetchUserAllowedServers…`).+ */+export async function fetchUserConnectorsFromControlApi(+ userId: string,+ rpcAccessToken: string+): Promise<UserConnectorsResponse> {+ const response = await fetch(+ `${controlApiBaseUrl()}/rpc/access/users/${encodeURIComponent(userId)}/mcp-connectors`,+ {+ method: 'GET',+ headers: controlApiHeaders(rpcAccessToken),+ }+ )++ if (!response.ok) {+ throw new Error(`Control API MCP connectors lookup failed (${response.status})`)+ }++ const parsed = (await response.json()) as Partial<UserConnectorsResponse>+ const agents = Array.isArray(parsed.agents)+ ? parsed.agents+ .map(sanitizeAgentConnectors)+ .filter((agent): agent is UserAgentConnectors => agent !== null)+ : []++ return { userId, agents }+}+export async function fetchHostConnectionFromControlApi(userId: string,hostRef: string,