Skip to content

fix(agents): use each agent's configured environment for auth, MCP and hooks - #3562

Merged
kdcokenny merged 7 commits into
mainfrom
fix/agent-config-provider-env
Dec 2, 2026
Merged

kdcokenny merged 7 commits into
mainfrom
fix/agent-config-provider-env

Conversation

@kdcokenny

@kdcokenny kdcokenny commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Description

What users saw. Users can set environment variables for an agent in Settings → Agents →
Advanced settings, or for a project in Project Settings. If they set CLAUDE_CONFIG_DIR there,
Claude was spawned with it and TUI hooks were installed under it. Everything else still used
~/.claude and ~/.claude.json:

  • hooks status, auth status and the login command;
  • Settings → MCP and the agent's MCP list;
  • adding or removing an MCP server.

A server added for the configured account landed in the default account's file. A structured
(ACP) chat started under the configured directory was given the default account's MCP servers,
with their credentials.

Cause. These paths read the host's ambient environment. They never received the env that the
spawn path builds from Settings. Claude's MCP adapter also hard-coded ~/.claude.json, ignoring
CLAUDE_CONFIG_DIR altogether.

Change.

  • Env per call. The desktop main process reads the provider's Settings env on every call, from
    the same source the spawn path uses. It passes the env explicitly to the host's agent-config
    runtime. The host merges it over its allowlisted ambient env with mergeAgentEnvLayers, the
    layering buildAcpSpawn uses. Nothing caches an env for a later call.
  • Plugin host and hook installer.
    • AgentPluginHost takes an optional env on checkAuthStatus (env fingerprint in its dedup
      key), buildLoginCommand, and MCP read/write/remove.
    • An MCP behaviour may resolve its config root from the env. Claude's .claude.json now follows
      CLAUDE_CONFIG_DIR.
    • AgentHookInstaller.hooksStatus takes the env too.
    • ACP sessions read their MCP servers under the session's own env (project over provider).
  • Auth status per env.
    • Status is cached and deduplicated per provider and env, and only the newest request publishes.
    • A login keeps the env it started with.
    • Switching env shows unknown rather than the previous account's status, so the sign-in modal
      is not closed by it.
  • Settings changes apply at once, without running the agent. When updateSettings changes an
    agent's env, it only invalidates that provider's auth status (dropped from the cache, published
    as unknown). It never starts claude auth status or any other agent subprocess: the editor
    saves half-typed entries, and the CLI writes its own files into whatever root it runs under. The
    next reader that needs the status probes under the env current at that moment. updateSettings
    also waits for the MCP list to be republished (file reads only) before returning. These
    refreshes are queued and logged without values. The renderer refetches hooks status and the
    agent's MCP lists.
  • Writes go to the listed root. A per-agent MCP removal sends back the root its list came from.
    The host only compares that root; a mismatch refuses the removal and never redirects it. The
    removal also republishes the list under the same lock.
  • Renderer boundary and filtering.
    • The renderer-facing agents and mcp contracts have no env fields, and controllers rebuild
      inputs field by field.
    • MCP calls carry only the envs of providers whose MCP root follows the env (Claude today), so
      other providers' Settings values are not sent to hosts for nothing.

