Skip to content

fix(codex): forward ${VAR} stdio env values with env_vars instead of writing them - #3406

Merged
Daniel Meppiel (danielmeppiel) merged 11 commits into
microsoft:mainfrom
abhishekacharya200:fix/codex-mcp-env-vars
Nov 11, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 11 commits into
microsoft:mainfrom
abhishekacharya200:fix/codex-mcp-env-vars

Conversation

@abhishekacharya200

@abhishekacharya200 Abhishek Acharya (abhishekacharya200) commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

A self-defined stdio dependency that declares a secret as

env:
  FIGMA_API_KEY: "${FIGMA_API_KEY}"

had the value resolved at install time and written into .codex/config.toml, a file that lives in the repository. If the variable was unset during install, the literal ${FIGMA_API_KEY} was written and Codex handed that string to the server. Codex can read a stdio server's variables from its own environment through env_vars, the way bearer_token_env_var is used for remote headers since #3042.

Issue and approved scope

Issue: #3393

Human scope-approval comment: #3393 (comment)

This PR covers the full Done when list of that record. Registry backed environment_variables, user scope semantics and other harnesses stay out of scope and untouched.

Fixes #3393

Change

At Codex project scope (.codex/config.toml):

  • An env value written as exactly ${VAR} or ${env:VAR} under the key VAR becomes env_vars = ["VAR"]. It is not resolved, prompted for or written, whether or not VAR is set.
  • Any other reference (TOKEN: ${OTHER}, AUTH: Bearer ${TOKEN}, <VAR>) keeps today's install time resolution, and APM prints one warning per server that names the keys only and suggests KEY: ${KEY}.
  • Static values, args placeholders, cwd, remote header fields and unrelated entries keep their current output. env_vars is emitted before the [env] sub table so tomlkit cannot nest it.
  • Reinstall: a value written by the older formatter is replaced with env_vars only when the entry is still APM managed and matches its recorded baseline, and the declaration forwards that key. APM then warns, names only, that the value was replaced and that a credential in a shared or committed config.toml should be rotated because Git history still holds it. An edited or unrecorded entry is preserved and install exits 1 with the existing reconciliation guidance, plus the same rotation note. A stored ${VAR} reference never held a secret, so it gets no rotation note.

At user scope (-g, ~/.codex or $CODEX_HOME) the output is unchanged, and the legacy matcher never applies there.

docs/src/content/docs/consumer/install-mcp-servers.md and the packaged apm-usage guidance (packages/apm-guide/.apm/skills/apm-usage/dependencies.md) describe this.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Maintenance / refactor

Testing

  • Tested locally
  • All existing tests pass
  • Added tests for new functionality (if applicable)

Installed CLI, tests/integration/test_codex_mcp_env_vars_e2e.py, with synthetic values and an isolated HOME and CODEX_HOME:

  • test_references_are_forwarded_for_set_and_unset_variables (both spellings, set and unset; no secret in config.toml, apm.lock.yaml or output)
  • test_unforwardable_references_warn_with_names_only, test_embedded_reference_is_resolved_and_named_in_warning
  • test_user_scope_install_still_resolves_values (matches the output of main for the same inputs)
  • test_reinstall_replaces_apm_written_value_with_env_vars, test_reinstall_preserves_a_value_that_was_edited_by_hand, test_reinstall_preserves_an_unrecorded_entry (the legacy config.toml is written by the test, so these run in CI)
  • Two more cases that install first with a real main build when APM_LEGACY_BINARY_PATH is set, and skip otherwise. Both pass locally.

tests/integration/test_mcp_stdio_env_resolution_e2e.py asserted the old Codex contract, so it is split: the Claude case is unchanged, and the Codex case asserts env_vars and no secret.

Unit tests in tests/unit/test_codex_adapter_phase3.py (TestForwardedStdioEnv, TestForwardedStdioEnvScope) and tests/unit/install/test_mcp_ownership.py cover the split, both scopes, the warning, baseline rendering without duplicate warnings, and the legacy upgrade path.

