Skip to content

fix: expand secrets in MCP tool parameters - #3278

Merged
jpshackelford merged 9 commits into
mainfrom
fix/mcp-secret-expansion-3277
Jun 16, 2026
Merged

jpshackelford merged 9 commits into
mainfrom
fix/mcp-secret-expansion-3277

Conversation

@jpshackelford

@jpshackelford jpshackelford commented May 16, 2026 •

Copy link
Copy Markdown
Member

Summary

MCP tool parameters do not expand environment variables or secrets, unlike terminal commands. When an agent passes $SECRET_NAME or ${SECRET_NAME} as a parameter to an MCP tool, it arrives at the MCP server as a literal string rather than being expanded to the actual secret value.

This PR adds secret/environment variable expansion to MCP tool parameters, making behavior consistent with terminal commands.

Fixes #3277

Context

We already support ${VAR} expansion in MCP connection setup (URL, headers, env) via expand_mcp_variables() in skills/utils.py — see PR #2873. However, this only applies to .mcp.json configuration, not to the actual tool call parameters sent at runtime.

This PR extends that capability to tool parameters themselves, so agents can pass $MY_SECRET as a tool argument and have it resolved before sending to the MCP server.

Changes

New function: expand_secrets_in_data()

Expands secret references in MCP tool action data with support for:

  • $VAR - Simple variable reference
  • ${VAR} - Braced variable reference
  • ${VAR:-default} - Variable with default value
  • Recursive expansion in nested dicts and lists

Updated MCPToolExecutor.__call__()

  • Expands secrets using conversation's SecretRegistry before calling MCP server
  • Masks secrets in observation output (like TerminalExecutor)
  • Gracefully handles expansion failures (falls back to original action)

Implementation Details

The implementation mirrors TerminalExecutor's secret handling:

  • Uses SecretRegistry.get_secret_value() for lookups (tracks values for masking)
  • Uses SecretRegistry.mask_secrets_in_output() for masking observation content
  • Adds _mask_observation() method to mask TextContent blocks

Testing

Added comprehensive tests in tests/sdk/mcp/test_mcp_secret_expansion.py:

  • test_executor_expands_secrets_in_action_data - Basic $VAR and ${VAR} expansion
  • test_executor_expands_braced_var_with_default - ${VAR:-default} syntax
  • test_executor_expands_nested_data_structures - Nested dicts and lists
  • test_executor_without_conversation_passes_literal_values - No expansion without conversation
  • test_observation_masks_secrets_in_output - Secret masking in responses

All existing MCP tests continue to pass (67 tests total).

Example

Before this fix:

# Agent passes secret reference
action = MCPToolAction(data={"api_key": "$MY_API_KEY"})
# MCP server receives literal "$MY_API_KEY" → authentication fails

After this fix:

# Agent passes secret reference  
action = MCPToolAction(data={"api_key": "$MY_API_KEY"})
# MCP server receives "actual-secret-value-123" → authentication succeeds

This PR was created by an AI agent (OpenHands) on behalf of the user.


Agent Server images for this PR

• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server

Variants & Base Images

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:c79117a-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-c79117a-python \
  ghcr.io/openhands/agent-server:c79117a-python

All tags pushed for this build

ghcr.io/openhands/agent-server:c79117a-golang-amd64
ghcr.io/openhands/agent-server:c79117af28f9c71a26748c7ce745e107dedef1ab-golang-amd64
ghcr.io/openhands/agent-server:fix-mcp-secret-expansion-3277-golang-amd64
ghcr.io/openhands/agent-server:c79117a-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:c79117a-golang-arm64
ghcr.io/openhands/agent-server:c79117af28f9c71a26748c7ce745e107dedef1ab-golang-arm64
ghcr.io/openhands/agent-server:fix-mcp-secret-expansion-3277-golang-arm64
ghcr.io/openhands/agent-server:c79117a-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:c79117a-java-amd64
ghcr.io/openhands/agent-server:c79117af28f9c71a26748c7ce745e107dedef1ab-java-amd64
ghcr.io/openhands/agent-server:fix-mcp-secret-expansion-3277-java-amd64
ghcr.io/openhands/agent-server:c79117a-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:c79117a-java-arm64
ghcr.io/openhands/agent-server:c79117af28f9c71a26748c7ce745e107dedef1ab-java-arm64
ghcr.io/openhands/agent-server:fix-mcp-secret-expansion-3277-java-arm64
ghcr.io/openhands/agent-server:c79117a-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:c79117a-python-amd64
ghcr.io/openhands/agent-server:c79117af28f9c71a26748c7ce745e107dedef1ab-python-amd64
ghcr.io/openhands/agent-server:fix-mcp-secret-expansion-3277-python-amd64
ghcr.io/openhands/agent-server:c79117a-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:c79117a-python-arm64
ghcr.io/openhands/agent-server:c79117af28f9c71a26748c7ce745e107dedef1ab-python-arm64
ghcr.io/openhands/agent-server:fix-mcp-secret-expansion-3277-python-arm64
ghcr.io/openhands/agent-server:c79117a-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:c79117a-golang
ghcr.io/openhands/agent-server:c79117af28f9c71a26748c7ce745e107dedef1ab-golang
ghcr.io/openhands/agent-server:fix-mcp-secret-expansion-3277-golang
ghcr.io/openhands/agent-server:c79117a-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:c79117a-java
ghcr.io/openhands/agent-server:c79117af28f9c71a26748c7ce745e107dedef1ab-java
ghcr.io/openhands/agent-server:fix-mcp-secret-expansion-3277-java
ghcr.io/openhands/agent-server:c79117a-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:c79117a-python
ghcr.io/openhands/agent-server:c79117af28f9c71a26748c7ce745e107dedef1ab-python
ghcr.io/openhands/agent-server:fix-mcp-secret-expansion-3277-python
ghcr.io/openhands/agent-server:c79117a-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim

