Skip to content

feat(mcp): support env-backed HTTP headers for Codex remotes - #1761

Closed
dijdzv wants to merge 1 commit into
microsoft:mainfrom
dijdzv:codex/env-http-headers
Closed

dijdzv wants to merge 1 commit into
microsoft:mainfrom
dijdzv:codex/env-http-headers

Conversation

@dijdzv

@dijdzv dijdzv commented Jun 12, 2026 •

Copy link
Copy Markdown

TL;DR

Add env_headers support for remote MCP dependencies and map it to Codex CLI's env_http_headers.

This lets APM generate Codex remote MCP config that references environment variables for HTTP header values, instead of writing secret values into .codex/config.toml. Existing static headers behavior is preserved as Codex http_headers.

Problem

APM already supports static HTTP headers for remote MCP servers, but Codex has a separate runtime-env header surface:

  • static values: http_headers
  • environment-backed values: env_http_headers

Without an APM manifest field for the second shape, package authors cannot express "write this header name, but read its value from this environment variable at runtime" for Codex remotes.

Approach

Introduce a generic MCP dependency field:

env_headers:
  Authorization: MCP_AUTH_TOKEN

Then map it to Codex config:

[mcp_servers.my-server.env_http_headers]
Authorization = "MCP_AUTH_TOKEN"

Static headers continue to map to Codex http_headers.

Implementation

  • MCPDependency now parses, serializes, displays, and validates env_headers.
  • MCPIntegrator carries env_headers through self-defined remote generation and overlay merging.
  • The Codex adapter emits env_http_headers for remote MCP config.
  • Overlay merging is deterministic: repeated installs replace existing entries for the same header name instead of appending duplicates.
  • The Codex adapter accepts both list and dict internal shapes and normalizes header names to strings.
  • Docs cover the new manifest field and the generated Codex output.

Validation

uv run --extra dev pytest tests/unit/test_mcp_overlays.py tests/unit/test_codex_adapter_phase3.py tests/unit/integration/test_mcp_integrator.py tests/integration/test_mcp_targets_gating_e2e.py -q

Result: 283 passed in 1.63s

uv run --extra dev ruff check src/ tests/

Result: All checks passed!

uv run --extra dev ruff format --check src/ tests/

Result: 1256 files already formatted

Smoke tested this branch's APM against a temporary project with a streamable HTTP MCP entry using env_headers:

uv run --project /home/dd/github/apm apm install --target codex --only mcp --no-audit

The generated Codex config contained:

[mcp_servers.remote-auth-smoke.env_http_headers]
Authorization = "MCP_AUTH_TOKEN"

codex exec loaded the generated config and successfully called the remote MCP tool.

How to test

  1. Create a project with a streamable HTTP MCP dependency that declares env_headers.
  2. Run apm install --target codex --only mcp.
  3. Confirm .codex/config.toml contains env_http_headers.
  4. Set the referenced environment variable and run codex exec with that Codex config.

Copilot AI review requested due to automatic review settings June 12, 2026 21:04

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.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds support for “env-backed HTTP headers” (env_headers) across the MCP dependency model, integrator overlays, and Codex target output so secrets can be provided at runtime via environment variables instead of being written into config.

Changes:

  • Introduces MCPDependency.env_headers with validation and (de)serialization support.
  • Propagates env_headers through MCPIntegrator remote info and overlay merging.
  • Maps remote env_headers to Codex env_http_headers, with unit + E2E tests and documentation updates.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tests/unit/test_mcp_overlays.py Adds unit coverage for env_headers parsing/serialization, validation, and overlay behavior.
tests/unit/test_codex_adapter_phase3.py Verifies Codex adapter maps remote env_headers into env_http_headers (list + dict shapes).
tests/integration/test_mcp_targets_gating_e2e.py Adds E2E coverage ensuring Codex writes env_http_headers into .codex/config.toml.
src/apm_cli/models/dependency/mcp.py Adds env_headers field, validation for CRLF + env var name format, and dict roundtripping.
src/apm_cli/integration/mcp_integrator.py Emits env_headers into remotes and merges overlays into cached server info.
src/apm_cli/adapters/client/codex.py Converts remote env_headers to Codex env_http_headers.
docs/src/content/docs/reference/manifest-schema.md Documents env_headers schema and expected Codex output.
docs/src/content/docs/producer/author-primitives/mcp-as-primitive.md Adds producer-facing docs + examples for env_headers.
docs/src/content/docs/consumer/install-mcp-servers.md Adds consumer install docs describing native env-header binding usage.

