Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(control-api): r1-m1 let agent-reached contexts enable per-user connect

Diego Zacarias963593d32cea
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 440d29703..6b4c1ff56 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.742",
+ "version": "0.1.743",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.742",
+ "version": "0.1.743",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index 0036854a4..f6c177d2c 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.742",
+ "version": "0.1.743",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts b/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
index ab83d1d2b..ca4dcd807 100644
--- a/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
+++ b/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
@@ -20,7 +20,7 @@ import { signOAuthState } from '../state.js'
* happy paths (context member + per-user) still exchange and persist.
*
* The per-user flavor has its own pre-exchange guard: some Context the user
- * belongs to must still enable the server (`userServerAccessReader`), so a user
+ * reaches must still enable the server (`userServerAccessReader`), so a user
* who lost that access between mint and callback cannot finish creating a grant.
*/
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index 6b4f08f81..429437331 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -293,8 +293,9 @@ export interface CallbackDeps {
*/
userContextsReader?: (userId: string) => Promise<{ contextIds: string[] }>
/**
- * Whether some Context the user belongs to still enables the server through
- * its `spec.mcpServers` allowlist. Required ONLY for the per-user mcp path
+ * Whether some Context the user reaches (directly, or through an agent
+ * assigned to them) still enables the server through its `spec.mcpServers`
+ * allowlist. Required ONLY for the per-user mcp path
* (`grantScope='user'`), re-checked before the code exchange so a user who
* lost that access after the authorize URL was minted cannot finish creating
* a grant. The route wires the same rule the authorize-URL mint applies. When
@@ -393,10 +394,13 @@ export type CallbackResult =
*/
| { kind: 'server_missing_context' }
/**
- * mcp subject with `grantScope='context'` where the consenting (signed) user
- * is NOT a member of the server's Context. A shared grant lends a team-wide
- * credential, so a non-member must not be able to bootstrap it. Fail closed →
- * 403, no persist.
+ * mcp subject whose consenting (signed) user lacks access, by flavor:
+ * - `grantScope='context'`: not a member of the server's `spec.contextRef`
+ * (a shared grant lends a Context-wide credential);
+ * - `grantScope='user'`: no Context the user reaches (directly or through an
+ * assigned agent) still lists the server in its `spec.mcpServers` allowlist.
+ * Also returned when the reader for that flavor is not wired. Fail closed →
+ * 403, no code exchange, no persist.
*/
| { kind: 'context_membership_denied' }
/**
@@ -555,9 +559,9 @@ export async function handleOAuthCallback(
* recovered fresh from the CR (authoritative), NOT from the state or any body.
*
* Access is re-checked BEFORE the code exchange, by flavor:
- * - `grantScope='user'` → some Context the signed user belongs to must still
- * allowlist the server (`userServerAccessReader`); `spec.contextRef` is not
- * consulted.
+ * - `grantScope='user'` → some Context the signed user reaches (directly or
+ * through an assigned agent) must still allowlist the server
+ * (`userServerAccessReader`); `spec.contextRef` is not consulted.
* - `grantScope='context'` → the signed user must be a member of the server's
* `spec.contextRef` (`userContextsReader`).
*
@@ -655,8 +659,9 @@ async function handleMcpOAuthCallback(
contextRef = subject.contextRef
} else {
// Per-user identity — the grant serves every Context that enables the
- // server, so access is "some Context of the user still allowlists it", the
- // same rule the mint applied. Fail closed when the reader is unwired.
+ // server, so access is "some Context the user reaches still allowlists
+ // it", the same rule the mint applied. Fail closed when the reader is
+ // unwired.
if (!deps.userServerAccessReader) return { kind: 'context_membership_denied' }
const enabled = await deps.userServerAccessReader(claims.userId, claims.mcpServerName)
if (!enabled) return { kind: 'context_membership_denied' }
diff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.ts
index 7f70aa660..652ff9b24 100644
--- a/control-api/src/routes/external/oauthCallback.ts
+++ b/control-api/src/routes/external/oauthCallback.ts
@@ -129,12 +129,14 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {
// Shared-identity mcp bootstrap requires the consenting user to be a
// member of the server's Context (defence in depth).
userContextsReader: getUserContexts,
- // Per-user mcp consent requires some Context of the user to still
- // allowlist the server — the same rule the authorize-URL mint applies.
+ // Per-user mcp consent requires some Context the user reaches
+ // (directly or through an assigned agent) to still allowlist the
+ // server — the same rule the authorize-URL mint applies.
userServerAccessReader: (userId, mcpServerName) =>
userHasContextEnablingMcpServer({
gateway,
mcpServersNamespace: config.mcpServersNamespace,
+ hostsNamespace: config.hostsNamespace,
userId,
mcpServerName,
}),
diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.ts
index 82c7acaea..6540fee06 100644
--- a/control-api/src/routes/internal/oauth.ts
+++ b/control-api/src/routes/internal/oauth.ts
@@ -307,11 +307,13 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
// and the consenting user must be a member of it, because the
// resulting shared grant is planted for that whole Context.
// - `user`: the grant is keyed by (user, server) and serves every
- // Context that enables the server, so the user must belong to at
- // least one Context whose `spec.mcpServers` allowlist names it — the
- // same rule invoke and the catalog apply. `spec.contextRef` and the
- // body contextId play no part: gating on the former rejected users
- // whose Context enables a server another Context declares.
+ // Context that enables the server, so the user must reach at least
+ // one Context whose `spec.mcpServers` allowlist names it — directly
+ // (`user_contexts`) or through an assigned agent's Host — which is
+ // every Context the flat catalog or the connectors panel resolves
+ // for them. `spec.contextRef` and the body contextId play no part:
+ // gating on the former rejected users whose Context enables a
+ // server another Context declares.
// Either way, connect shares the `mcp:server:invoke` scope with invoke,
// so without this gate any user could start consent for (and enumerate)
// integrations none of their Contexts expose.
@@ -335,6 +337,7 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
const enabled = await userHasContextEnablingMcpServer({
gateway,
mcpServersNamespace: config.mcpServersNamespace,
+ hostsNamespace: config.hostsNamespace,
userId,
mcpServerName,
})
diff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.ts
index 7b26ed14a..5096e421a 100644
--- a/control-api/src/services/access/mcpInvocable.ts
+++ b/control-api/src/services/access/mcpInvocable.ts
@@ -37,6 +37,7 @@ import {
type AgentDirectoryEntry,
buildAgentDirectoryEntry,
} from '../directory/accessReconciliation.js'
+import { getUserAgents } from '../directory/agentAccess.js'
import { getUserContexts } from '../directory/contextAccess.js'
const log = rootLogger.child({ module: 'mcpInvocable' })
@@ -148,6 +149,42 @@ function asArray<T>(value: unknown): T[] {
return Array.isArray(value) ? (value as T[]) : []
}
+interface VisibleAgentHost {
+ host: HostCR
+ directoryEntry: AgentDirectoryEntry
+}
+
+/**
+ * The Hosts behind already-authorized agent names that the agent directory
+ * would show (same order as `agentNames`): disabled, deleting, foreign-namespace
+ * and sentinel Hosts, and Hosts whose directory name differs from the requested
+ * one, are dropped. A 404 drops the agent; any other read failure propagates,
+ * because it says nothing about whether the Host still exists.
+ *
+ * Shared by the per-agent catalogs and the per-user consent gate so that every
+ * Host a catalog shows is a Host the gate counts.
+ */
+async function loadVisibleAgentHosts(
+ gateway: Pick<K8sGateway, 'getResource'>,
+ hostsNamespace: string,
+ agentNames: readonly string[]
+): Promise<VisibleAgentHost[]> {
+ const resolved = await Promise.all(
+ agentNames.map(async (requestedName): Promise<VisibleAgentHost | null> => {
+ 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
+ throw error
+ }
+ })
+ )
+ return resolved.filter((item): item is VisibleAgentHost => item !== null)
+}
+
/**
* Resolve the set of allowed server names per context.
* When `scopedContextIds` is provided, contexts NOT in scope are dropped.
@@ -199,32 +236,53 @@ export async function allowedMcpServerNamesForContexts(
}
/**
- * Whether some Context the user belongs to enables `mcpServerName` through its
- * `spec.mcpServers` allowlist. This is the access rule for consenting to (and
- * completing consent for) a per-user OAuth server: the grant is keyed by
+ * Whether some Context the user reaches still enables `mcpServerName` through
+ * its `spec.mcpServers` allowlist. This is the access rule for consenting to
+ * (and completing consent for) a per-user OAuth server: the grant is keyed by
* (user, server) and serves every Context that enables the server, so access
- * follows the same allowlist rule invoke and the catalog apply, never the
- * server's own `spec.contextRef`.
+ * follows the allowlists, never the server's own `spec.contextRef`.
+ *
+ * A Context is reached directly (`getUserContexts`, active users) or through
+ * an agent assigned to the user (`getUserAgents` → a Host the agent directory
+ * shows → its `spec.contextRef`). Those are the two sources the flat
+ * `/mcp-servers` catalog and the per-agent connectors panel resolve from, so
+ * anything either offers the user can be connected. Team membership
+ * (`team_contexts`, `team_agents`) does not count: neither catalog reads it
+ * for a user, and this path has no trusted team id.
*
- * Membership is `getUserContexts` (direct `user_contexts` only, active users)
- * so this gate stays aligned with the catalog, which reads the same source;
- * counting team membership here alone would let a user connect servers the
- * catalog never shows them. Deliberately ignores grant presence: the consent
- * flow exists precisely for servers that have no grant yet.
+ * Agents are read only when the direct Contexts do not enable the server, so
+ * a Host read failure cannot break consent that direct membership already
+ * allows; when it is needed, a failure propagates rather than answering
+ * false. Deliberately ignores grant presence: the consent flow exists
+ * precisely for servers that have no grant yet.
*/
export async function userHasContextEnablingMcpServer(opts: {
- gateway: Pick<K8sGateway, 'listResource'>
+ gateway: Pick<K8sGateway, 'listResource' | 'getResource'>
mcpServersNamespace: string
+ hostsNamespace: string
userId: string
mcpServerName: string
}): Promise<boolean> {
const { contextIds } = await getUserContexts(opts.userId)
- const allowed = await allowedMcpServerNamesForContexts(
+ const direct = await allowedMcpServerNamesForContexts(
opts.gateway,
opts.mcpServersNamespace,
contextIds
)
- return allowed.has(opts.mcpServerName)
+ if (direct.has(opts.mcpServerName)) return true
+
+ const { agentNames } = await getUserAgents(opts.userId)
+ const hosts = await loadVisibleAgentHosts(opts.gateway, opts.hostsNamespace, agentNames)
+ const agentContextIds: string[] = []
+ for (const { host } of hosts) {
+ const contextRef = host.spec?.contextRef
+ if (contextRef) agentContextIds.push(contextRef)
+ }
+ if (agentContextIds.length === 0) return false
+ const reached = await allowedMcpServerNamesForContexts(opts.gateway, opts.mcpServersNamespace, [
+ ...new Set([...contextIds, ...agentContextIds]),
+ ])
+ return reached.has(opts.mcpServerName)
}
/**
@@ -418,22 +476,9 @@ export async function resolveMcpServersForAgents(
const { mcpServersNamespace, hostsNamespace, agentNames } = 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 it so callers can preserve their
- // names-only compatibility field instead of silently revoking access.
- throw error
- }
- })
- )
+ // A non-404 Host read failure propagates so callers can preserve their
+ // names-only compatibility field instead of silently revoking access.
+ const visibleHosts = await loadVisibleAgentHosts(gateway, hostsNamespace, agentNames)
let serverList: McpServerCR[] = []
try {
@@ -448,15 +493,6 @@ export async function resolveMcpServersForAgents(
)
}
- 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
@@ -592,21 +628,7 @@ export async function resolveConnectorsForAgents(
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
- }
- })
- )
+ const visibleHosts = await loadVisibleAgentHosts(gateway, hostsNamespace, agentNames)
let serverList: McpServerCR[] = []
try {
@@ -626,10 +648,6 @@ export async function resolveConnectorsForAgents(
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
diff --git a/control-api/test/fixtures/contextAllowlist.ts b/control-api/test/fixtures/contextAllowlist.ts
index 42a20f0e4..c4c635e63 100644
--- a/control-api/test/fixtures/contextAllowlist.ts
+++ b/control-api/test/fixtures/contextAllowlist.ts
@@ -24,6 +24,27 @@ export async function seedAllowlistedContext(
}
}
+/**
+ * Seed an agent's Host CR in the hosts namespace with the CRD-required fields
+ * (`host`, `contextRef`, an LLM `secretRef`). Hand-written: no exported
+ * producer builds Host CRs.
+ */
+export async function seedAgentHost(
+ gateway: MockGateway,
+ name: string,
+ contextRef: string,
+ spec: Record<string, unknown> = {}
+): Promise<void> {
+ await gateway.createResource(
+ 'hosts',
+ {
+ metadata: { name },
+ spec: { host: name, contextRef, secretRef: `${name}-llm`, ...spec },
+ },
+ config.hostsNamespace
+ )
+}
+
/**
* Who belongs to what, keyed by user id. `contexts` answers the
* `getUserContexts` read (`FROM user_contexts`), `agents` the `getUserAgents`
diff --git a/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts b/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts
index 86c9fd780..9bab267b1 100644
--- a/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts
+++ b/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts
@@ -4,7 +4,7 @@ import { createApp } from '../src/app.js'
import { config } from '../src/config.js'
import { verifyOAuthStateSignature } from '../src/oauth/state.js'
import { checkAndIncrement } from '../src/services/rateLimiterService.js'
-import { membership, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
+import { membership, seedAgentHost, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
import { MockGateway } from './mockGateway.js'
/**
@@ -15,9 +15,10 @@ import { MockGateway } from './mockGateway.js'
* The `oauthClientId` + grantScope come from the McpServer CR, never the body.
*
* Membership gate by flavor:
- * - `user` → the user must belong (user_contexts) to at least one Context
- * whose `spec.mcpServers` allowlist names the server; `spec.contextRef` is
- * irrelevant and the body `contextId` is ignored.
+ * - `user` → the user must reach at least one Context whose
+ * `spec.mcpServers` allowlist names the server — directly (user_contexts)
+ * or through an assigned agent's Host (user_agents → Host.contextRef);
+ * `spec.contextRef` is irrelevant and the body `contextId` is ignored.
* - `context` → membership in the server's `spec.contextRef` (unchanged).
*/
@@ -243,9 +244,10 @@ describe('POST /api/v1/internal/mcp-oauth/authorize-url (U5)', () => {
//
// These replace the earlier "member of spec.contextRef" expectations: a
// `user`-scope grant is keyed by (user, server) and serves every Context that
- // enables the server, so the gate is the same rule invoke uses — the user
- // belongs to at least one Context whose allowlist names the server. The
- // server's own `spec.contextRef` no longer decides anything for this flavor.
+ // enables the server, so the gate is "the user reaches at least one Context
+ // whose allowlist names the server", directly or through an assigned agent.
+ // The server's own `spec.contextRef` no longer decides anything for this
+ // flavor.
// Reproduces the reported 403: the server's contextRef is a Context the user
// is NOT in, but a Context the user IS in allowlists the server.
@@ -309,6 +311,26 @@ describe('POST /api/v1/internal/mcp-oauth/authorize-url (U5)', () => {
expect(res.body.authorizeUrl).toContain('https://accounts.google.com/')
})
+ // The server's own Context dropped it; the user still reaches a Context that
+ // allowlists it through an assigned agent, which is where the connectors
+ // panel offers it.
+ it('user flavor: reached only through an assigned agent whose Context allowlists it mints OK', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-owner' })
+ await seedAllowlistedContext(gateway, 'ctx-owner', [])
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c')
+ membership(mockPoolQuery, {
+ contexts: { 'user-7': ['ctx-owner'] },
+ agents: { 'user-7': ['host-c'] },
+ })
+ const res = await post(app)
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+ .send({ mcpServerName: 'gdrive', userId: 'user-7' })
+ expect(res.status).toBe(200)
+ expect(res.body.authorizeUrl).toContain('https://accounts.google.com/')
+ })
+
it('user flavor: the body contextId is ignored (neither required nor cross-checked)', async () => {
seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-owner' })
await seedAllowlistedContext(gateway, 'ctx-business', ['gdrive'])
diff --git a/control-api/test/routes.oauthCallback.userAccessGate.test.ts b/control-api/test/routes.oauthCallback.userAccessGate.test.ts
index 440f5eff3..ac6220921 100644
--- a/control-api/test/routes.oauthCallback.userAccessGate.test.ts
+++ b/control-api/test/routes.oauthCallback.userAccessGate.test.ts
@@ -4,21 +4,23 @@ import request from 'supertest'
import { config } from '../src/config.js'
import { signOAuthState } from '../src/oauth/state.js'
import { createOAuthCallbackRouter } from '../src/routes/external/oauthCallback.js'
-import { membership, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
+import { editContextAllowlist } from '../src/services/contextAllowlist.js'
+import { membership, seedAgentHost, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
import { MockGateway } from './mockGateway.js'
/**
* The per-user (`grantScope: user`) consent callback re-checks access through the
* PRODUCTION wiring of `userServerAccessReader` in `createOAuthCallbackRouter`:
- * some Context the signed user belongs to must allowlist the server. The server's
- * own `spec.contextRef` is deliberately a Context the user is NOT a member of, so
- * only the allowlist rule can decide the outcome.
+ * some Context the signed user reaches — directly or through an assigned
+ * agent's Host — must allowlist the server. The server's own `spec.contextRef`
+ * is deliberately a Context the user is NOT a member of, so only the allowlist
+ * rule can decide the outcome.
*
* Contexts are written through the real allowlist writer, membership is the
- * `user_contexts` read on the mocked pool (the same stand-in the sibling suites
- * use), and the state is signed by the real signer. The provider token endpoint
- * is the only network edge: `globalThis.fetch`, which the route wires as its
- * baked-lane transport.
+ * `user_contexts` / `user_agents` reads on the mocked pool (the same stand-in
+ * the sibling suites use), Host CRs are hand-written, and the state is signed
+ * by the real signer. The provider token endpoint is the only network edge:
+ * `globalThis.fetch`, which the route wires as its baked-lane transport.
*/
const mockPoolQuery = vi.fn()
@@ -147,4 +149,29 @@ describe('GET /api/v1/oauth-callback/:oauthClientId — per-user access re-check
expect(sql).toContain('INSERT INTO oauth_grants')
expect(params.slice(0, 5)).toEqual(['mcpserver', MCP_NS, SERVER, USER_ID, OAUTH_CLIENT_ID])
})
+
+ it('200 when the user reaches an allowlisting Context only through an assigned agent; exchanges and writes the user grant', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-c', [SERVER])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c')
+ membership(mockPoolQuery, {
+ contexts: { [USER_ID]: [OWNER_CONTEXT] },
+ agents: { [USER_ID]: ['host-c'] },
+ })
+ // The owner Context no longer allowlists the server.
+ await editContextAllowlist(
+ gateway as never,
+ { name: OWNER_CONTEXT, namespace: MCP_NS },
+ servers => servers.filter(name => name !== SERVER)
+ )
+
+ const res = await callback()
+
+ expect(res.status).toBe(200)
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
+ const writes = grantWrites()
+ expect(writes).toHaveLength(1)
+ const [sql, params] = writes[0] as [string, unknown[]]
+ expect(sql).toContain('INSERT INTO oauth_grants')
+ expect(params.slice(0, 5)).toEqual(['mcpserver', MCP_NS, SERVER, USER_ID, OAUTH_CLIENT_ID])
+ })
})
diff --git a/control-api/test/services.access.userMcpServerAccess.test.ts b/control-api/test/services.access.userMcpServerAccess.test.ts
index 2104eae69..51968cf71 100644
--- a/control-api/test/services.access.userMcpServerAccess.test.ts
+++ b/control-api/test/services.access.userMcpServerAccess.test.ts
@@ -3,18 +3,23 @@ import fc from 'fast-check'
import { config } from '../src/config.js'
import {
allowedMcpServerNamesForContexts,
+ resolveConnectorsForAgents,
+ resolveInvocableMcpServersForContexts,
userHasContextEnablingMcpServer,
} from '../src/services/access/mcpInvocable.js'
-import { membership, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
+import { membership, seedAgentHost, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
import { MockGateway } from './mockGateway.js'
/**
* The access rule shared by the per-user OAuth connect gate and its callback:
- * a user may connect a server iff they belong (user_contexts) to at least one
- * Context whose `spec.mcpServers` allowlist names it — the same rule invoke and
- * the catalog apply. Membership comes from `getUserContexts` (mocked at the
- * pool, so the real SQL runs through it); allowlists are written through the
- * real allowlist writer onto the gateway fake.
+ * a user may connect a server iff some Context they reach allowlists it in
+ * `spec.mcpServers` — directly (user_contexts) or through an assigned agent
+ * (user_agents → a Host the agent directory shows → its contextRef). Those are
+ * the sources of the flat `/mcp-servers` catalog and the connectors panel; team
+ * membership does not count. Membership is answered at the pool (the real
+ * readers' SQL runs through it); allowlists are written through the real
+ * allowlist writer onto the gateway fake; Host CRs are hand-written (no
+ * exported producer).
*/
const mockPoolQuery = vi.fn()
@@ -23,11 +28,13 @@ vi.mock('../src/db.js', () => ({
}))
const MCP_NS = config.mcpServersNamespace
+const HOSTS_NS = config.hostsNamespace
function check(gateway: MockGateway, userId: string, mcpServerName: string): Promise<boolean> {
return userHasContextEnablingMcpServer({
gateway: gateway as never,
mcpServersNamespace: MCP_NS,
+ hostsNamespace: HOSTS_NS,
userId,
mcpServerName,
})
@@ -76,13 +83,15 @@ describe('userHasContextEnablingMcpServer', () => {
expect(listSpy).not.toHaveBeenCalled()
})
- it('membership is read from user_contexts only (team membership does not count)', async () => {
+ it('team membership does not count: neither team_contexts nor team_agents is read', async () => {
await seedAllowlistedContext(gateway, 'ctx-team', ['notion'])
- membership(mockPoolQuery, { contexts: { 'user-1': [] } })
+ await seedAgentHost(gateway, 'host-team', 'ctx-team')
+ membership(mockPoolQuery, { contexts: { 'user-1': [] }, agents: { 'user-1': [] } })
expect(await check(gateway, 'user-1', 'notion')).toBe(false)
const sqls = mockPoolQuery.mock.calls.map(([sql]) => String(sql))
expect(sqls.some(sql => sql.includes('FROM user_contexts'))).toBe(true)
- expect(sqls.some(sql => sql.includes('team_contexts'))).toBe(false)
+ expect(sqls.some(sql => sql.includes('FROM user_agents'))).toBe(true)
+ expect(sqls.some(sql => /team_contexts|team_agents/.test(sql))).toBe(false)
})
it('propagates a Context list failure instead of answering false', async () => {
@@ -92,6 +101,218 @@ describe('userHasContextEnablingMcpServer', () => {
})
})
+describe('userHasContextEnablingMcpServer — Contexts reached through assigned agents', () => {
+ let gateway: MockGateway
+
+ beforeEach(() => {
+ gateway = new MockGateway(MCP_NS)
+ mockPoolQuery.mockReset()
+ })
+
+ it('S1: no direct Contexts, an assigned agent whose Context allowlists the server → true', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c')
+ membership(mockPoolQuery, { agents: { 'user-1': ['host-c'] } })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(true)
+ })
+
+ it('S2: the direct Context dropped the server, an assigned agent Context still allowlists it → true', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-owner', [])
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c')
+ membership(mockPoolQuery, {
+ contexts: { 'user-1': ['ctx-owner'] },
+ agents: { 'user-1': ['host-c'] },
+ })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(true)
+ })
+
+ it('an agent assigned to another user does not count', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c')
+ membership(mockPoolQuery, { agents: { 'user-2': ['host-c'] } })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(false)
+ })
+
+ it('a disabled Host does not count', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c', { enabled: false })
+ membership(mockPoolQuery, { agents: { 'user-1': ['host-c'] } })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(false)
+ })
+
+ it('the legacy fleet-wide sentinel Host does not count', async () => {
+ expect(HOSTS_NS).toBe('mcp-host')
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'standalone', 'ctx-c')
+ membership(mockPoolQuery, { agents: { 'user-1': ['standalone'] } })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(false)
+ })
+
+ it('a deleting Host does not count', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c')
+ const real = gateway.getResource.bind(gateway)
+ vi.spyOn(gateway, 'getResource').mockImplementation(async (plural, name, ns) => {
+ const row = (await real(plural, name, ns)) as { metadata: Record<string, unknown> }
+ return plural === 'hosts'
+ ? { ...row, metadata: { ...row.metadata, deletionTimestamp: '2026-10-12T00:00:00Z' } }
+ : row
+ })
+ membership(mockPoolQuery, { agents: { 'user-1': ['host-c'] } })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(false)
+ })
+
+ it('a Host whose directory name differs from the assigned agent name does not count', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'host-other', 'ctx-c')
+ const real = gateway.getResource.bind(gateway)
+ vi.spyOn(gateway, 'getResource').mockImplementation(async (plural, name, ns) =>
+ plural === 'hosts' ? real(plural, 'host-other', ns) : real(plural, name, ns)
+ )
+ membership(mockPoolQuery, { agents: { 'user-1': ['host-c'] } })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(false)
+ })
+
+ it('a Host in another namespace does not count', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await gateway.createResource(
+ 'hosts',
+ {
+ metadata: { name: 'host-c' },
+ spec: { host: 'host-c', contextRef: 'ctx-c', secretRef: 'x' },
+ },
+ 'some-other-namespace'
+ )
+ membership(mockPoolQuery, { agents: { 'user-1': ['host-c'] } })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(false)
+ })
+
+ it('a missing (404) Host is ignored, the other agents still count', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c')
+ membership(mockPoolQuery, { agents: { 'user-1': ['host-gone', 'host-c'] } })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(true)
+ })
+
+ it('a non-404 Host read failure propagates when the direct Contexts do not enable the server', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-c', ['gdrive'])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c')
+ vi.spyOn(gateway, 'getResource').mockRejectedValue(
+ Object.assign(new Error('apiserver unavailable'), { statusCode: 503 })
+ )
+ membership(mockPoolQuery, { agents: { 'user-1': ['host-c'] } })
+ await expect(check(gateway, 'user-1', 'gdrive')).rejects.toThrow('apiserver unavailable')
+ })
+
+ it('a Host read failure does not matter when a direct Context already enables the server', async () => {
+ await seedAllowlistedContext(gateway, 'ctx-business', ['gdrive'])
+ await seedAgentHost(gateway, 'host-c', 'ctx-c')
+ const hostRead = vi
+ .spyOn(gateway, 'getResource')
+ .mockRejectedValue(Object.assign(new Error('apiserver unavailable'), { statusCode: 503 }))
+ membership(mockPoolQuery, {
+ contexts: { 'user-1': ['ctx-business'] },
+ agents: { 'user-1': ['host-c'] },
+ })
+ expect(await check(gateway, 'user-1', 'gdrive')).toBe(true)
+ expect(hostRead).not.toHaveBeenCalled()
+ })
+})
+
+/**
+ * What the user is offered must be connectable: every server the connectors
+ * panel classifies as `oauth-user` for the user's agents, or the flat
+ * `/mcp-servers` rail returns for their Contexts (all grants present), passes
+ * the consent gate — and the gate admits nothing that neither offers.
+ */
+describe('consent gate vs. what the catalogs offer (property)', () => {
+ const contextNames = ['ctx-a', 'ctx-b', 'ctx-c']
+ const hostNames = ['host-1', 'host-2', 'host-3']
+ const servers = ['s1', 's2', 's3']
+ const allGrantsPresent = { query: async () => ({ rows: [{ '?column?': 1 }], rowCount: 1 }) }
+
+ async function seedUserOauthServer(gateway: MockGateway, name: string): Promise<void> {
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name },
+ spec: {
+ contextRef: 'ctx-a',
+ image: 'example/mcp:1',
+ transport: { type: 'streamableHttp', url: `https://${name}.example.com/mcp` },
+ auth: { type: 'oauth' },
+ oauth: { id: `${name}-client`, grantScope: 'user' },
+ },
+ },
+ MCP_NS
+ )
+ }
+
+ it('panel ∪ flat rail ⇔ gate', async () => {
+ await fc.assert(
+ fc.asyncProperty(
+ fc.record({
+ allowlists: fc.dictionary(
+ fc.constantFrom(...contextNames),
+ fc.uniqueArray(fc.constantFrom(...servers), { maxLength: 3 })
+ ),
+ hosts: fc.dictionary(
+ fc.constantFrom(...hostNames),
+ fc.record({ contextRef: fc.constantFrom(...contextNames), enabled: fc.boolean() })
+ ),
+ userContexts: fc.uniqueArray(fc.constantFrom(...contextNames), { maxLength: 3 }),
+ userAgents: fc.uniqueArray(fc.constantFrom(...hostNames, 'host-gone'), { maxLength: 4 }),
+ }),
+ async ({ allowlists, hosts, userContexts, userAgents }) => {
+ const gateway = new MockGateway(MCP_NS)
+ for (const name of servers) await seedUserOauthServer(gateway, name)
+ for (const name of contextNames) {
+ await seedAllowlistedContext(gateway, name, allowlists[name] ?? [])
+ }
+ for (const [name, h] of Object.entries(hosts)) {
+ await seedAgentHost(gateway, name, h.contextRef, { enabled: h.enabled })
+ }
+ membership(mockPoolQuery, {
+ contexts: { 'user-1': userContexts },
+ agents: { 'user-1': userAgents },
+ })
+
+ const panel = await resolveConnectorsForAgents(
+ gateway as never,
+ {
+ mcpServersNamespace: MCP_NS,
+ hostsNamespace: HOSTS_NS,
+ agentNames: userAgents,
+ userId: 'user-1',
+ },
+ allGrantsPresent as never
+ )
+ const flat = await resolveInvocableMcpServersForContexts(
+ gateway as never,
+ MCP_NS,
+ userContexts,
+ 'user-1',
+ allGrantsPresent as never
+ )
+ const offered = new Set<string>(flat.map(s => s.name))
+ for (const agent of panel) {
+ for (const c of agent.connectors) if (c.authKind === 'oauth-user') offered.add(c.name)
+ }
+
+ for (const name of servers) {
+ expect({ name, gate: await check(gateway, 'user-1', name) }).toEqual({
+ name,
+ gate: offered.has(name),
+ })
+ }
+ }
+ ),
+ { numRuns: 200 }
+ )
+ })
+})
+
describe('allowedMcpServerNamesForContexts', () => {
const contextNames = ['ctx-a', 'ctx-b', 'ctx-c', 'ctx-d']
// Padded variants are reachable: the allowlist writer stores the name as given.