About Multi-Architecture Support

  • Each variant tag (e.g., c79117a-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., c79117a-python-amd64) are also available if needed

These tests demonstrate that MCP tool parameters do not expand
secrets/environment variables, unlike terminal commands.

The tests verify that MCPToolExecutor should:
- Expand $VAR and ${VAR} syntax to secret values
- Support ${VAR:-default} with default values
- Traverse nested data structures (dicts and lists)
- Pass literal values when no conversation is provided

Current behavior (3 tests FAIL):
- $CUSTOMER_ID is passed as literal string instead of 'expanded-customer'
- ${VAR:-default} is passed as literal instead of being expanded

Expected behavior after fix:
- Secret references are expanded before sending to MCP server

Refs: #3277
Add secret/environment variable expansion to MCP tool parameters,
making behavior consistent with terminal commands.

Changes:
- Add expand_secrets_in_data() function supporting:
  - $VAR - Simple variable reference
  - ${VAR} - Braced variable reference
  - ${VAR:-default} - Variable with default value
  - Recursive expansion in nested dicts and lists

- Update MCPToolExecutor.__call__() to:
  - Expand secrets using conversation's SecretRegistry
  - Mask secrets in observation output (like TerminalExecutor)
  - Gracefully handle expansion failures

The implementation mirrors TerminalExecutor's secret handling:
- Uses SecretRegistry.get_secret_value() for lookups
- Uses SecretRegistry.mask_secrets_in_output() for masking
- Tracks exported values for consistent masking

Fixes: #3277

Co-authored-by: openhands <openhands@all-hands.dev>
@jpshackelford jpshackelford added bug Something isn't working mcp labels May 16, 2026 — with OpenHands AI
@github-actions

github-actions Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/mcp
   tool.py1271687%71, 85–88, 225, 232, 234–236, 302–303, 308, 316, 344, 374
openhands-sdk/openhands/sdk/skills
   utils.py1921592%144, 161, 235, 268–269, 272, 289–290, 345, 358, 362, 390, 411, 552–553
TOTAL30429844672% 

- Fix E501 line too long in test docstring
- Fix pyright type error by using isinstance() instead of hasattr()
- Add missing blank line after function (ruff format)

Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
@jpshackelford
jpshackelford marked this pull request as ready for review May 16, 2026 08:04

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Acceptable - Solid implementation that solves a real problem. Core logic is sound with one improvement opportunity around error handling.

[IMPROVEMENT OPPORTUNITIES]

  • [tool.py, Line 222] Error Handling: Silent exception swallowing in _mask_observation could hide masking bugs
  • [test_mcp_secret_expansion.py, Lines 54-55, 95, 129] Documentation: Test docstrings still say "Currently FAILING" - update to reflect implementation is complete

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟡 MEDIUM

This PR changes how MCP tools receive parameters when secrets are involved. Key risk factors:

✅ Mitigating factors:

  • Feature is opt-in (requires conversation parameter)
  • Graceful degradation (falls back to original action on expansion failure)
  • No breaking changes (backward compatible - when conversation is None, no expansion occurs)
  • Mirrors existing TerminalExecutor pattern
  • Comprehensive test coverage

⚠️ Remaining risks:

  • Silent failures in masking logic could potentially expose secrets in logs/output
  • New code path for secret expansion could have edge cases not covered by tests