Comment thread src/apm_cli/adapters/client/codex.py Resolved
Comment thread src/apm_cli/models/dependency/mcp.py Resolved
@dijdzv dijdzv changed the title add(mcp): map environment-backed remote headers to Codex feat(mcp): support env-backed HTTP headers for Codex remotes Jun 12, 2026
@dijdzv

dijdzv commented Jun 12, 2026

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

@dijdzv
dijdzv force-pushed the codex/env-http-headers branch from 60c1efe to 58aeebf Compare June 12, 2026 21:10
@dijdzv
dijdzv requested a review from Copilot June 12, 2026 21:20

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.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.

Comment thread src/apm_cli/adapters/client/codex.py Resolved
@dijdzv
dijdzv force-pushed the codex/env-http-headers branch from 58aeebf to 222016a Compare June 12, 2026 21:24
@dijdzv
dijdzv requested a review from Copilot June 12, 2026 21:35

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.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.

Comment thread src/apm_cli/models/dependency/mcp.py Resolved
Comment thread src/apm_cli/adapters/client/codex.py Resolved
Codex supports remote MCP headers whose values are read from environment variables at runtime, but APM only emitted static HTTP headers. This forced secret-bearing headers to be resolved or stored during install. Add an env_headers MCP manifest field and map it to Codex env_http_headers while preserving existing static header behavior.

Cover self-defined remotes, overlay merging, Codex formatting for list and dict shapes, and the end-to-end Codex config write path.

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.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/apm_cli/models/dependency/mcp.py:232

  • env_headers validation correctly rejects empty / whitespace-only header names, but static headers validation still allows an empty header name (it only checks CR/LF). That can silently drop user intent later (adapters typically ignore empty names) and makes validation inconsistent across the two header surfaces. Consider rejecting empty / whitespace-only header names for headers as well.
        if self.env_headers:
            for k, v in self.env_headers.items():
                k_str = str(k) if k is not None else ""
                v_str = str(v) if v is not None else ""
                if not k_str.strip():

@sergio-sisternes-epam

Copy link
Copy Markdown
Contributor

APM Review Panel: ship_with_followups

PR #1761 adds env_headers manifest field so Codex MCP servers bind auth headers to env vars at runtime, keeping secrets out of config files.

cc dijdzv Daniel Meppiel (@danielmeppiel) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

This is a clean, community-contributed feature that directly addresses a real Codex auth pain point without introducing secret-handling risk at the APM layer. The auth-expert confirms APM never resolves the secret value -- it only emits the env-var name into config.toml for Codex to dereference at server-start. The supply-chain-security-expert's finding on header-name validation from registry responses is the highest-signal defensive improvement: header names sourced from remote registries bypass the local validate() path and land in TOML output without character-class enforcement. While the TOML library will quote keys correctly, defense-in-depth at the ingestion boundary is warranted and should ship in this PR or immediately after.

The test-coverage-expert flags a missing integration test for the non-Codex boundary: when env_headers is declared but the target adapter cannot honor it, no assertion proves the key does not leak into cursor/copilot JSON. The evidence block marks this as outcome:missing on a secure-by-default surface, which elevates it above opinion-tier. Combined with the devx-ux-expert's recommendation to emit a diagnostic on that same boundary, this is a coherent gap -- the silent-ignore path has neither a user-facing warning nor an automated regression trap. I side with adding the test; the warning can follow.

The doc-writer's blocking-severity CHANGELOG finding is procedurally correct -- every new manifest field gets an [Unreleased] entry -- but it is metadata compliance, not a merge-blocking defect. It should be folded before merge as a minor commit, not gate the PR.

Dissent. No direct panelist-vs-panelist disagreement. The doc-writer rated the missing CHANGELOG entry as blocking while routing context correctly notes it is metadata compliance rather than a functional merge blocker. I side with treating it as a must-fix-before-merge nit (one commit), not a reason to request-changes the PR. The test-coverage-expert's missing-test finding on the non-Codex boundary (outcome:missing, secure-by-default) outweighs any recommended-tier opinion finding per the evidence-weighting contract.

Aligned with: Portable by manifest (env_headers declared in apm.yml, translated per-target by adapter layer); Secure by default (APM never reads the secret value -- but non-Codex regression test gap means the boundary lacks an automated guard); Pragmatic as npm (mirrors how npm scripts consume env vars -- familiar to the target audience, zero new concepts).

