Repository navigation
Conversation
There was a problem hiding this comment.
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_headerswith validation and (de)serialization support. - Propagates
env_headersthroughMCPIntegratorremote info and overlay merging. - Maps remote
env_headersto Codexenv_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. |
|
@microsoft-github-policy-service agree |
60c1efe to
58aeebf
Compare
58aeebf to
222016a
Compare
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.
222016a to
a2412fb
Compare
There was a problem hiding this comment.
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_headersvalidation correctly rejects empty / whitespace-only header names, but staticheadersvalidation 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 forheadersas 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():
APM Review Panel:
|
| 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
- [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.
- [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.
- [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.
- [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.
- [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
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
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_configin codex.py and_apply_overlayin 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: Extractnormalize_name_value_pairshelper 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 asenv_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_headersfield on remote MCP server entries: targets with native env-header support (Codexenv_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.
|
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 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. |
TL;DR
Add
env_headerssupport for remote MCP dependencies and map it to Codex CLI'senv_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 staticheadersbehavior is preserved as Codexhttp_headers.Problem
APM already supports static HTTP headers for remote MCP servers, but Codex has a separate runtime-env header surface:
http_headersenv_http_headersWithout 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:
Then map it to Codex config:
Static
headerscontinue to map to Codexhttp_headers.Implementation
MCPDependencynow parses, serializes, displays, and validatesenv_headers.MCPIntegratorcarriesenv_headersthrough self-defined remote generation and overlay merging.env_http_headersfor remote MCP config.Validation
Result:
283 passed in 1.63sResult:
All checks passed!Result:
1256 files already formattedSmoke tested this branch's APM against a temporary project with a streamable HTTP MCP entry using
env_headers:The generated Codex config contained:
codex execloaded the generated config and successfully called the remote MCP tool.How to test
env_headers.apm install --target codex --only mcp..codex/config.tomlcontainsenv_http_headers.codex execwith that Codex config.