Recommendation: Acceptable for merge with suggested logging improvement. The risk is moderate but well-contained by opt-in design and fallback behavior.

VERDICT: ✅ Worth merging - Implementation follows existing patterns and adds important parity between terminal and MCP secret handling.

KEY INSIGHT: This elegantly mirrors TerminalExecutor's secret expansion pattern while maintaining backward compatibility through opt-in conversation parameter.


Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:

  1. Add a .agents/skills/custom-codereview-guide.md file to your branch (or edit it if one already exists) with the /codereview trigger and the context the reviewer is missing (e.g., "Security concerns about X do not apply here because Y"). See the customization docs for the required frontmatter format.
  2. Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
  3. When your PR is merged, the guideline file goes through normal code review by repository maintainers.

Resolve with AI? Install the iterate skill in your agent and run /iterate to automatically drive this PR through CI, review, and QA until it's merge-ready.

Comment thread openhands-sdk/openhands/sdk/mcp/tool.py Resolved

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

✅ QA Report: PASS

MCP tool parameters now correctly expand secrets before sending to MCP servers. All verification tests pass, CI is green, and the implementation achieves the stated goal.

Does this PR achieve its stated goal?

Yes. The PR claims to add secret/environment variable expansion to MCP tool parameters (addressing issue #3277). I verified this works correctly through functional testing:

  • Core functionality: Agent-provided secret references like $API_KEY and ${CUSTOMER_ID} are now expanded to their actual values before the MCP server receives them.
  • Backward compatibility: Without a conversation/secret registry, literals are preserved unchanged (no breaking change).
  • Advanced syntax: The ${VAR:-default} syntax works as documented.
  • Nested structures: Secrets in nested dictionaries and lists are recursively expanded.
  • Security: Secrets appearing in MCP tool responses are properly masked in observations.

The implementation mirrors the existing TerminalExecutor secret handling, which is the appropriate pattern.

Phase Result
Environment Setup ✅ Dependencies installed, project builds successfully
CI Status ✅ 31 checks passed, 2 skipped, 0 failing
Functional Verification ✅ All 6 verification tests pass
Functional Verification

Test 1: Core Secret Expansion Function

Step 1 — Verify expand_secrets_in_data() function works:

Created a test with secrets API_KEY=super-secret-key-12345 and CUSTOMER_ID=customer-abc-789.

Input data:

{'api_key': '$API_KEY', 'customer': '${CUSTOMER_ID}', 'literal': 'not-a-secret'}

Output:

{'api_key': 'super-secret-key-12345', 'customer': 'customer-abc-789', 'literal': 'not-a-secret'}

✅ Result: Secrets expanded correctly, literals preserved.


Test 2: Executor Without Conversation (BEFORE behavior)

Step 1 — Establish baseline: what happens without conversation?

Created an MCPToolExecutor with action data containing secret references, called WITHOUT a conversation object.

Input to executor:

{'api_key': '$API_KEY', 'customer_id': '${CUSTOMER_ID}'}

What was sent to MCP server:

{'api_key': '$API_KEY', 'customer_id': '${CUSTOMER_ID}'}

✅ Result: Literals preserved unchanged. This maintains backward compatibility — if no conversation/secret registry is available, the old behavior is preserved.


Test 3: Executor With Conversation (AFTER/NEW behavior)

Step 1 — Apply the fix: provide conversation with secret registry:

Created a conversation with SecretRegistry containing the test secrets, then called the executor WITH the conversation.

Input to executor:

{'api_key': '$API_KEY', 'customer_id': '${CUSTOMER_ID}'}

What was sent to MCP server (after expansion):

{'api_key': 'super-secret-key-12345', 'customer_id': 'customer-abc-789'}

✅ Result: Secrets expanded before sending to MCP server. This is the core fix — agents can now pass $SECRET_NAME and it will be resolved to the actual value, just like terminal commands.


Test 4: Nested Secret Expansion

Step 1 — Test complex nested structures:

Input with nested dicts and lists:

{
  'auth': {
    'token': '$TOKEN',
    'credentials': {'username': '${USER}'}
  },
  'ids': ['$TOKEN', 'literal-id']
}

Expanded output:

{
  'auth': {
    'token': 'secret-token-xyz',
    'credentials': {'username': 'admin-user'}
  },
  'ids': ['secret-token-xyz', 'literal-id']
}

✅ Result: Secrets in nested structures are recursively expanded.


Test 5: Default Value Syntax

Step 1 — Test ${VAR:-default} syntax:

Input with existing and missing secrets:

{'existing': '${EXISTING:-fallback}', 'missing': '${MISSING:-default-value}'}

Expanded output:

{'existing': 'actual-value', 'missing': 'default-value'}

✅ Result: Existing secrets use their actual value (not the default), missing secrets fall back to the specified default.


Test 6: Secret Masking in Output

Step 1 — Verify secrets in MCP responses are masked:

MCP server response (simulated raw output):

Your API key is super-secret-key-12345 and it worked!

Observation text (after masking):

[Tool 'test_tool' executed.]Your API key is <secret-hidden> and it worked!

✅ Result: Secrets appearing in MCP tool output are automatically masked, preventing accidental exposure in logs.


Full Verification Script Output

======================================================================
✅ ALL VERIFICATION TESTS PASSED
======================================================================

Summary:
  • Secret expansion function works correctly
  • Without conversation: literals preserved (backward compatible)
  • With conversation: secrets expanded before MCP call
  • Nested structures are handled
  • Default value syntax ${VAR:-default} works
  • Secrets in output are masked

Unit Tests

Ran the new test file tests/sdk/mcp/test_mcp_secret_expansion.py:

5 passed, 5 warnings in 0.04s

All 5 unit tests pass:

  • test_executor_expands_secrets_in_action_data
  • test_executor_expands_braced_var_with_default
  • test_executor_expands_nested_data_structures
  • test_executor_without_conversation_passes_literal_values
  • test_observation_masks_secrets_in_output

Issues Found

None.

- Add logging to except block in _mask_observation() for debugging
- Update test docstring to reflect fix is implemented

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Member Author

Addressed feedback in d71a58b. Ready for another look.

@jpshackelford jpshackelford added the customer-support This item has been reported by a customer and is being tracked as a support ticket. label May 16, 2026

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Acceptable - Solid implementation that solves a real problem. Core logic is sound with one improvement opportunity around code reuse.

[IMPROVEMENT OPPORTUNITIES]

  • See inline comment about potential code reuse

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟢 LOW

Additive functionality with comprehensive test coverage, proper error handling, and backward compatibility. No breaking changes - when conversation is not provided, behavior is unchanged (literal values passed through).

VERDICT:
✅ Worth merging: Pragmatic solution to a real user problem with good test coverage

KEY INSIGHT:
This PR successfully bridges the gap between terminal and MCP tool secret handling, enabling consistent secret access patterns across execution contexts.

Comment thread openhands-sdk/openhands/sdk/mcp/tool.py Resolved

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

✅ QA Report: PASS

MCP tool parameters now correctly expand secret references ($VAR, ${VAR}, ${VAR:-default}) to actual secret values before sending to MCP servers, and mask secrets in observation output.

Does this PR achieve its stated goal?

Yes. The PR successfully fixes issue #3277 by implementing secret expansion in MCP tool parameters, making the behavior consistent with terminal commands. I verified this by:

  1. Before the fix (main branch): Secret references like $API_KEY were passed as literal strings to the MCP server, causing authentication failures.
  2. After the fix (this PR): Secret references are expanded to actual values (e.g., $API_KEY → super-secret-api-key-12345) before being sent to the MCP server, and secrets in observation output are automatically masked with <secret-hidden>.

The implementation handles all claimed features: simple variable references ($VAR), braced syntax (${VAR}), default values (${VAR:-default}), nested data structures (dicts and lists), and graceful error handling when expansion fails.

Phase Result
Environment Setup ✅ Dependencies installed, all 68 MCP tests pass
CI Status ⚙️ Checks in progress (unresolved-review-threads failed, tests/builds running)
Functional Verification ✅ All secret expansion scenarios verified end-to-end
Functional Verification

Test 1: Basic Secret Expansion (Before/After Comparison)

Step 1 — Reproduce the bug (main branch without the fix):

Checked out main branch and ran a functional test that sends an MCP tool action with secret references:

action = MCPToolAction(
    data={
        "api_key": "$API_KEY",
        "customer_id": "${CUSTOMER_ID}",
        "static_value": "hello",
    }
)

Result on main:

❌ FAILURE: Secrets were NOT expanded!
   Expected api_key='super-secret-api-key-12345', got '$API_KEY'
   Expected customer_id='customer-abc-xyz', got '${CUSTOMER_ID}'

This confirms the bug exists: the MCP server receives literal strings like $API_KEY instead of the actual secret values.

Step 2 — Apply the PR's changes:

Checked out the PR branch fix/mcp-secret-expansion-3277.

Step 3 — Re-run with the fix in place:

Ran the same functional test with the PR's changes:

✅ SUCCESS: Secrets were expanded correctly!
   - $API_KEY → super-secret-api-key-12345
   - ${CUSTOMER_ID} → customer-abc-xyz

What MCP server received:

{
    "api_key": "super-secret-api-key-12345",  # Expanded!
    "customer_id": "customer-abc-xyz",  # Expanded!
    "static_value": "hello"  # Unchanged
}

This proves the fix works: secret references are now expanded before being sent to the MCP server.


Test 2: Secret Masking in Output

Verification:

The MCP server returned a response containing the secret value:

"API call succeeded with key: super-secret-api-key-12345"

What the agent observed:

"[Tool 'test_tool' executed.]API call succeeded with key: <secret-hidden>"

Result: ✅ Secrets automatically masked in observation output, preventing leakage in conversation history.


Test 3: Default Value Syntax (${VAR:-default})

Test input:

action = MCPToolAction(
    data={
        "existing": "${EXISTING_SECRET:-fallback}",  # Secret exists
        "missing": "${MISSING_SECRET:-default-value}",  # Secret missing
    }
)

What MCP server received:

{
    "existing": "existing-value",  # Used actual secret (not fallback)
    "missing": "default-value"  # Used default (secret not found)
}

Result: ✅ Default value syntax works correctly.


Test 4: Nested Data Structures

Test input:

action = MCPToolAction(
    data={
        "auth": {
            "token": "$TOKEN",
            "user": {"id": "${USER_ID}"}
        },
        "ids": ["$USER_ID", "static-id"]
    }
)

What MCP server received:

{
    "auth": {
        "token": "secret-token-xyz",  # Expanded in nested dict
        "user": {"id": "user-123"}  # Expanded in deeply nested dict
    },
    "ids": ["user-123", "static-id"]  # Expanded in list
}

Result: ✅ Recursive expansion works in nested dicts and lists.


Test 5: No Expansion Without Conversation

Verification:

Called executor(action, conversation=None) with secret references.

What MCP server received:

{
    "api_key": "$API_KEY",  # Literal, not expanded
    "customer_id": "${CUSTOMER_ID}"  # Literal, not expanded
}

Result: ✅ Correctly passes literal values when no conversation/secret registry is available.


Test 6: Graceful Error Handling

Verification:

Simulated a secret registry failure that raises an exception during get_secret_value().

Observed behavior:

WARNING: Failed to expand secrets in MCP tool action: Simulated registry failure

What MCP server received:

{"api_key": "$API_KEY"}  # Fell back to original action

Result: ✅ Executor logs a warning and gracefully falls back to the original action when expansion fails.


Test 7: Existing Test Suite

Command:

uv run pytest tests/sdk/mcp/ -v

Result:

======================= 68 passed, 5 warnings in 15.09s ========================

Result: ✅ All existing MCP tests pass (67 existing + 5 new tests for secret expansion). No regressions introduced.

Issues Found

None. The implementation works as described, handles edge cases gracefully, and introduces no regressions.

DRY up the variable expansion logic used by both:
- expand_mcp_variables() for MCP config expansion
- expand_secrets_in_data() for runtime tool parameter expansion

The new expand_variable_references() function parameterizes:
- support_unbraced: Whether to support $VAR syntax (tool params) or only ${VAR} (config)
- check_env: Whether to check os.environ (config) or not (tool params)
- variables dict: Optional dict of variable name → value mappings
- get_secret: Optional callback for secret lookups

This ensures consistent behavior and reduces maintenance burden.

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Member Author

Addressed refactoring suggestion in 64c4569 — extracted expand_variable_references() as the shared helper function. Both expand_mcp_variables() and expand_secrets_in_data() now use the same core logic. Ready for another look.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟢 Good taste - Solid implementation that solves a real problem with clean refactoring.

[IMPROVEMENT OPPORTUNITIES]

  • See inline comments for minor documentation cleanup suggestions

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟢 LOW

Additive functionality with comprehensive test coverage, proper error handling, and backward compatibility. When conversation=None, behavior is unchanged (literals pass through). When conversation is provided, secrets are expanded before calling MCP servers and masked in outputs. No breaking changes.

VERDICT:
✅ Worth merging - Fixes real bug (issue #3277), well-tested, backward compatible

KEY INSIGHT:
Good refactoring to extract expand_variable_references() as shared helper - eliminates code duplication between MCP config expansion and runtime parameter expansion while maintaining flexibility through clear parameters.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

✅ QA Report: PASS

MCP tool parameters now correctly expand secret references before sending to the MCP server, and secrets are properly masked in output.

Does this PR achieve its stated goal?

Yes. The PR successfully fixes issue #3277. I verified end-to-end that MCP tool parameters now expand environment variables and secrets (e.g., $SECRET_NAME, ${SECRET_NAME}, ${VAR:-default}) before sending them to the MCP server, making behavior consistent with terminal commands. The fix includes proper secret masking in observations and graceful fallback when no conversation is provided.

Phase Result
Environment Setup ✅ Dependencies installed, SDK imports successfully
CI Status ⚠️ Most checks passing (sdk-tests ✅, tools-tests ✅, pre-commit ✅). One unrelated failure: Build & Push (golang-arm64)
Functional Verification ✅ All core functionality verified with before/after comparison
Functional Verification

Test 1: Reproduce the Bug (Without Fix)

Step 1 — Establish baseline on main branch:

Checked out main branch (without the fix) and ran test script:

git checkout main
uv run python /tmp/test_mcp_secret_expansion_demo.py

Output:

=== MCP Tool Secret Expansion Demo ===

Test 1: Simple $VAR expansion
--------------------------------------------------
Agent sends: {
  "api_key": "$API_KEY",
  "customer": "$CUSTOMER_ID"
}
MCP server receives: {
  "api_key": "$API_KEY",
  "customer": "$CUSTOMER_ID"
}
Observation text: Authenticated with API key: $API_KEY
AssertionError: Secret was not expanded!

Interpretation: This confirms the bug exists — when an agent passes $API_KEY to an MCP tool, the MCP server receives the literal string "$API_KEY" instead of the actual secret value. This would cause authentication failures in real scenarios.


Test 2: Verify the Fix (With PR Changes)

Step 2 — Apply the PR's changes:

git checkout fix/mcp-secret-expansion-3277

Step 3 — Re-run with the fix in place:

uv run python /tmp/test_mcp_secret_expansion_demo.py

Output:

=== MCP Tool Secret Expansion Demo ===

Test 1: Simple $VAR expansion
--------------------------------------------------
Agent sends: {
  "api_key": "$API_KEY",
  "customer": "$CUSTOMER_ID"
}
MCP server receives: {
  "api_key": "super-secret-api-key-12345",
  "customer": "customer-abc-789"
}
Observation text: Authenticated with API key: <secret-hidden>
✅ Secrets expanded correctly!
✅ Secrets masked in observation output!

Test 2: ${VAR:-default} expansion with defaults
--------------------------------------------------
Agent sends: {
  "existing": "${API_KEY}",
  "missing": "${NONEXISTENT:-fallback-value}"
}
MCP server receives: {
  "existing": "super-secret-api-key-12345",
  "missing": "fallback-value"
}
✅ Braced variables and defaults work correctly!

Test 3: Nested dict/list expansion
--------------------------------------------------
Agent sends: {
  "auth": {
    "token": "$API_KEY",
    "customer_ids": [
      "$CUSTOMER_ID",
      "static-id"
    ]
  }
}
MCP server receives: {
  "auth": {
    "token": "super-secret-api-key-12345",
    "customer_ids": [
      "customer-abc-789",
      "static-id"
    ]
  }
}
✅ Nested structures expanded correctly!

Test 4: Without conversation (no expansion expected)
--------------------------------------------------
Agent sends: {
  "api_key": "$API_KEY"
}
MCP server receives: {
  "api_key": "$API_KEY"
}
✅ Correctly skips expansion when no conversation provided!

==================================================
All tests passed! ✅
==================================================

Interpretation: The fix works perfectly:

  1. Secret expansion works — $API_KEY is expanded to "super-secret-api-key-12345" before sending to the MCP server
  2. Multiple formats supported — Both $VAR and ${VAR} syntax work
  3. Default values work — ${NONEXISTENT:-fallback-value} correctly uses the default when the variable doesn't exist
  4. Recursive expansion works — Secrets in nested dicts and lists are properly expanded
  5. Secret masking works — The actual secret value is replaced with <secret-hidden> in observation output
  6. Safe fallback — When no conversation is provided, literals pass through unchanged (correct behavior)

Test 3: No Regressions in Existing MCP Tests

Command:

uv run pytest tests/sdk/mcp/ -v

Result:

======================= 68 passed, 5 warnings in 13.95s ========================

Breakdown:

  • 63 existing MCP tests: All PASS (no regressions introduced)
  • 5 new secret expansion tests: All PASS (new functionality works correctly)

New tests added by this PR:

  1. test_executor_expands_secrets_in_action_data — Verifies basic $VAR and ${VAR} expansion
  2. test_executor_expands_braced_var_with_default — Verifies ${VAR:-default} syntax
  3. test_executor_expands_nested_data_structures — Verifies recursive expansion in nested dicts/lists
  4. test_executor_without_conversation_passes_literal_values — Verifies safe fallback behavior
  5. test_observation_masks_secrets_in_output — Verifies secret masking in responses

Issues Found

None. The PR successfully achieves its stated goal with comprehensive test coverage and no regressions.


Verified behavior:

  • ✅ Secrets expand in MCP tool parameters (fixes #3277)
  • ✅ Supports $VAR, ${VAR}, and ${VAR:-default} syntax
  • ✅ Works recursively in nested data structures
  • ✅ Secrets are masked in observation output
  • ✅ Graceful fallback when no conversation is provided
  • ✅ All existing MCP tests continue to pass (no regressions)
  • ✅ Comprehensive test coverage added

This QA report was generated by an AI agent (OpenHands) on behalf of the user.

- Remove outdated 'FAILING' comments from test docstrings
- Remove redundant conditional in expand_variable_references()

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Member Author

Addressed review feedback in 11b37aa:

  • Removed outdated 'FAILING' comments from test docstrings
  • Simplified redundant conditional in expand_variable_references()

Ready for another look.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Acceptable - Solid implementation that solves a real problem. Code quality is excellent, but this PR requires eval evidence before approval due to tool execution behavior changes.

[EVAL RISK REQUIREMENT]
This PR changes tool calling/execution behavior (MCP tools now expand secrets instead of passing literals), which falls under the eval-risk category per repository policy. Before this can be approved:

  1. Run lightweight evals (SWE-bench, GAIA, or similar) to verify no performance regression
  2. Post eval monitor link (openhands-eval-monitor.vercel.app) to the PR
  3. A human maintainer should review and confirm the eval results

See repo guidelines for details.

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟢 LOW (technical)

The implementation is backward compatible (when conversation=None, behavior unchanged), has comprehensive test coverage (67 MCP tests pass), proper error handling with graceful fallback, and follows established patterns from TerminalExecutor. The refactoring extracts common expansion logic cleanly. No breaking changes to public APIs.

VERDICT:
⏸️ Needs eval evidence: Code is merge-ready from a technical standpoint, but requires eval run + human review per repository policy for tool execution changes.

KEY INSIGHT:
Clean refactoring that eliminates code duplication while solving a real UX gap (MCP tools should behave like terminal commands for secret expansion). The shared expand_variable_references() helper provides consistent behavior across MCP config and runtime tool parameters.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

✅ QA Report: PASS

MCP tool parameters now correctly expand secrets and environment variables, matching terminal command behavior.

Does this PR achieve its stated goal?

Yes. The PR fixes issue #3277 completely. Before this fix, MCP tool parameters passed literal strings like $API_KEY to MCP servers, causing authentication failures. After this fix, MCP tools expand secret references to actual values (e.g., super-secret-key-12345) before calling the server, and mask secrets in observation output. The implementation mirrors TerminalExecutor's behavior, achieving consistency across the SDK.

Phase Result
Environment Setup ✅ Build successful, dependencies installed
CI Status ⚠️ Most checks pass; unresolved-review-threads expected, windows-build unrelated to this PR
Functional Verification ✅ All behaviors verified end-to-end
Functional Verification

Test 1: Basic Secret Expansion ($VAR and ${VAR} syntax)

Step 1 — Reproduce the bug (main branch):

Created test script that passes MCP tool action with secret references:

action = MCPToolAction(data={
    "api_key": "$API_KEY",
    "customer_id": "${CUSTOMER_ID}",
})

Ran on main branch:

git checkout main
.venv/bin/python /tmp/test_mcp_secret_expansion.py

Output:

Actual values sent to MCP server:
  api_key: $API_KEY
  customer_id: ${CUSTOMER_ID}

❌ SECRET EXPANSION BROKEN: $API_KEY passed as literal string
❌ SECRET EXPANSION BROKEN: ${CUSTOMER_ID} passed as literal string

This confirms the bug: MCP server received literal $API_KEY instead of the actual secret value, which would cause authentication to fail.

Step 2 — Apply the PR's changes:
Switched to PR branch:

git checkout fix/mcp-secret-expansion-3277

Step 3 — Re-run with the fix in place:
Ran same test script:

.venv/bin/python /tmp/test_mcp_secret_expansion.py

Output:

Actual values sent to MCP server:
  api_key: super-secret-key-12345
  customer_id: customer-abc-xyz

✅ SECRET EXPANSION WORKING: $API_KEY was expanded
✅ SECRET EXPANSION WORKING: ${CUSTOMER_ID} was expanded

Observation text returned to agent:
   [Tool 'test_api' executed.]Authenticated with API key: <secret-hidden>
✅ SECRET MASKING WORKING: Secret value masked in observation

The fix works: secrets are now expanded to their actual values before being sent to the MCP server, and secrets in responses are automatically masked.


Test 2: Default Value Syntax (${VAR:-default})

Tested that ${VAR:-default} syntax works correctly:

  • Existing secret: ${API_KEY:-fallback} → expanded to real-api-key (not fallback)
  • Missing secret: ${MISSING_SECRET:-default-value} → expanded to default-value

Ran:

.venv/bin/python /tmp/test_mcp_default_values.py

Output:

Actual values sent to MCP server:
  existing_with_default: real-api-key
  missing_with_default: default-value

✅ EXISTING SECRET: Used actual value (not default)
✅ MISSING SECRET: Used default value

Default value fallback works correctly.


Test 3: Nested Data Structures

Tested secret expansion in nested dicts and lists:

action = MCPToolAction(data={
    "auth": {
        "token": "$TOKEN",
        "credentials": {
            "username": "${USER}",
            "type": "bearer"
        }
    },
    "ids": ["$USER", "static-value", "${TOKEN}"]
})

Ran:

.venv/bin/python /tmp/test_mcp_nested_expansion.py

Output:

Actual nested structure sent to MCP server:
  auth.token: secret-token-xyz
  auth.credentials.username: john-doe
  auth.credentials.type: bearer
  ids[0]: john-doe
  ids[1]: static-value
  ids[2]: secret-token-xyz

✅ Nested dict: auth.token expanded correctly
✅ Deeply nested: auth.credentials.username expanded correctly
✅ Non-secret: auth.credentials.type unchanged
✅ List expansion: ids[0] expanded correctly
✅ List non-secret: ids[1] unchanged
✅ List expansion: ids[2] expanded correctly

Recursive expansion works correctly for complex nested structures.


Test 4: Comprehensive Test Suite

Ran all MCP tests to ensure no regressions:

.venv/bin/pytest tests/sdk/mcp/ -v

Result:

68 passed, 5 warnings in 14.05s

All 68 tests pass, including:

  • 5 new tests added by this PR (secret expansion + masking)
  • 63 existing MCP tests (no regressions)

The PR successfully adds the new functionality without breaking any existing behavior.

Issues Found

None. The implementation is clean, well-tested, and achieves the stated goal without breaking existing functionality.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @jpshackelford, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

This comment was created by an AI agent (OpenHands) on behalf of the user.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @jpshackelford, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

This comment was generated by an AI agent (OpenHands) on behalf of the repository maintainers.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: This PR seems to be currently waiting for review. @jpshackelford, could you please take a look when you have a chance?

This comment was created by an AI agent (OpenHands) on behalf of the user.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @jpshackelford, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

This comment was created by an AI agent (OpenHands) on behalf of the user.

@jpshackelford

Copy link
Copy Markdown
Member Author

@VascoSch92 Your changes are a clear improvement. Thanks very much!

Dropping the expand_secrets_in_data() wrapper in favor of calling expand_variable_references() directly makes sense — it was an unnecessary indirection layer. Keeping check_env=False and support_unbraced=True preserves the original intent (secrets only, shell-style $VAR), just with less code.

Switching to action.model_copy(update={"data": ...}) and rebuilding the observation the same way is cleaner and safer than reconstructing MCPToolAction/MCPToolObservation by hand, since it carries over any other fields automatically.

The _mask_observation() rewrite reads well, and I like that non-text blocks (e.g. images) now explicitly pass through untouched.

The match/case refactor in skills/utils.py is a nice readability bump (and fine given we're on 3.10+).

The test changes are my favorite part. Moving to fixtures + parametrization tightened things up considerably, and the new coverage fills real gaps in my original tests.

Thanks again for taking time to help me get this right!

@jpshackelford
jpshackelford merged commit f2329b7 into main Jun 16, 2026
44 of 45 checks passed
@jpshackelford
jpshackelford deleted the fix/mcp-secret-expansion-3277 branch June 16, 2026 11:37
pengzhang-create pushed a commit to Pyromind-Dynamics/software-agent-sdk that referenced this pull request Aug 13, 2026
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: Vasco Schiavo <115561717+VascoSch92@users.noreply.github.com>
Co-authored-by: VascoSch92 <vasco.schiavo@protonmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working customer-support This item has been reported by a customer and is being tracked as a support ticket. mcp

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP tool parameters do not expand secrets/environment variables (unlike terminal commands)

4 participants