Repository navigation
fix(codex): forward ${VAR} stdio env values with env_vars instead of writing them - #3406
Conversation
There was a problem hiding this comment.
🟡 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
| if forwarded_env: | ||
| stdio_config["env_vars"] = forwarded_env | ||
| stdio_config["env"] = written_env |
There was a problem hiding this comment.
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.
| if forwarded_env: | ||
| stdio_config["env_vars"] = forwarded_env | ||
| stdio_config["env"] = written_env | ||
| self._merge_extra(stdio_config, server_info) |
There was a problem hiding this comment.
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.
| 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()) |
There was a problem hiding this comment.
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.
e949407 to
9acc197
Compare
…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.
|
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. |
# Conflicts: # CHANGELOG.md
…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]>
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]>
Co-authored-by: Copilot <[email protected]>
APM Review Panel:
|
| 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
cwdafterargs); exact TOML bytes pinned. (f709243) - Reverted the
env_varspassthrough reservation that changed user-scope output; at project scope the modeledenv_varsstill wins overextra. (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
argsreference to a forwarded variable is still resolved. (63dd531) - Binary e2e for
extra.env_varsat 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_varsin 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_varsin_HARNESS_EXTRA_ALIASES-- changes passthrough policy and user-scope Codex output for everyextra.env_varsmanifest; 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.
Co-authored-by: Copilot App <[email protected]>
c3c86a8
into
microsoft:main
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]>
…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]>
* 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]>


Description
A self-defined stdio dependency that declares a secret as
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 throughenv_vars, the waybearer_token_env_varis 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):envvalue written as exactly${VAR}or${env:VAR}under the keyVARbecomesenv_vars = ["VAR"]. It is not resolved, prompted for or written, whether or notVARis set.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 suggestsKEY: ${KEY}.cwd, remote header fields and unrelated entries keep their current output.env_varsis emitted before the[env]sub table so tomlkit cannot nest it.env_varsonly 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 committedconfig.tomlshould 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,~/.codexor$CODEX_HOME) the output is unchanged, and the legacy matcher never applies there.docs/src/content/docs/consumer/install-mcp-servers.mdand the packagedapm-usageguidance (packages/apm-guide/.apm/skills/apm-usage/dependencies.md) describe this.Type of change
Testing
Installed CLI,
tests/integration/test_codex_mcp_env_vars_e2e.py, with synthetic values and an isolatedHOMEandCODEX_HOME:test_references_are_forwarded_for_set_and_unset_variables(both spellings, set and unset; no secret inconfig.toml,apm.lock.yamlor output)test_unforwardable_references_warn_with_names_only,test_embedded_reference_is_resolved_and_named_in_warningtest_user_scope_install_still_resolves_values(matches the output ofmainfor 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 legacyconfig.tomlis written by the test, so these run in CI)mainbuild whenAPM_LEGACY_BINARY_PATHis set, and skip otherwise. Both pass locally.tests/integration/test_mcp_stdio_env_resolution_e2e.pyasserted the old Codex contract, so it is split: the Claude case is unchanged, and the Codex case assertsenv_varsand no secret.Unit tests in
tests/unit/test_codex_adapter_phase3.py(TestForwardedStdioEnv,TestForwardedStdioEnvScope) andtests/unit/install/test_mcp_ownership.pycover the split, both scopes, the warning, baseline rendering without duplicate warnings, and the legacy upgrade path.With
main'ssrc, 13 unit tests and 8 integration tests fail; all pass with this change. Locally:tests/unit/install,tests/unit/adapters,test_codex_adapter_phase3.pyandtest_global_mcp_scope.pygive 3409 passed; the two integration files give 13 passed;ruff check,ruff format --check,lint-architecture-boundaries.shandlint-auth-signals.share clean.Spec conformance (OpenAPM v0.1)