With main's src, 13 unit tests and 8 integration tests fail; all pass with this change. Locally: tests/unit/install, tests/unit/adapters, test_codex_adapter_phase3.py and test_global_mcp_scope.py give 3409 passed; the two integration files give 13 passed; ruff check, ruff format --check, lint-architecture-boundaries.sh and lint-auth-signals.sh are clean.

Spec conformance (OpenAPM v0.1)

  • N/A -- this PR does not change OpenAPM-observable behaviour.

Copilot AI left a comment

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.

🟡 Changes recommended

Unresolved issues let transitive dependencies request credentials outside the modeled env field and prevent upgrading or removing legacy managed entries, leaving plaintext secrets in place.

3 open issues
What changed in this PR

This PR addresses #3393 by using Codex’s runtime env_vars field for same-name environment references in self-defined stdio MCP servers, rather than writing resolved values into config.toml.

Changes:

  • Separates forwarded references from values that retain install-time resolution, while preserving argument substitution.
  • Adds forwarding and TOML-output tests and updates install-flow expectations for Codex.
  • Records the behavior change in the changelog; registry-backed servers remain unchanged.
File Description
tests/​unit/​test_codex_adapter_phase3.py Adds coverage for forwarding, literal values, argument resolution, and written TOML.
tests/​unit/​install/​test_mcp_integrator_install_flow.py Expects Codex runtime forwarding while preserving Claude’s existing behavior.
src/​apm_cli/​adapters/​client/​codex.py Splits stdio environment entries and emits forwarded names through env_vars.
CHANGELOG.md Documents the new Codex stdio environment behavior.

Review effort: Balanced

Comment thread src/apm_cli/adapters/client/codex.py Outdated
Comment on lines +404 to +406
if forwarded_env:
stdio_config["env_vars"] = forwarded_env
stdio_config["env"] = written_env

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 95c6d93. A new adapter hook, matches_legacy_managed_server_config, lets the self defined branch of compare_native_mcp_connection treat an entry from the older formatter as an update. It only accepts a value that is the literal ${VAR} or the current environment value, since that is all the old formatter could write. Anything else stays a conflict, so manual edits are kept. One limit: if the variable changed after the old write, the entry also reports a conflict, which is the safe side. Tests are in test_mcp_ownership.py.

Comment on lines +404 to +407
if forwarded_env:
stdio_config["env_vars"] = forwarded_env
stdio_config["env"] = written_env
self._merge_extra(stdio_config, server_info)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 95c6d93. env_vars is now in _HARNESS_EXTRA_ALIASES, the literal in the architecture guard is updated, and a new test checks that extra: {env_vars: [...]} does not reach the rendered config.

Comment thread src/apm_cli/adapters/client/codex.py Outdated
forwarded_env: list[str] = []
for name, raw_value in raw_env.items():
if isinstance(raw_value, str):
reference = _ENV_VAR_RE.fullmatch(raw_value.strip())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 95c6d93. The match now runs on raw_value directly, so a value with surrounding whitespace or a trailing newline keeps install time resolution. Tests cover both cases.

A self-defined stdio dependency that declared a secret as
`FIGMA_API_KEY: ${FIGMA_API_KEY}` had the value resolved at install time and
written to `.codex/config.toml`, which sits in the repository. When the
variable was unset, the literal `${FIGMA_API_KEY}` was written instead and
handed to the server as text.

Codex can read a stdio server's variables from its own environment through
`env_vars`, so a value authored as exactly `${VAR}` under the key `VAR` is now
forwarded instead of resolved. Every other value, including a reference under
a different key, keeps the existing install-time resolution.

Args keep resolving against the forwarded names when the value is available,
so an argument that references the variable is unchanged.
…tter

env_vars now represents the modeled env field, so passthrough can no
longer request launch environment variables. Only an exact ${VAR} value
is forwarded, so authored whitespace keeps install time resolution. A
stdio entry the older formatter wrote counts as managed when its value
is the literal reference or the current environment value; anything
else stays a conflict, so manual edits are preserved.
@sergio-sisternes-epam

