Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-safe-outputs-dynamic-input-mcp-container.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions .github/skills/agentic-workflows/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Load these files from `github/gh-aw` (they are not available locally).
- `.github/aw/github-agentic-workflows.md`
- `.github/aw/github-mcp-server.md`
- `.github/aw/instructions.md`
- `.github/aw/linter-workflows.md`
- `.github/aw/llms.md`
- `.github/aw/loop.md`
- `.github/aw/lsp.md`
Expand Down
33 changes: 33 additions & 0 deletions actions/setup/js/safe_outputs_config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,26 @@ const { ERR_SYSTEM } = require("./error_codes.cjs");
const fs = require("fs");
const path = require("path");

/**
* Collect the names of any ${GH_AW_INPUT_*} placeholders that are unresolved
* (i.e. the corresponding environment variable is absent from process.env).
* Returns an empty array when all placeholders are resolved.
* @param {string} rawJson - The raw JSON string before placeholder substitution
* @returns {string[]}
*/
function collectUnresolvedInputPlaceholders(rawJson) {
const unresolved = [];
const pattern = /\$\{(GH_AW_INPUT_[A-Z0-9_]+)\}/g;
let match;
while ((match = pattern.exec(rawJson)) !== null) {
const envName = match[1];
if (process.env[envName] === undefined && !unresolved.includes(envName)) {
unresolved.push(envName);
}
}
return unresolved;
}

function resolveEnvPlaceholders(value) {
if (Array.isArray(value)) {
return value.map(resolveEnvPlaceholders);
Expand Down Expand Up @@ -45,6 +65,19 @@ function loadConfig(server) {
server.debug(`Config file content length: ${configFileContent.length} characters`);
// Don't log raw content to avoid exposing sensitive configuration data
server.debug(`Config file read successfully, attempting to parse JSON`);
// Warn about any GH_AW_INPUT_* placeholders that cannot be resolved before substitution.
// This should not happen when the workflow is compiled correctly (the compiler ensures these
// env vars are in the MCP gateway step env and the docker -e allowlist), but if it does the
// error will surface later as a cryptic "No remote refs available for merge-base calculation"
Comment thread
github-actions[bot] marked this conversation as resolved.
// rather than pointing at the root cause.
const unresolvedInputs = collectUnresolvedInputPlaceholders(configFileContent);
if (unresolvedInputs.length > 0) {
Comment thread
github-actions[bot] marked this conversation as resolved.
const varList = unresolvedInputs.join(", ");
const unresolvedMsg = `ERR_CONFIG: Unresolved workflow input placeholder(s) in safe-outputs config: ${varList}. The values were not passed to the MCP container. Verify that the workflow was compiled with a version that forwards GH_AW_INPUT_* to the container env.`;
server.error(unresolvedMsg);
console.error(`[safe_outputs_config] ERR_CONFIG: Unresolved workflow input placeholder(s): ${varList}`);
Comment thread
github-actions[bot] marked this conversation as resolved.
throw new Error(unresolvedMsg);
}
safeOutputsConfigRaw = resolveEnvPlaceholders(JSON.parse(configFileContent));
server.debug(`Successfully parsed config from file with ${Object.keys(safeOutputsConfigRaw).length} configuration keys`);
} else {
Expand Down
61 changes: 61 additions & 0 deletions actions/setup/js/safe_outputs_config.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ describe("safe_outputs_config", () => {
// Create a mock server with debug function
mockServer = {
debug: vi.fn(),
error: vi.fn(),
};

// Use unique paths for each test
Expand Down Expand Up @@ -216,5 +217,65 @@ describe("safe_outputs_config", () => {
expect(debugOutput).toContain("***REDACTED***");
expect(debugOutput).not.toContain("runtime-project-token");
});

it("should emit exactly one diagnostic when a GH_AW_INPUT_* placeholder is duplicated and unresolved", () => {
const configDir = path.dirname(testConfigPath);
fs.mkdirSync(configDir, { recursive: true });

// ${GH_AW_INPUT_FOO} appears twice but the env var is not set
fs.writeFileSync(
testConfigPath,
JSON.stringify({
"create-pull-request": {
"base-branch": "${GH_AW_INPUT_FOO}",
"head-branch": "${GH_AW_INPUT_FOO}",
},
})
);

const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
try {
loadConfig(mockServer);

// Deduplication: only one diagnostic per unique unresolved var
const unresolvedPlaceholderErrors = consoleSpy.mock.calls.filter(call => String(call[0]).includes("GH_AW_INPUT_FOO"));
expect(unresolvedPlaceholderErrors).toHaveLength(1);

const errorOutput = mockServer.error.mock.calls.map(call => String(call[0])).join("\n");
expect(errorOutput).toContain("GH_AW_INPUT_FOO");
expect(errorOutput).toContain("Unresolved workflow input placeholder");
} finally {
consoleSpy.mockRestore();
}
});

it("should emit no diagnostic when all GH_AW_INPUT_* placeholders are resolved", () => {
const configDir = path.dirname(testConfigPath);
fs.mkdirSync(configDir, { recursive: true });
process.env.GH_AW_INPUT_BASE_BRANCH = "develop";

fs.writeFileSync(
testConfigPath,
JSON.stringify({
"create-pull-request": {
"base-branch": "${GH_AW_INPUT_BASE_BRANCH}",
},
})
);

const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
try {
loadConfig(mockServer);

const inputPlaceholderErrors = consoleSpy.mock.calls.filter(call => String(call[0]).includes("GH_AW_INPUT_"));
expect(inputPlaceholderErrors).toHaveLength(0);

const errorOutput = mockServer.error.mock.calls.map(call => String(call[0])).join("\n");
expect(errorOutput).not.toContain("Unresolved workflow input placeholder");
} finally {
consoleSpy.mockRestore();
delete process.env.GH_AW_INPUT_BASE_BRANCH;
}
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# ADR-48099: Forward GH_AW_INPUT_* Vars to MCP Gateway Container

**Date**: 2026-07-26
**Status**: Accepted
**Deciders**: pelikhan, copilot-swe-agent

---

### Context

Since v0.80.0, the safe-outputs MCP server runs inside a Docker container with a filtered `-e` allowlist. When a workflow author uses a dynamic safe-outputs field — for example `base-branch: ${{ inputs.base_branch }}` — the compiler writes a `${GH_AW_INPUT_BASE_BRANCH}` shell-style placeholder into the container's `config.json`. However, because `GH_AW_INPUT_*` variables were never included in the docker run `-e` allowlist, and were not emitted in the "Start MCP Gateway" step `env:` block, those placeholders remained unresolved at runtime inside the container. This caused `create_pull_request` (and other safe-outputs handlers) to fail with the cryptic error "No remote refs available for merge-base calculation" — with no indication that an unresolved placeholder was the root cause.

### Decision

We will extend the workflow compiler to extract all `GH_AW_INPUT_*` environment variable names referenced in the safe-outputs config, emit them in the "Start MCP Gateway" step `env:` block (so the runner process holds the resolved values), and append a `-e GH_AW_INPUT_*` flag for each one in the `docker run` command (so the container inherits those values). Additionally, we will add a `collectUnresolvedInputPlaceholders()` diagnostic in the MCP server's config loader to surface any remaining unresolved placeholders with a clear error message instead of a silent runtime failure.

### Alternatives Considered

#### Alternative 1: Pass All Runner Environment Variables to the Container

Instead of selectively forwarding only `GH_AW_INPUT_*` vars, forward the entire runner environment into the container via `--env-file` or `--env-host`. This would have resolved the issue without any compiler changes. It was rejected because the filtered `-e` allowlist exists specifically to limit what the container can observe — passing the full runner env would expose secrets, tokens, and other runner-level vars to the containerized MCP server, defeating the security boundary that the allowlist enforces.

#### Alternative 2: Resolve Placeholders at Compile Time

Substitute `${{ inputs.* }}` values directly into `config.json` at compile time so no placeholder survives to runtime. This was rejected because workflow input values are not known at compile time — they are resolved by GitHub Actions at workflow-dispatch time. Embedding them statically would require a separate "late-compilation" step at workflow startup, and would force config.json to be regenerated per-run, complicating the current architecture where `config.json` is written once at compile time as a static artifact.

#### Alternative 3: Redesign Config Using a Runtime-Resolved Mechanism

Replace the `${GH_AW_INPUT_*}` placeholder pattern in `config.json` with a runtime mechanism (e.g., the container reads vars directly from a mounted secrets file or a well-known env var namespace). This would eliminate the coupling between safe-outputs config parsing and MCP gateway code generation. It was rejected because it would require a significant redesign of the safe-outputs config system and a coordinated breaking change to the MCP server's config loader — too high a cost for a targeted bug fix.

### Consequences

#### Positive
- Dynamic safe-outputs fields like `base-branch: ${{ inputs.base_branch }}` now work correctly in the containerized MCP server for all safe-outputs handlers, not just `create-pull-request`.
- Unresolved placeholder errors now surface with an explicit, actionable error message (`ERR_CONFIG: Unresolved workflow input placeholder(s): ...`) rather than a cryptic merge-base failure.
- The fix is compiler-driven and backward-compatible: existing workflows without dynamic safe-outputs fields are unaffected (the new code paths only activate when `GH_AW_INPUT_*` vars are detected in the safe-outputs config).

#### Negative
- Each `${{ inputs.* }}` reference in a safe-outputs config now results in one additional env var forwarded to the MCP gateway container, incrementally widening the container's visible environment beyond what the original allowlist intended.
- The compiler now couples safe-outputs config parsing (`extractSafeOutputsInputEnvVars`) to MCP gateway step generation (`generateMCPGatewaySetup`), increasing the surface area that must be updated if either subsystem changes independently.

#### Neutral
- Two new test cases validate the fix: an update to the existing dynamic-allowed-repos test (asserts `GH_AW_INPUT_*` appears in both step env blocks and the docker run command) and a new regression test `TestSafeOutputsDynamicBaseBranchPassedToMCPContainer` covering the exact failure scenario.
- The `appendMCPGatewaySafeOutputsInputEnvFlags` function is ordered after `appendMCPGatewayConditionalEnvFlags` in the docker run command assembly, which means `GH_AW_INPUT_*` flags appear after standard conditional flags — this ordering has no functional impact but may affect readability of generated workflow YAML.

---

*ADR created by [adr-writer agent]. Review and finalize before changing status from Draft to Accepted.*
1 change: 1 addition & 0 deletions pkg/cli/data/agentic_workflows_fallback_aw_files.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"github-agentic-workflows.md",
"github-mcp-server.md",
"instructions.md",
"linter-workflows.md",
"llms.md",
"loop.md",
"lsp.md",
Expand Down
32 changes: 31 additions & 1 deletion pkg/workflow/mcp_renderer_builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com/github/gh-aw/pkg/constants"
"github.com/github/gh-aw/pkg/logger"
"github.com/github/gh-aw/pkg/sliceutil"
)

var mcpRendererBuiltinLog = logger.New("workflow:mcp_renderer_builtin")
Expand Down Expand Up @@ -98,7 +99,24 @@ func (r *MCPConfigRendererUnified) renderSafeOutputsTOML(yaml *strings.Builder,
yaml.WriteString(" args = [\"-w\", \"$GITHUB_WORKSPACE\"]\n")
yaml.WriteString(" entrypoint = \"sh\"\n")
yaml.WriteString(" entrypointArgs = [\"-c\", \"sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh\"]\n")
yaml.WriteString(" env_vars = [\"DEBUG\", \"DEFAULT_BRANCH\", \"GH_AW_ASSETS_ALLOWED_EXTS\", \"GH_AW_ASSETS_BRANCH\", \"GH_AW_ASSETS_MAX_SIZE_KB\", \"GH_AW_MCP_LOG_DIR\", \"GH_AW_SAFE_OUTPUTS\", \"GH_AW_SAFE_OUTPUTS_CONFIG_PATH\", \"GH_AW_SAFE_OUTPUTS_TOOLS_PATH\", \"GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST\", \"GITHUB_REPOSITORY\", \"GITHUB_SHA\", \"GITHUB_TOKEN\", \"GITHUB_WORKSPACE\", \"RUNNER_TEMP\"]\n")

// Build the env_vars list: fixed vars + any GH_AW_INPUT_* vars referenced by the
// safe-outputs config so the nested container can resolve ${GH_AW_INPUT_…} placeholders.
safeOutputsEnvVars := []string{
"DEBUG", "DEFAULT_BRANCH",
"GH_AW_ASSETS_ALLOWED_EXTS", "GH_AW_ASSETS_BRANCH", "GH_AW_ASSETS_MAX_SIZE_KB",
"GH_AW_MCP_LOG_DIR", "GH_AW_SAFE_OUTPUTS", "GH_AW_SAFE_OUTPUTS_CONFIG_PATH",
"GH_AW_SAFE_OUTPUTS_TOOLS_PATH", "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST",
"GITHUB_REPOSITORY", "GITHUB_SHA", "GITHUB_TOKEN", "GITHUB_WORKSPACE", "RUNNER_TEMP",
}
if workflowData != nil {
safeOutputsEnvVars = append(safeOutputsEnvVars, sliceutil.SortedKeys(workflowData.SafeOutputsInputEnvVars)...)
}
quoted := make([]string, len(safeOutputsEnvVars))
for i, v := range safeOutputsEnvVars {
quoted[i] = "\"" + v + "\""
}
yaml.WriteString(" env_vars = [" + strings.Join(quoted, ", ") + "]\n")

// Check if GitHub tool has guard-policies configured (or auto-lockdown will run)
// If so, generate a linked write-sink guard-policy for safeoutputs
Expand Down Expand Up @@ -274,6 +292,18 @@ func renderSafeOutputsMCPConfigWithOptions(yaml *strings.Builder, isLast bool, i
{"RUNNER_TEMP", "RUNNER_TEMP", false},
}

// Append GH_AW_INPUT_* vars referenced by the safe-outputs config so the nested
// container can resolve ${GH_AW_INPUT_…} shell-style placeholders at runtime.
if workflowData != nil {
for _, name := range sliceutil.SortedKeys(workflowData.SafeOutputsInputEnvVars) {
envVars = append(envVars, struct {
name string
value string
isLiteral bool
}{name, name, false})
}
}

for i, envVar := range envVars {
comma := ","
if i == len(envVars)-1 {
Expand Down
Loading
Loading