Repository navigation
🗝️ feat: Limit an API Key's Runs to the MCP Tools Its Owner Granted It - #18280
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5ae56fadb7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (req.apiKeyBound === true) return undefined; | ||
| return req.apiKeyId ?? getBackgroundResponseWorkerRecord(req)?.sourceKeyId ?? undefined; |
There was a problem hiding this comment.
Preserve the bound-key exemption in background workers
With remoteApi.integrations.mode: delegated, channel Responses fail during background execution. Channels explicitly submit background: true (packages/api/src/channels/runs.ts), but createBackgroundResponseWorkerAuth reconstructs the request without apiKeyBound. This fallback consequently treats the admitted record's bound sourceKeyId as a personal key. prepare then throws binding_mismatch, because createAgentKeyMCPConsentStorage excludes documents with a binding. Preserve or re-resolve the source key's binding during worker admission so channel runs retain the intended exemption.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d3bc5d8. createAgentKeyMCPGrantHost now takes a getKey reader (wired to getAgentApiKeyById). In prepare, when the request carries no key of its own, which is the background worker's rebuilt request, the host reads the key the admitted record names and attaches nothing if it is one issued to an integration, as on the request that started the run. A personal key stays under its grant in the background, and a key that is gone is refused with binding_mismatch.
Evidence: packages/api/src/apiKeys/grants.spec.ts › "keeps the exemption of a key issued to an integration when its run is a background one"; api/server/services/ApiKeys/grants.spec.js › "asks the key store what kind of key a background run names" loads the real wiring. Removing the lookup fails the first.
| const grantPath = '/:id/agents/:agentId/mcp-consent'; | ||
|
|
||
| router.get(grantPath, requireJwtAuth, checkRemoteAgentsUse, (req, res) => grants().get(req, res)); |
There was a problem hiding this comment.
Provide a frontend entry point for managing key grants
When an operator enables delegated mode, personal keys without grants lose all MCP access, but owners cannot grant or restore access from the application. Repository-wide searches for mcp-consent, mcpGrants, and AgentKeyMCP find no frontend integration for these routes; the existing API-key settings item only exposes deletion. Add a per-key/per-agent consent entry point with the grant-management flow in this change rather than leaving owners to construct HTTP requests manually. AGENTS.md explicitly requires backend capabilities to ship with a frontend entry point.
AGENTS.md reference: AGENTS.md:L50-L53
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
| const canUseAgent = async (agentId, user) => | ||
| ( | ||
| await checkRemoteAgentAccess({ | ||
| userId: user.id, | ||
| role: user.role, |
There was a problem hiding this comment.
Move the agent-access helper into the TypeScript host
The new canUseAgent helper constructs an authorization request, calls the access service, and interprets its result inside legacy CJS. This violates the explicit AGENTS.md boundary that new helpers and service-call behavior belong in packages/api, while /api only wires dependencies and invokes the TypeScript module. Move this adapter into the TypeScript grant host and inject getAgent and getEffectivePermissions from this file, keeping the authorization behavior within the required package boundary.
AGENTS.md reference: AGENTS.md:L80-L84
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d3bc5d8. api/server/services/ApiKeys/grants.js no longer builds the check. It passes getAgent and getEffectivePermissions to createAgentKeyMCPGrantHost, which builds canUseAgent from checkRemoteAgentAccess in packages/api/src/apiKeys/grants.ts and uses it for both the access check and the enrollment root.
Evidence: grants.spec.ts › "asks whether the owner may run the agent, and refuses the grant and its use when they may not" drives it through the injected permission reader; forcing the check to pass fails it.
| const loadOwner = async (identity: AgentKeyMCPIdentity): Promise<IUser | null> => { | ||
| const user = await deps.findUser(identity.ownerId); | ||
| if (!user || (user.tenantId ?? null) !== identity.tenantId) return null; | ||
| user.id = identity.ownerId; | ||
| return user; |
There was a problem hiding this comment.
Reuse the owner lookup within each authorization evaluation
For every MCP call authorized under an existing key grant, authority.authorize invokes both canUse and getLimits, and each independently calls this uncached loadOwner; after those finish, resolveEnrollment performs a third lookup of the same owner. The production dependencies all delegate to methods.findUser, which issues a Mongo query, so this adds redundant database traffic and another serial user-read round trip before every upstream tool call. Unlike the existing schedule host's pendingPrincipals coalescing, this host does not even share the concurrent reads. Share fresh owner/config data within each authorization evaluation, without caching authorization across tool calls, as required by AGENTS.md's request-path data-reuse rule.
AGENTS.md reference: AGENTS.md:L203-L205
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d3bc5d8. loadAuthorization reads the owner once and their configuration once, then builds a consent service for that one evaluation whose findUser and getAppConfig return those values (createService(source)), the same shape as the schedule runtime's. The access check, the limits and the offer share them, and nothing is kept for the next call.
Evidence: grants.spec.ts › "reads the owner and their configuration once for each call it authorizes" (one of each per call, and a second owner read on the next call). Handing back the shared service's authority fails it.
…pt Host The agent-access check and the grant-mode lookup lived in the legacy route and service files. The host now builds the check from an injected agent reader and permission reader, and the key handlers resolve the mode from an injected configuration reader. Each authorized call read the owner three times and their configuration twice. The host now reads both once per call and shares them between the access check, the limits and the offer; nothing is kept between calls. A background worker rebuilds its request from the admitted record, which names the key but not its kind, so a key issued to an integration lost its exemption and its channel runs were refused. The host asks the key store when the request carries no key itself.
The key grant dialog turned a failed or pending agent list into an empty picker with an instruction to choose from it. It now shows a spinner while the list loads, an error with a retry when it could not be read and nothing is cached, and a plain statement when the owner has no agent the key could run.
5ae56fa to
7214869
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7214869d83
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const list = useListAgentsQuery( | ||
| { requiredPermission: PermissionBits.VIEW }, | ||
| { select: (res) => res.data }, | ||
| ); |
There was a problem hiding this comment.
Include remotely accessible agents in the grant picker
When a user has REMOTE_AGENT VIEW permission but no AGENT VIEW permission for an agent, this picker never offers that agent. useListAgentsQuery uses the normal catalog, whose getAgentListAccess implementation in packages/api/src/agents/listing.ts filters exclusively on ResourceType.AGENT, whereas the grant host's checkRemoteAgentAccess explicitly accepts remote-only access. In delegated mode, these users can run the agent but cannot grant their key the MCP access it needs through Settings. Populate the picker using remote-run access rules, or provide another way to select remotely accessible agents. This leaves a supported backend grant flow without the frontend entry point required by the repository guidance.
AGENTS.md reference: AGENTS.md:L58-L59
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ccbcad7. The picker no longer reads the app's catalog. GET /api/api-keys/agents (listAgents in packages/api/src/apiKeys/handlers.ts) returns the agents shared with the caller for remote use (REMOTE_AGENT view) together with the ones that are theirs to share (AGENT share), which is the rule checkRemoteAgentAccess applies to one agent. KeyGrant.tsx reads it through useApiKeyAgents, so an agent shared only for remote use can be granted, and an agent the owner can view but not run remotely is no longer offered.
Read against the same rule (a key can be granted exactly where it can run): a key issued to an integration holds no grants, so the key list now marks it (bound) and the MCP access button is not shown for it.
Evidence: handlers.spec.ts › listAgents; api/server/routes/__tests__/apiKeys.spec.js › "lists the agents a key can be granted for, and does not take the path for a key id" (real route); KeyGrant.spec.tsx › "lists the agents this key could run, not the catalog the owner browses"; Item.spec.tsx and agentApiKey.spec.ts for the bound key. Five mutations (either half of the rule, the de-duplication, the route order, the button condition, the marker) each fail a test.
… Personal Keys The grant dialog's picker read the app's agent catalog, which lists agents the owner can view. Running an agent with a key follows another rule: the agent is shared with the owner for remote use, or is theirs to share. An agent shared only for remote use could be run but not granted. A new list, GET /api/api-keys/agents, applies that rule to all agents, and the picker reads it. A key issued to an integration holds no grants but showed the MCP access button. The key list now marks such a key, and the button is not shown for it.
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
/quality risk scopes=api |
Quality reportGate: open. The selected checks completed. Scores and risk levels are advisory. Status: completed (success). Actions run, attempt 1.
Change riskTakeaway: 3 changed lines have no test. Highest CRAP among changed functions:
Changed lines with no test
|
| Function | Complexity | Coverage | CRAP | Location |
|---|---|---|---|---|
callTool |
164 | 88% | 209.2 | packages/api/src/mcp/MCPManager.ts:1524 |
view |
43 | 93% | 43.5 | packages/api/src/schedules/authorization/service.ts:303 |
authorize |
37 | 88% | 39.2 | packages/api/src/schedules/authorization/execution.ts:283 |
(anonymous) |
33 | 92% | 33.6 | packages/api/src/schedules/authorization/enrollment.ts:68 |
resolve |
22 | 100% | 22.0 | packages/api/src/schedules/authorization/execution.ts:173 |
recordScheduledMCPToolAuthFailure |
21 | 91% | 21.3 | packages/api/src/schedules/service.ts:340 |
confirm |
19 | 86% | 20.1 | packages/api/src/schedules/authorization/service.ts:414 |
(anonymous) |
18 | 89% | 18.4 | packages/api/src/apiKeys/middleware.ts:65 |
prepare |
17 | 100% | 17.0 | packages/api/src/apiKeys/grants.ts:211 |
resolveRemoteIntegrations |
11 | 100% | 11.0 | packages/api/src/apiKeys/grants.ts:41 |
46 more functions below the threshold (or cut for size) are in report.md.
CRAP = complexity² × (1 − coverage)³ + complexity
Jobs (1)
| Check | Result |
|---|---|
| Change risk (api) | success |
All data (quality-report artifact) · Run page
The gate opens only when the workflow, source selection, tooling verification, and every report job succeed. A report job fails on a failed test in its workspace's own Jest run, a tool error, a job timeout, or an incomplete mutation report, including a mutation shard that reaches its execution budget. A cancelled workflow keeps the gate closed. Scores are advisory. A change-risk file marked incomplete or unavailable, for example by a failed api/ source-alias suite, does not close the gate.
Summary
A run started with an agent API key (chat completions, Responses, a background Responses worker) can call every MCP server its key's owner can use, with the owner's stored credentials. An API key carries no scope: whoever holds it holds all of the owner's integrations, for every agent the owner can run remotely.
This PR lets an owner say, per key and per agent, which MCP servers and tools a run started with that key may use, and refuses everything else. It is the grant scheduled chats already have (#18260, #18273), held by an API key instead of a schedule: the same consent service, the same storage writes, the same check at
MCPManager.callTool.It is off unless the operator turns it on.
endpoints.agents.remoteApi.integrations.modedefaults toowner, which is today's behaviour; underdelegateda personal key with no grant for the agent may not use MCP tools at all. Where it is on, each key in Settings → API Keys gets an "MCP access" button that opens the grant dialog for the agent the owner picks. Changing the default todelegatedis the next PR.Seventh step of the unattended-authority work. Related to #13824.
How it works
Remote runs already build MCP tools through the same request context and
MCP.jspath as scheduled runs, so attaching an execution to that context is enough for every tool, including handoff and subagent tools, to be bound and checked.The legacy
/apifiles only wire.api/server/services/ApiKeys/grants.jspasses the storage, the user, role, agent, permission and key readers and the enrollment readers tocreateAgentKeyMCPGrantHost; the host builds the "may the owner run this agent remotely" check itself fromcheckRemoteAgentAccess.api/server/routes/apiKeys.jspassesgetAppConfigto the key handlers, which resolve the mode.Each authorized call builds its own consent service over one read of the owner and one of their configuration, shared by the access check, the limits and the offer. Nothing resolved there is kept for the next call.
The dialog.
GrantDialogtakes where the grant is read and written (source: one query and two mutations) and the words that depend on what holds it (copy). Everything else, including the tool boxes, the changed-tool note and the lifetime field, is shared with schedules, whose existing tests run against it through the wrapper. The key dialog has one thing a schedule's does not: the owner picks the agent first. Until then nothing is requested. The picker lists the agents a key can run, which is not the catalog the owner browses in the app:GET /api/api-keys/agentsreturns the agents shared with the caller for remote use together with the ones that are theirs to share, the rulecheckRemoteAgentAccessapplies to one agent on each remote request. The "MCP access" button is not shown for a key issued to an integration. The agent list shows a spinner while it loads, an error with a retry when it could not be read and nothing is cached, and a plain statement when the owner has no agent. The owner's ticks live in a part of the dialog keyed by the agent, so switching agent starts over.What differs from a schedule's grant:
getScheduleMCPExecutionreturns nothing for a key's execution).approval: false, the dialog shows no "ask me first", and asking is rejected.Type of change
Testing
Tested environments/configuration: WSL2, Node.js 24. Storage tests run against
mongodb-memory-server. No external services.Automated tests:
packages/data-schemas/src/methods/agentKeyConsent.spec.ts(new): one grant per agent on a key, each on its own; one winner among concurrent grants; revocation; pins and change marks stay on the one agent's grant; the admission and confirmation fences of 📌 feat: Pin an Allowed Schedule Tool to the Definition It First Ran With #18273 hold on a key's grant, one agent at a time; nothing found or written for another owner, another tenant or an unknown key; no grant on an expired or a bound key; a grant made out to a different key, owner or agent is refused; an agent id is never turned into a field path unless it has the id shape; an unreadable stored grant fails closed; classic update operators only.packages/data-schemas/src/methods/scheduleConsent.spec.tsandschedule*.spec.ts(existing): unchanged and passing against the shared storage implementation.packages/api/src/apiKeys/grants.spec.ts(new), through the real consent service and enrollment resolver: unrestricted unless the operator asks for grants; every MCP tool refused for a key with no grant; only the allowed tools run; a grant is for one agent; revoked and expired grants stop; an unknown key or an unnamed agent is refused, not unrestricted; a run no key started is not restricted; a background run of a key issued to an integration keeps its exemption, a personal key's background run stays under its grant, a key that is gone is refused, and a request that authenticated with the key reads nothing extra; the owner's permission on the agent decides both the grant and its use; the owner and their configuration are read once per authorized call and not kept; an agent with other tools can be granted and is not treated as a schedule run; servers come fromremoteApi.integrations.resources, not from the schedules list; no approval pause; the HTTP handler hides keys that are not the caller's; which key a request runs under.packages/api/src/apiKeys/handlers.spec.ts(new): the list carriesgrants: trueonly underdelegated, resolved for the owner who asks, and does not list keys when the mode cannot be established; the agent list is the union of both kinds of remote access, each agent once, read in parallel, with nothing read when there is none and no partial answer when a lookup fails.packages/data-schemas/src/methods/agentApiKey.spec.ts: a key issued to an integration is marked in the owner's list, without its binding.packages/api/src/apiKeys/middleware.auth.spec.ts: a key issued to an integration is marked on the request; a personal key is not.packages/api/src/agents/authority/context.spec.ts: the key id on a remote execution context.api/server/controllers/agents/__tests__/openai.spec.js,responses.unit.spec.js: each controller puts the run under its key's grant before any tool is loaded, with the key id in the context; a bound key names no key; nothing is loaded when the grant check fails.api/server/services/ApiKeys/grants.spec.js(new) andapi/server/routes/__tests__/apiKeys.spec.js(new): load the real server wiring and the real route against the real packages, with only the app's singletons stood in for. They check that the default mode leaves a key run untouched, that no config is read for a run no key started, that the key store is asked about a background run's key, that the list's flag comes from the configuration resolved for the caller, and that/agentsis served by the agent list and not taken for a key id.client/src/components/Nav/SettingsTabs/ApiKeys/__tests__/KeyGrant.spec.tsx(new): nothing is requested, listed or spinning until an agent is picked; the picker reads the list of agents the key can run; that list's loading, failed (with retry), stale-but-usable and empty states, driven through the real query; picking an agent requests that key and agent's grant, and confirming sends it; picking another starts over; a state with nothing to grant uses the key's wording; revoking goes to that key and agent.client/src/components/Nav/SettingsTabs/ApiKeys/__tests__/Item.spec.tsx,List.spec.tsx: the button is absent unless the list says grants are in use, and for a key issued to an integration; it is labelled with the key's name, announces a dialog, and opens it for that key.client/src/components/SidePanel/Schedules/__tests__/Consent.spec.tsx(existing): unchanged and passing against the shared dialog.packages/data-provider/src/types/scheduleConsent.spec.ts: the config block and the key identity.packages/api/src/schedules) pass unchanged with the generic types.Each new rule was broken in turn and a test confirmed to fail.
npx tsc --noEmitis clean inpackages/api,packages/data-schemas,packages/data-providerandclient.Not verified: a real remote request with
mode: delegatedagainst a running server, and the dialog against a running server. The mock e2e lane (e2e/specs/mock/scenarios/auth-path-reads.spec.ts) makes real API-key calls to both endpoints in the default mode. No test drives a real background Responses worker; the worker case is tested at the host with a request that carries no key.Performance
In the default
ownermode a key request reads the owner's configuration once more (fail-closed, through the config service's cache) and nothing else.Under
delegated, starting a run adds that configuration read and one read of the key's document for its grant; a background run adds one more read of the key to learn its kind. These are serial.Each MCP tool call then pays what a scheduled run's call pays, through the same service: one grant read, one owner read, one configuration read, the role, agent and permission reads of the access check, the agent-graph resolution of the offer, and the admission write (plus a pin write on a tool's first use). I did not measure latency before and after; the tool call's own network round trip is not changed.
Listing keys reads the owner's configuration once more. Opening the grant dialog makes one request for the agent list: two permission lookups in parallel, then one read of the names of the agents found.
Screenshots / recordings
The real components under the app's stylesheet in Chromium, fed fixed data in place of the API. The Cancel button shows its key because the capture does not initialise the shared package's i18n; the app does. The agent list's loading, failed and empty states were added after these captures and are not shown.
A key row, before and after (the button only appears where grants are in use):
The dialog: before an agent is picked, the picker open, and an agent picked.
Risk / compatibility
Default unchanged. With
integrations.modeunset orowner, nothing is attached and remote runs behave as before. The grant step does not read the configuration copy on the request: a config that fell back to the deployment's base during an override outage must not read as unrestricted.Under
delegated, these are not restricted:POST /v1/events, which runs through the chat controller path, not these two controllers.What the caller sees. A refused tool call reaches the model as an error tool result, as any failed tool call does today; the API response does not carry a typed code. A refusal at the grant step itself (unknown key, unnamed agent) is a run-level error: 403 with
mcp_reauth_requiredfor a non-streaming request.Storage.
AgentApiKeygains an optionalmcpGrantsmap keyed by agent id. No migration. A grant for an agent that is later deleted stays on the key until the key goes; it cannot be used, since the access check finds no agent. A replica without this change ignores the field and runs key requests unrestricted, which is today's behaviour, sodelegatedis only real once every replica is upgraded.Refactor. The schedule consent storage now goes through a shared implementation with two holders, and the schedule dialog through a shared component. Their filters, update operators and behaviour are the same; the existing storage and dialog tests are the check on that.