Copy link
Copy Markdown
Collaborator

Thank you for contributing this pull request. The linked issue #3393 is open but has not been accepted by a maintainer. APM starts with an issue, not an implementation (https://github.com/microsoft/apm/blob/main/CONTRIBUTING.md). Please wait for a maintainer to review and accept the scope in #3393 before proceeding. This PR is labelled status/deferred until then.


Generated by autopilot-pr-triage-worker. This comment is AI-generated and may contain errors.

@sergio-sisternes-epam Sergio Sisternes (sergio-sisternes-epam) added area/mcp-config MCP server configuration depth, transports, variable resolution. status/deferred Not invited for implementation now; no release commitment. triage/recommended Automated advice completed; not human scope approval. type/bug Something does not work as documented. labels Nov 3, 2026
@danielmeppiel Daniel Meppiel (danielmeppiel) removed the status/deferred Not invited for implementation now; no release commitment. label Nov 10, 2026
…ope end to end

Forwarding through env_vars now applies to project scope only, so
~/.codex and $CODEX_HOME output is the same as before. References Codex
cannot forward keep install time resolution and get a names-only
warning. On reinstall an APM-written value is replaced only for an
unchanged managed entry, with a credential rotation note; an edited or
unrecorded entry is preserved with manual reconciliation guidance.
Installed-CLI tests cover set and unset variables in both spellings,
static and mismatched values, user scope and migration. Docs and the
packaged apm-usage guidance describe the behavior.
Folds the remaining gaps against the apm-scope:v1 record on microsoft#3393 on
top of the contributor's project-scope reshape.

- User-scope Codex output is byte-identical to main again: the stdio
  entry keeps its historical key order (cwd after args), and the
  env_vars passthrough reservation is reverted because it changed every
  scope's output for manifests that set extra.env_vars. At project scope
  the modeled env_vars still wins over extra through the shadow guard.
- The legacy upgrade now uses the lockfile fingerprint when one exists
  (v0.35.0+): a match proves APM wrote the entry even after the
  variable changed, a mismatch keeps it a conflict. Without a
  fingerprint the literal-or-current-environment check still applies
  and is logged at debug level.
- Names in the new warning and conflict text are ASCII-escaped like the
  microsoft#3042 header warning.
- The simulated-migration e2e records the legacy write's fingerprint as
  v0.35.0 did; real v0.35.0 -> head migration passes unchanged.

Addresses Copilot inline r4399350161 (recorded native hash) and panel
findings from python-architect, supply-chain-security-expert and
cli-logging-expert.

Co-authored-by: Copilot <[email protected]>
Addresses doc-writer panel finding on install-mcp-servers.md accuracy.

Co-authored-by: Copilot <[email protected]>
The ownership and install changes apply the existing req-mf-013 matrix
to Codex: a same-key ${VAR} reference is passed through natively
(env_vars) and every other reference keeps install-time resolution with
a diagnostic. No manifest, lockfile schema, resolver or policy semantics
change, so no new requirement anchor is added.

apm-spec-waiver: Codex native env_vars rendering applies existing req-mf-013 (native pass-through where supported, diagnostic otherwise); no new normative requirement, schema or lockfile change.

Co-authored-by: Copilot <[email protected]>
The installed CLI keeps the modeled env_vars at project scope when a
manifest also sets extra.env_vars, and leaves user-scope passthrough
exactly as before. Pins the boundary the deferred passthrough-denylist
follow-up would change.

Addresses CEO follow-up from test-coverage-expert.

apm-spec-waiver: Codex native env_vars rendering applies existing req-mf-013 (native pass-through where supported, diagnostic otherwise); no new normative requirement, schema or lockfile change.

Co-authored-by: Copilot <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_with_followups

Codex project-scope stdio MCP env values declared as KEY: ${KEY} / KEY: ${env:KEY} now land as env_vars instead of resolved secrets, user-scope output stays byte-identical to main, and legacy upgrades are proven by the lockfile fingerprint when one exists.

panel-mode=full; personas=python-architect,test-coverage-expert,doc-writer,supply-chain-security-expert,cli-logging-expert

cc Abhishek Acharya (@abhishekacharya200) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

Measured against the approved apm-scope:v1 record on #3393. Abhishek Acharya (@abhishekacharya200) independently pushed the project-scope reshape (efdfde7) while the panel ran, so the maintainer-side work was rebased onto that commit and only the remaining gaps were folded on top. Thank you -- it was a close match to the planned reshape.

No panelist raised a blocking-severity finding. 15 of the new unit tests fail on main, as do the binary e2e cases, and all of them pass on head. Mutation-break checks show the user-scope key order, the fingerprint veto, and the passthrough boundary are each load-bearing. A real v0.35.0 -> head migration passes end to end. One item is deferred: reserving env_vars in the passthrough denylist. That change would alter user-scope output for every extra.env_vars manifest, which the scope record rules out, and the gap already exists on main.

Panel summary

Persona B R N Takeaway
Python Architect 0 1 2 Hooks follow base+subclass; ownership.py stays the single comparison owner; denylist registration deferred.
Test Coverage Expert 0 0 1 Every Done-when clause maps to a test; e2e extra.env_vars case now folded.
Doc Writer 0 2 1 Accuracy fixes folded; earlier placement/wording notes targeted superseded text.
Supply Chain Security Expert 0 0 2 No secret reaches config, lock or output on the project path; fingerprint proof sound.
CLI Logging Expert 0 1 2 Notes targeted superseded wording; contributor's text fires only on the real write.

B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.

Folded in this run

  • User-scope Codex output byte-identical to main again (stdio key order cwd after args); exact TOML bytes pinned. (f709243)
  • Reverted the env_vars passthrough reservation that changed user-scope output; at project scope the modeled env_vars still wins over extra. (f709243)
  • Legacy upgrade uses the lockfile fingerprint when recorded (v0.35.0+): match upgrades even after the variable rotated, mismatch stays a conflict; hashless fallback is logged at debug level. (f709243)
  • ASCII-escaped names in the new warning and conflict text. (f709243)
  • Docs: an args reference to a forwarded variable is still resolved. (63dd531)
  • Binary e2e for extra.env_vars at project and user scope. (58db0b2)
  • Mode B spec gate: waiver citing existing req-mf-013 (native pass-through where supported, diagnostic otherwise). (c97a100)

Copilot signals reviewed

  • r4399350161 (legacy upgrade) -- LEGIT; folded by contributor in 95c6d93, fingerprint proof added in f709243.
  • r4399350216 (reserve env_vars in passthrough) -- LEGIT; reverted to keep user scope unchanged, deferred below.
  • r4399350259 (strip() forwarded non-exact values) -- LEGIT; fixed by contributor in 95c6d93.

Deferred

  • Reserve env_vars in _HARNESS_EXTRA_ALIASES -- changes passthrough policy and user-scope Codex output for every extra.env_vars manifest; the scope record keeps user scope unchanged. Pre-existing on main; suggest a separate issue.

Evidence

  • Lint (merge commit with current main): ruff check + format, pylint R0801 10.00/10, auth-signals, architecture boundaries -- all clean; ASCII-only diff.
  • Tests: Codex adapter + ownership + install-flow units 179 passed; binary e2e 15 passed via a local shim (including 2 real v0.35.0 legacy-migration tests).
  • CI at 71a1a7f: 24 success, 2 neutral, 1 skipped, 0 failing.
  • CLA: no CLA status is reported on this PR.
PR head stance iterations folds deferrals copilot rounds CI mergeable state notes
#3406 71a1a7f ship_with_followups 2 7 1 2 green MERGEABLE BLOCKED pending required review

Recommendation

Ready for maintainer review: CI is green on the latest push, and no foldable items remain inside the approved scope. Track the env_vars passthrough reservation as its own scoped follow-up. Credit Abhishek Acharya (@abhishekacharya200)'s independent reshape in the merge message.