Growth signal. Story angle: "Install authenticated MCP servers on Codex with zero secrets in your repo." This is a concrete conversion hook for Codex early-adopters searching for MCP auth patterns. CHANGELOG entry should lead with the user benefit.

Panel summary

Persona B R N Takeaway
Python Architect 0 1 2 Solid feature addition; env_headers normalization logic is duplicated across codex adapter and mcp_integrator -- extract a shared helper to keep the dual-shape parsing in one place.
CLI Logging Expert 0 1 2 No blocking output regressions. Minor nits on warning message clarity and missing verbose-mode breadcrumbs for the env_headers resolution path.
DevX UX Expert 0 2 2 The env_headers field is a clean, familiar pattern. Main UX gap: silent ignoring on non-Codex targets -- users will not know their headers are ineffective until runtime failures.
Supply Chain Security Expert 0 1 1 Feature correctly defers secret resolution to Codex runtime. Header names from registry responses bypass McpDependency.validate() before TOML serialization in codex.py.
OSS Growth Hacker 0 2 1 Strong adoption play: env_headers directly addresses the Codex auth-header pain point. Docs present. Two recommended improvements to maximise discoverability.
Auth Expert 0 0 2 Auth changes are sound. AuthCacheKey uses empty-string sentinel correctly. The env_headers feature never resolves secret values at APM runtime.
Doc Writer 1 2 1 env_headers docs are largely accurate and well-placed. Key gaps: no CHANGELOG [Unreleased] entry, targets-matrix Codex section omits env_http_headers shape note.
Test Coverage Expert 0 1 0 Integration test covers full Codex env_headers flow; unit tests cover validation/normalization thoroughly. Recommended: add regression trap for non-Codex target boundary.

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

Top 5 follow-ups

  1. [Test Coverage Expert] Add integration test asserting env_http_headers key does not appear in non-Codex target output -- Missing test on a secure-by-default surface (outcome:missing) -- the silent-ignore path has no regression trap. Highest-signal gap.
  2. [Supply Chain Security Expert] Validate header names from registry responses against RFC 7230 tchar set before TOML insertion -- Remote-sourced header names bypass validate(); defense-in-depth requires ingestion-point validation.
  3. [Doc Writer] Add CHANGELOG [Unreleased] entry naming the user benefit of env_headers -- Release-notes contract requires it; fold the growth-hacker's benefit-first wording.
  4. [DevX UX Expert] Emit a one-line diagnostic when env_headers is declared on a target that cannot honor it -- Silent ignoring causes opaque 401s; users deserve a clear signal at install time.
  5. [Python Architect] Extract shared normalize_name_value_pairs helper to deduplicate codex.py and mcp_integrator.py -- Identical dual-shape parsing in two files; single-owner contract prevents future drift.

Architecture

classDiagram
    direction LR
    class MCPDependency {
      <<ValueObject>>
      +name: str
      +headers: dict | None
      +env_headers: dict | None
      +from_dict(d) MCPDependency
      +validate()
      +display() str
    }
    class MCPClientAdapter {
      <<Abstract>>
      +install_server()
      +_format_server_config()
    }
    class CodexClientAdapter {
      <<ConcreteAdapter>>
      +_format_server_config()
      +_determine_config_key()
    }
    class MCPIntegrator {
      +_build_self_defined_info()
      +_apply_overlay()
      +uninstall()
    }
    MCPClientAdapter <|-- CodexClientAdapter
    MCPIntegrator ..> MCPDependency : reads
    CodexClientAdapter ..> MCPDependency : reads
    MCPIntegrator ..> MCPClientAdapter : delegates install
    note for MCPDependency "env_headers added: header->env_var map"
    note for CodexClientAdapter "Emits env_http_headers in config.toml"
    classDef touched fill:#fff3b0,stroke:#d47600
    class MCPDependency:::touched
    class CodexClientAdapter:::touched
    class MCPIntegrator:::touched