Protocol. PROTOCOL_VERSION 13.2.0 → 13.3.0, a minor bump, as agents/architecture/workspace-server.md
prescribes for optional fields and new procedures. main already took 13.1 for
git.repository.deletePrRef (#3559) and 13.2 for the optional addRemote result (#3558); these
additions get their own minor, so an older server is told apart by the negotiated minor. The doc
and version tests list which minor introduced what. The agent-config contract gains, in 13.3:

  • env? on hooksStatus, startLogin, refreshAuthStatus and listMcpForAgent;
  • providerEnvs? on saveMcpServer, removeMcpServer and removeMcpForAgent;
  • expectedConfigRoot? on removeMcpForAgent, and configRoot? in the listMcpForAgent output;
  • new refreshMcpServers and invalidateAuthStatus procedures.

Only the desktop main process fills these fields.

High-risk areas: provider environment handling (the auth probe and login PTY now get the
Settings env through the same merge as spawn; no allowlist widened; terminal-env.ts untouched),
and the workspace protocol (minor bump, additive optional fields, two new procedures).

The analysis in #3207 identified the bug and the paths involved. This is a smaller replacement
for that PR, without its env cache or its ACP hook installation.

Related issues

Supersedes #3207.

Testing

  • nx run-many -t build --all --skip-nx-cache: pass.

  • nx run-many -t typecheck lint format:check for core, plugins, desktop and workspace-server:
    pass. Lint includes the boundary-rule allowlist tests.
    After merging main at 33f0fe87a8 (with the Claude ACP adapter 0.114 bump, chore(plugins): update the Claude Code ACP adapter to 0.114.0 #3570):

  • @emdash/core: agent-plugins, agent-config, ACP and workspace-server tests, 838 passed. An
    earlier full-suite run had 3109 passing and 9 failing; the 9 are the known process-group and
    tmux tests that fail in this VM.

  • @emdash/plugins tests: 823 passed.

  • @emdash/workspace-server tests: 121 passed.

  • Desktop node tests for agents, MCP, conversations, settings and bootstrap: 60 files, 398 passed.

  • Desktop browser project, in 34 shards: 110 files, 698 passed.

  • New tests (behaviour tests checked to fail without their change, plus read-only regression
    guards):

    • The reproduction table runs through the real plugin host, agent-config runtime and Claude
      plugin, with two config roots in temp directories. Spawn, hooks, auth, login, MCP list, save
      and remove, and session MCP all agree on the configured root. With nothing configured they all
      use the default root.
    • Overlapping auth refreshes (A/B and A/B/A).
    • An env change and a login under a new env never show the old account.
    • A list followed by an env change refuses the removal and leaves both roots untouched.
    • A renderer call carrying env or providerEnvs is stripped by both contracts and never
      reaches the host.
    • Only MCP-root providers' envs are sent.
    • After updateSettings resolves, a save lands in the new root.
    • Post-settings refreshes are queued and a failed one is logged.
    • updateSettings with a changed env starts no auth subprocess and publishes unknown; the
      next status read probes once, under the new env.
    • Reading the MCP list under CLAUDE_CONFIG_DIR="" or a missing directory writes nothing in
      either root or the working directory.
  • Manual run of the Electron app, current main against this branch merged with it, with two
    Claude roots:

    • Cold start: Settings → MCP shows the configured root, and adding and removing servers change
      only that root's file. On main, both land in the default file.
    • Terminal and structured chats run with the configured root; terminal hooks are installed
      there (structured chats install none). The chat's session gets the configured root's servers (WHO=alt), and since chore(plugins): update the Claude Code ACP adapter to 0.114.0 #3570 they
      still reach claude on its command line (--mcp-config); claude runs with the configured
      CLAUDE_CONFIG_DIR. On main, claude also runs with the configured root but its
      --mcp-config carries the default account's servers (WHO=personal).
    • chore(plugins): update the Claude Code ACP adapter to 0.114.0 #3570's invalid-settings refusal follows the root the session runs with: an invalid
      settings.json in the default root does not block a chat configured for another root (the
      chat answers normally), and an invalid one in the configured root stops the chat with the
      error naming /tmp/claude-alt/settings.json. main behaves the same here, since the agent
      process already got the configured CLAUDE_CONFIG_DIR there.
    • Nested parallel subagents (two children, each with a nested child): every row shows
      "Completed", also after restarting the app.
    • With the sheet open, removing or resetting the variable switches hooks, MCP lists and Settings
      → MCP back at once.
    • With nothing configured, behaviour matches main.
    • No log contains the Settings env values.
    • Editing the variable starts no claude process (checked with a logging wrapper), and both
      roots' files stay byte-identical.
    • Sign in, started from the chat's sign-in prompt, spawns claude auth login with
      CLAUDE_CONFIG_DIR=/tmp/claude-alt, or with it unset when nothing is configured (as on
      main). The modal stays open, and cancelling writes nothing to the other root. The prompt
      itself had to be forced: in that VM a signed-out Claude chat fails its first prompt
      (prompt_failed, "Not logged in") instead of reporting auth_required, on main too.

Known limits.

  • Other providers with an env-rooted config (Codex CODEX_HOME, Copilot, Qwen, OpenCode, MiMoCode,
    Prime Agent) still read their MCP config from the home path; their hooks already follow the
    override.
  • ACP chat sign-in uses the provider's Settings env, not the project's.
  • Workspace trust still writes to the default root (~/.claude.json), so Claude asks for folder
    trust under a configured root; provider usage still ignores the env.
  • A Settings → MCP click already in flight while updateSettings runs can still land in the new
    root.
  • A workspace server below 13.3 (development builds only; no release has shipped protocol 13)
    ignores the new fields and cannot serve the two 13.3 procedures, so the Settings → MCP list
    fails to load against it.
  • Sign-in was verified by the spawned login command and its environment, not by completing a
    login.
  • Remote hosts were not run.
  • A signed-out Claude structured chat shows prompt_failed rather than a sign-in prompt
    (existing on main).

Screenshot/Recording (if applicable)

Not attached. The manual run's results and file checksums are in the report.

Checklist
  • I kept this PR small and focused
  • I ran a self-review before opening this PR
  • I ran the relevant local checks or explained why not
  • I updated docs when behavior or setup changed
  • I added or updated tests when behavior changed, or explained why not
  • I only added comments where the logic is not obvious
  • I used Conventional Commits for commit
    messages and, when possible, the PR title

…n explicit provider env

AgentPluginHost.checkAuthStatus (env in its dedup key), buildLoginCommand,
readMcpServers, writeMcpServers and removeMcpServer take an optional env,
merged over the allowlisted agent env with mergeAgentEnvLayers, the same
layering buildAcpSpawn uses. MCP behaviours may resolve their config root
from that env; Claude's .claude.json follows CLAUDE_CONFIG_DIR. The home root
keeps the injected fs. AgentHookInstaller.hooksStatus takes the env too, and
ACP sessions read MCP servers under the session env.
…3.1.0

The agent-config contract gains optional, additive fields: env on
hooksStatus, startLogin, refreshAuthStatus, listMcpForAgent and
removeMcpForAgent; providerEnvs on saveMcpServer and removeMcpServer; and a
refreshMcpServers procedure that republishes the MCP list under the given
envs. Auth status and its in-flight dedup are keyed by provider and env
fingerprint, a login keeps the env it started with, and a refresh under a new
env stops showing the previous account at once. A per-agent MCP removal
refuses when the caller's listed root differs from the root the env resolves
to now. Minor protocol bump: 13.0.0 -> 13.1.0.
…nvalidate on change

The agents and MCP controllers read the provider env from Settings on every
call (createProviderEnvSource, injected through controllers.ts) and pass it
to the host's agent-config runtime: hooks status, auth refresh, login, the
per-agent MCP list and removal, and Settings -> MCP list, save and removal.
The renderer-facing agents and MCP contracts declare their inputs without
env, and controllers rebuild upstream inputs field by field, so a renderer
cannot supply one.

When updateSettings changes a provider's env it re-probes auth and
republishes the MCP list before returning; the renderer also refetches hooks
status and the agent's MCP list. A per-agent removal sends back the root its
list came from, which the host only compares.
main's #3559 took protocol 13.1.0 for git.repository.deletePrRef. The
agent-config additions on this branch (optional provider env fields,
refreshMcpServers, invalidateAuthStatus) move to their own minor, 13.2.0,
so a 13.1 server built from main is told apart by the negotiated minor.
Version tests and workspace-server.md list which minor introduced what.
Move the provider environment protocol change to 13.3.0; 13.2.0 is taken by the optional addRemote result.
Conflict in session-materializer.test.ts: both sides added a test at the
same place (session MCP servers read under the session env; the agent's
explanation of a failed load kept). Both tests are kept.
@kdcokenny
kdcokenny marked this pull request as ready for review December 2, 2026 15:01
@greptile-apps

greptile-apps Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5RetriggerView in Greptile

[Medium impact] The changes reach agent sign-in, hook status, and MCP settings for providers with saved environment overrides.

The PR appears safe to merge, with a non-blocking auth cache cleanup issue.

Findings

  1. P2 Old auth environments accumulate ▶
Fix with agent prompt
### Issue 1
packages/core/src/runtimes/agent-config/node/runtime/auth.ts:130-133
`invalidateStatus` changes the cache key without removing old entries. Each later auth check creates another entry that retains its full `env`, including credentials. `createAsyncCache` has no size limit by default, and its TTL prevents reuse but does not remove expired entries. Repeated settings edits and auth checks therefore keep unreachable entries until the runtime exits. Remove the provider's old entries when invalidating, or bound this cache.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Passes each agent's Settings environment through auth, login, hooks, and MCP calls. ACP sessions now read MCP servers with their session environment.

  • Auth checks, login, and hook status use each agent’s saved environment.
  • Claude MCP lists and edits follow the configured config root.
  • Workspace connections now use protocol version 13.3.0.

Acknowledged limits from kdcokenny, not reported: other providers' MCP roots, project-specific sign-in, workspace trust and usage roots, in-flight Settings MCP writes, and compatibility with development servers below 13.3. Remote hosts and completed sign-in were not manually verified.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Settings[Provider Settings] --> Main[Desktop main process]
  Renderer[Renderer request] --> Main
  Main --> Runtime[Host agent-config runtime]
  Runtime --> Host[AgentPluginHost]
  Ambient[Allowlisted host environment] --> Host
  Host --> Auth[Auth and login]
  Host --> Hooks[Hook status]
  Host --> MCP[Environment-selected MCP root]
  Session[ACP session environment] --> Host
Loading

Reviews (1) · Last reviewed commit: "Merge origin/main into fix/agent-config-..." · Reviewed by Greptile

Comment on lines +130 to +133
invalidateStatus(providerId: string): void {
this.statusEpochs.set(providerId, (this.statusEpochs.get(providerId) ?? 0) + 1);
this.nextStatusGeneration(providerId);
this.publishedEnvs.delete(providerId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Old auth environments accumulate

invalidateStatus changes the cache key without removing old entries. Each later auth check creates another entry that retains its full env, including credentials. createAsyncCache has no size limit by default, and its TTL prevents reuse but does not remove expired entries. Repeated settings edits and auth checks therefore keep unreachable entries until the runtime exits. Remove the provider's old entries when invalidating, or bound this cache.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/core/src/runtimes/agent-config/node/runtime/auth.ts
Line: 130-133

Comment:
**Old auth environments accumulate**

`invalidateStatus` changes the cache key without removing old entries. Each later auth check creates another entry that retains its full `env`, including credentials. `createAsyncCache` has no size limit by default, and its TTL prevents reuse but does not remove expired entries. Repeated settings edits and auth checks therefore keep unreachable entries until the runtime exits. Remove the provider's old entries when invalidating, or bound this cache.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2c56895: status cache keys now hold only the env fingerprint, the env is kept only while its probe is pending, and a provider's earlier entries are dropped when its status is invalidated or a newer read settles. A new test checks that one entry remains after repeated env changes and that earlier env objects are collectable.

…its environment changes

The auth status cache keyed entries by provider, epoch and env fingerprint,
but each entry kept the full StatusKey, env included, and invalidation only
bumped the epoch. Entries for earlier envs became unreachable yet stayed in
the cache, with their env values, until the runtime exited.

The cache key now carries the fingerprint only; a probe reads its env from a
map that holds it only while that read is pending. When a read settles or
the status is invalidated, the provider's entries other than the newest
request's are dropped (entries still being read are kept until they settle).

Copy link
Copy Markdown
Member Author

Merging with the review requirement overridden; evidence for the record, on head 2c56895a7d:

  • Independent review, several rounds: env is resolved only in the main process and never accepted from the renderer; auth status is deduplicated per provider and env and only the newest request publishes; a settings save never starts an agent process; an MCP removal is refused when the root it was listed from no longer matches. The last round covered the auth cache commit made for the bot's finding: a 30,000-operation seeded interleaving run with no invariant violation, at most one cache entry per provider, no env retained after its probe settles, and no env value or fingerprint in logs or errors.
  • App run against current main, with two Claude config roots: Settings → MCP shows and edits the configured root (on main, additions land in the default account's file); a structured chat gets the configured root's MCP servers on the claude command line (on main it is handed the default account's); hooks, auth status and the login command follow the configured root; changing the variable with the sheet open switches at once and starts no claude process; with nothing configured, behaviour matches main; no log contains Settings env values. After the adapter bump (chore(plugins): update the Claude Code ACP adapter to 0.114.0 #3570): the settings file that is validated is the configured root's, and an invalid file in the default root does not block a chat configured for another root.
  • Checks: uncached build, typecheck, lint with allowlists, format check; plugins tests (823), core agent-plugins, agent-config, ACP and workspace-server tests (838), workspace-server tests (121), desktop node tests for agents, MCP, conversations, settings and bootstrap (398), whole desktop browser project (698). CI green including the browser jobs; the bot review's one finding is fixed in 2c56895a7d.
  • High-risk areas touched: provider environment handling for the auth probe and login (same merge as spawn, no allowlist widened) and the workspace protocol (13.2.0 → 13.3.0, additive optional fields and two new procedures; the workspace server must ship with or before the desktop).
  • Not run: remote hosts, a completed sign-in (verified by the spawned login command and its environment), and providers other than Claude (listed as known limits in the description).

@kdcokenny
kdcokenny merged commit 4d9076e into main Dec 2, 2026
17 checks passed
@kdcokenny
kdcokenny deleted the fix/agent-config-provider-env branch December 2, 2026 15:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant