Repository navigation
fix: expand secrets in MCP tool parameters - #3278
Conversation
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>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
- 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>
all-hands-bot
left a comment
There was a problem hiding this comment.
🟡 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_observationcould 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
- 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:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger 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.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- 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
/iterateto automatically drive this PR through CI, review, and QA until it's merge-ready.
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ 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_KEYand${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_datatest_executor_expands_braced_var_with_defaulttest_executor_expands_nested_data_structurestest_executor_without_conversation_passes_literal_valuestest_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>
|
Addressed feedback in d71a58b. Ready for another look. |
all-hands-bot
left a comment
There was a problem hiding this comment.
🟡 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.
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ 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:
- Before the fix (main branch): Secret references like
$API_KEYwere passed as literal strings to the MCP server, causing authentication failures. - 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 actionResult: ✅ 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/ -vResult:
======================= 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>
|
Addressed refactoring suggestion in 64c4569 — extracted |
all-hands-bot
left a comment
There was a problem hiding this comment.
🟢 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
left a comment
There was a problem hiding this comment.
✅ 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 | |
| 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.pyOutput:
=== 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-3277Step 3 — Re-run with the fix in place:
uv run python /tmp/test_mcp_secret_expansion_demo.pyOutput:
=== 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:
- Secret expansion works —
$API_KEYis expanded to"super-secret-api-key-12345"before sending to the MCP server - Multiple formats supported — Both
$VARand${VAR}syntax work - Default values work —
${NONEXISTENT:-fallback-value}correctly uses the default when the variable doesn't exist - Recursive expansion works — Secrets in nested dicts and lists are properly expanded
- Secret masking works — The actual secret value is replaced with
<secret-hidden>in observation output - 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/ -vResult:
======================= 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:
test_executor_expands_secrets_in_action_data— Verifies basic$VARand${VAR}expansiontest_executor_expands_braced_var_with_default— Verifies${VAR:-default}syntaxtest_executor_expands_nested_data_structures— Verifies recursive expansion in nested dicts/liststest_executor_without_conversation_passes_literal_values— Verifies safe fallback behaviortest_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>
|
Addressed review feedback in 11b37aa:
Ready for another look. |
all-hands-bot
left a comment
There was a problem hiding this comment.
🟡 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:
- Run lightweight evals (SWE-bench, GAIA, or similar) to verify no performance regression
- Post eval monitor link (
openhands-eval-monitor.vercel.app) to the PR - 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
left a comment
There was a problem hiding this comment.
✅ 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 | |
| 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.pyOutput:
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-3277Step 3 — Re-run with the fix in place:
Ran same test script:
.venv/bin/python /tmp/test_mcp_secret_expansion.pyOutput:
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 toreal-api-key(notfallback) - Missing secret:
${MISSING_SECRET:-default-value}→ expanded todefault-value
Ran:
.venv/bin/python /tmp/test_mcp_default_values.pyOutput:
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.pyOutput:
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/ -vResult:
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.
|
[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. |
|
[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. |
|
[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. |
|
[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. |
|
@VascoSch92 Your changes are a clear improvement. Thanks very much! Dropping the Switching to a The The match/case refactor in 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! |
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>
Summary
MCP tool parameters do not expand environment variables or secrets, unlike terminal commands. When an agent passes
$SECRET_NAMEor${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) viaexpand_mcp_variables()inskills/utils.py— see PR #2873. However, this only applies to.mcp.jsonconfiguration, not to the actual tool call parameters sent at runtime.This PR extends that capability to tool parameters themselves, so agents can pass
$MY_SECRETas 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 valueUpdated
MCPToolExecutor.__call__()SecretRegistrybefore calling MCP serverTerminalExecutor)Implementation Details
The implementation mirrors
TerminalExecutor's secret handling:SecretRegistry.get_secret_value()for lookups (tracks values for masking)SecretRegistry.mask_secrets_in_output()for masking observation content_mask_observation()method to mask TextContent blocksTesting
Added comprehensive tests in
tests/sdk/mcp/test_mcp_secret_expansion.py:test_executor_expands_secrets_in_action_data- Basic$VARand${VAR}expansiontest_executor_expands_braced_var_with_default-${VAR:-default}syntaxtest_executor_expands_nested_data_structures- Nested dicts and liststest_executor_without_conversation_passes_literal_values- No expansion without conversationtest_observation_masks_secrets_in_output- Secret masking in responsesAll existing MCP tests continue to pass (67 tests total).
Example
Before this fix:
After this fix:
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
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:c79117a-pythonRun
All tags pushed for this build
About Multi-Architecture Support
c79117a-python) is a multi-arch manifest supporting both amd64 and arm64c79117a-python-amd64) are also available if needed