Generated by autopilot-pr-merge-worker. This comment is AI-generated and may contain errors.

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit c3c86a8 into microsoft:main Nov 11, 2026
3 checks passed
Daniel Meppiel (danielmeppiel) added a commit to Aaryan-Dadu/apm that referenced this pull request Nov 12, 2026
Resolve conflicts with microsoft#3406 (Codex env_vars) and the 0.1.56 spec
amendment. The legacy-entry check now uses the single adapter hook
matches_legacy_managed_server_config(recorded_write=...) that main
introduced; Claude overrides it instead of adding a parallel hook, and
ownership calls it once for self-defined and registry baselines. The
PR's spec changelog row becomes 0.1.57 so it no longer collides with
main's 0.1.56; the working-draft count is 137 (132 MUST, 5 SHOULD).

Co-authored-by: Copilot App <[email protected]>
Daniel Meppiel (danielmeppiel) added a commit to Aaryan-Dadu/apm that referenced this pull request Nov 12, 2026
…onflict

The MCP variable compatibility inventory was written before microsoft#3406 landed
on main and still said Codex project scope writes resolved env values.
Codex project and user scope are now separate rows, and the known-gap
lists name Codex user scope. The producer page no longer uses Codex
project env as the example of a harness needing literal values. The
consumer page says a preserved Claude entry ends the install with an
error naming each field and its reference. The CHANGELOG entry is
trimmed to one line ending in (microsoft#3377).

Addresses review-panel follow-ups (doc-writer, devx-ux-expert).

Co-authored-by: Copilot App <[email protected]>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 12, 2026
* fix(claude): keep ${VAR} references in project .mcp.json

Claude Code expands ${VAR} and ${VAR:-default} in the project .mcp.json,
so apm install keeps the references there instead of prompting for and
writing the real values. Reinstall replaces values an earlier release
wrote when APM can confirm it wrote them; otherwise it keeps the entry
and names the fields to fix. User scope is unchanged.

Adds an MCP variable compatibility page covering every harness.

Closes #3252

* docs(spec): add req-mf-026 for Claude project MCP references

Adds the spec citation for this PR's install and ownership change:
req-mf-026 in Section 4.5, the Appendix C and manifest rows, three
conformance tests, and the regenerated CONFORMANCE files.

* fix(claude): key MCP upgrade checks by declared name; clearer guidance

After merging main (#3493), self-defined servers keep their declared name
(slashes included) as the native key. The security-upgrade snapshot and
the conflict guidance looked entries up by the truncated key, so a
slash-named server lost its upgrade notice and reconciliation guidance.
Both now use the declared key.

Panel follow-ups folded: the conflict guidance names which ${VAR} belongs
in each field (names only, never values or defaults); the --force caveat
sits on its own line; Claude's upgrade notice reads "the project
.mcp.json"; the opaque _begin_env_tracking/_record_env_diagnostics
snapshot contract is documented; a test guards that Claude redeclares
every mutable Copilot aggregation bucket; a symmetric project-scope
assertion; a comment documents the empty-value expansion choice.

Addresses review-panel follow-ups (python-architect, devx-ux-expert,
cli-logging-expert, test-coverage-expert, supply-chain-security-expert).

Co-authored-by: Copilot App <[email protected]>

* docs(mcp): record Codex env_vars after #3406; name exit on conflict

The MCP variable compatibility inventory was written before #3406 landed
on main and still said Codex project scope writes resolved env values.
Codex project and user scope are now separate rows, and the known-gap
lists name Codex user scope. The producer page no longer uses Codex
project env as the example of a harness needing literal values. The
consumer page says a preserved Claude entry ends the install with an
error naming each field and its reference. The CHANGELOG entry is
trimmed to one line ending in (#3377).

Addresses review-panel follow-ups (doc-writer, devx-ux-expert).

Co-authored-by: Copilot App <[email protected]>

---------

Co-authored-by: danielmeppiel <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/mcp-config MCP server configuration depth, transports, variable resolution. triage/recommended Automated advice completed; not human scope approval. type/bug Something does not work as documented.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Codex: stdio MCP env ${VAR} written as plaintext into .codex/config.toml instead of using env_vars

4 participants