Loading
flowchart TD
    A["apm install --mcp"] --> B["MCPDependency.from_dict()"]
    B --> C{"env_headers present?"}
    C -->|Yes| D["validate(): regex check env var names"]
    C -->|No| E["skip"]
    D --> F["MCPIntegrator._build_self_defined_info()"]
    F --> G["Emit env_headers as list of name/env dicts"]
    G --> H["MCPIntegrator._apply_overlay()"]
    H --> I{"existing shape?"}
    I -->|list| J["Parse list, merge by name, normalize to list"]
    I -->|dict| K["Parse dict, merge by name, normalize to list"]
    J --> L["CodexClientAdapter._format_server_config()"]
    K --> L
    L --> M{"raw_env_headers shape?"}
    M -->|dict| N["Iterate items"]
    M -->|list| O["Iterate dicts with name/env keys"]
    N --> P["[FS] Write env_http_headers to config.toml"]
    O --> P
Loading

Recommendation

Ship after folding the CHANGELOG entry (one commit). The remaining follow-ups -- non-Codex regression test, header-name validation from registry responses, silent-ignore diagnostic, and helper extraction -- are all recommended improvements that can land as fast-follows without blocking this community contribution. The feature is architecturally sound, auth-safe, and directly addresses a real Codex user pain point.


Full per-persona findings

Python Architect

  • [recommended] Duplicate dict/list env_headers normalization logic in codex.py and mcp_integrator.py at src/apm_cli/adapters/client/codex.py:276
    Both _format_server_config in codex.py and _apply_overlay in mcp_integrator.py independently handle env_headers as either a list of {name, env} dicts or a plain dict, with identical None-guard, isinstance branching, and str() coercion. A small shared helper would keep the parsing contract in one place.
    Suggested: Extract normalize_name_value_pairs helper into mcp.py or a shared utils module.
  • [nit] identity.py extraction is unrelated to env_headers feature at src/apm_cli/models/dependency/identity.py:1
    The new identity.py module extraction is orthogonal to env_headers. Splitting it would keep the branch focused and simplify revert if needed.
  • [nit] Overlay merge always normalizes to list shape even when source was dict at src/apm_cli/integration/mcp_integrator.py:413
    Round-trip changes the config shape. Document that canonical persisted shape is always [{name, env}] so future readers know this is intentional, not lossy.

CLI Logging Expert

  • [recommended] env_headers resolution path is silent -- no verbose breadcrumb at src/apm_cli/integration/mcp_integrator.py
    When --verbose is active, the install path for env_headers adds no diagnostic output, making it invisible in verbose mode. Progressive disclosure: default is rightly silent, but verbose should show resolved header count.
    Suggested: Add a verbose-only log line after env_headers are written into the MCP config.
  • [nit] Unknown-keys warning in from_dict should lead with the dependency name at src/apm_cli/models/dependency/mcp.py
    Current format leads with the type. Better to lead with the dependency name for scanability in multi-dep installs.
    Suggested: Reword to lead with name: "{name}: unknown MCP key(s) ignored: {keys}".
  • [nit] apm.yml load failure warning is too long for default output at src/apm_cli/deps/plugin_parser.py
    The message includes the full exception in default output. In non-verbose mode the user cannot act on a raw exception. Lead with outcome; put exc behind --verbose.

DevX UX Expert

  • [recommended] Emit a diagnostic when env_headers is declared but the target adapter cannot honor it
    Silent ignoring violates the failure-mode-is-the-product principle. A user who declares env_headers expecting auth to flow to VS Code or Claude Code will get opaque 401s with no hint.
    Suggested: "env_headers on '{name}' ignored: {target} does not support environment-backed headers yet"
  • [recommended] Error messages expose validator internals rather than actionable guidance
    The invalid-env-var error should hint that the user likely pasted a secret instead of an env var name.
    Suggested: Add: "Did you mean to use an environment variable name (e.g. MY_API_KEY) rather than a literal value?"
  • [nit] display() uses Python dict repr instead of user-friendly rendering
    env_headers={'X-Api-Key': 'MCP_API_KEY'} reads like a debug dump. Consider rendering as env_headers: X-Api-Key=$MCP_API_KEY.
  • [nit] Field name env_headers could be confused with headers without inline docs
    Ensure the manifest schema reference explains the distinction clearly.

Supply Chain Security Expert

  • [recommended] Header names from registry server_info bypass validate() before TOML output in codex.py at src/apm_cli/adapters/client/codex.py
    Header names read from remote registry responses are written to env_http_headers without CR/LF or special-character validation. Defense-in-depth requires validating at the ingestion point.
    Suggested: Add shared header-name validation helper and call it in the codex adapter before inserting into env_http_headers.
  • [nit] Consider restricting header names to RFC 7230 tchar set
    Current validation only rejects CR/LF. RFC 7230 token chars would be a tighter, correct constraint.
    Suggested: Regex: ^[A-Za-z0-9!#$%&'*+\-.^_|~]+$` for header name validation.

OSS Growth Hacker

  • [recommended] Add a one-liner Codex example in quickstart or first-package guide
    Codex users will search for "codex mcp auth header". The current example lives deep in the manifest-schema reference. A tip callout near the top of install-mcp-servers.md converts Codex users at the top of funnel.
  • [recommended] CHANGELOG entry should name the user benefit, not just the field
    Release notes are a conversion surface. Lead with: "Codex MCP servers can now pull auth headers from env vars at runtime via env_headers, keeping secrets out of config files."
  • [nit] Docs should clarify that other adapters may support env_headers in the future
    Add one sentence: "Other adapters may support env_headers in the future; unsupported targets safely ignore the field."

Auth Expert

  • [nit] _SECRET_RE bare-PAT branch comment could note all five prefix letters at src/apm_cli/core/auth.py
    Not harmful -- better to over-redact. Comment note only for future maintainers.
  • [nit] allow_external_fallback lacks docstring explaining intended callers at src/apm_cli/core/auth.py
    Add brief comment about when False is appropriate.

Doc Writer

  • [blocking] No CHANGELOG [Unreleased] entry for env_headers / env_http_headers support
    The [Unreleased] block in CHANGELOG.md is empty. PR feat(mcp): support env-backed HTTP headers for Codex remotes #1761 introduces a new manifest field and a new Codex-specific config translation. The project consistently logs new fields in [Unreleased]. Omitting it breaks the release-notes contract.
    Suggested: Add: "- env_headers field on remote MCP server entries: targets with native env-header support (Codex env_http_headers) bind the header value to the named environment variable at server-start. (feat(mcp): support env-backed HTTP headers for Codex remotes #1761)"
  • [recommended] targets-matrix Codex section omits env_http_headers MCP shape note
    The targets-matrix Codex section is silent on env_http_headers, leaving no discoverable canonical statement that env_headers translates to env_http_headers.
  • [recommended] env_headers field description in mcp-as-primitive.md uses "such as" implying other current targets support it
    If Codex is the only current target, "such as Codex" is misleading. Change to: "Currently honored by Codex (env_http_headers); other targets silently ignore the field."
  • [nit] Secrets section prose in mcp-as-primitive.md does not mention env_headers pattern
    Extend summary sentence to note env_headers as the zero-secret variant.

Test Coverage Expert

  • [recommended] No test asserts env_headers is silently dropped for non-Codex targets
    When a streamable-http dep WITH env_headers is installed to cursor/copilot targets, no test asserts resulting JSON lacks env_http_headers key. grep found no such assertion.
    Proof (missing): tests/integration/test_mcp_targets_gating_e2e.py::test_non_codex_targets_omit_env_http_headers -- proves: env_headers in apm.yml does not leak runtime-secret binding keys into non-Codex config files [secure-by-default, multi-harness-support]
    assert 'env_http_headers' not in cursor_data['mcpServers']['e2e-env']

Performance Expert -- inactive

No performance-sensitive surfaces touched; PR touches only MCP config generation. No changes to cache/, deps/, install/phases/, install/pipeline.py, install/resolve.py, or scripts/perf/.

This panel is advisory. It does not block merge. Re-apply the
panel-review label after addressing feedback to re-run.

@sergio-sisternes-epam Sergio Sisternes (sergio-sisternes-epam) removed the panel-review Request an advisory PR review; consumed after review. Not human approval or a merge gate. label Aug 18, 2026
@danielmeppiel

Copy link
Copy Markdown
Collaborator

Thank you for the Codex implementation and the working example. I rechecked the issue references: #2606 is related, but it tracks per-dependency MCP targets, not this PR's new env_headers contract. I could not verify an issue tracking the scope of this change.

Closing for now under our contribution rules. With a small maintainer team and limited review capacity, we need a matching issue and supported scope before substantive PR review. Please open a short issue for the environment-backed header proposal, or link an existing matching issue if I missed it. A responsible maintainer can then confirm the bounded scope and review contact, and we can reopen this PR when those are in place.

This is an intake decision, not a judgment of the implementation. The existing commits, discussion and credit are preserved; there is no need to discard or redo the work.

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.

4 participants