Skip to content

feat(openclaw_agent): consume rollout-scoped Gym MCP metadata - #2733

Closed
cwing-nvidia wants to merge 5 commits into
fix/structured-mcp-tool-provenancefrom
feat/openclaw-dynamic-mcp-handoff-2670
Closed

cwing-nvidia wants to merge 5 commits into
fix/structured-mcp-tool-provenancefrom
feat/openclaw-dynamic-mcp-handoff-2670

Conversation

@cwing-nvidia

@cwing-nvidia cwing-nvidia commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR lets OpenClaw discover and call rollout-scoped Gym resources-server tools while keeping each signed MCP token isolated to its own invocation.

Details

  • consume the shared RolloutMCPServer contract from /seed_session, then translate it once into OpenClaw mcp.servers configuration
  • merge the Gym server into each ephemeral openclaw.json, preserving unrelated static MCP servers and giving the rollout entry same-name precedence
  • invoke OpenClaw after seeding so signed metadata never enters the public Responses API or shared mutable state
  • keep OpenClaw-native session event parsing local, but return response and canonical provenance through the shared AgentExecutionResult/AgentEpisode contract
  • remove agent-local metadata validation and tuple/callback plumbing; shared code handles URL resolution, header normalization, and typed provenance transport
  • document built-in, static MCP, and rollout-scoped Gym tool behavior

Closes #2670

Test plan

  • pytest responses_api_agents/openclaw_agent/tests -q — 75 passed (including process-tree cleanup outside the sandbox)
  • shared MCP/reverification/OpenClaw matrix — 273 passed
  • scoped pre-commit run --files ... — passed
  • fresh post-refactor Workplace/OpenClaw MCP rollout with OpenClaw 2026.6.11 and nvidia/nvidia/nemotron-3.5-lightning
    • stored name: workplace_assistant__email_reply_email
    • emitted call_id: chatcmpl-tool-b27ad536832c6461
    • sidecar: (workplace_assistant, email_reply_email) under that call ID
    • rollout reward: 1.0
    • reverification reward: 1.0
    • rollout workspace and token config removed after execution

Stack

This PR is intentionally based on #2673 and now directly consumes its shared MCP handoff infrastructure. Retarget to main after #2673 merges.

Keep OpenClaw's session-event extraction and verifier forwarding with the dynamic MCP handoff work so the complete path can be validated together.

Signed-off-by: Chris Wing <[email protected]>
Translate seeded MCP metadata into each invocation's ephemeral OpenClaw config so resources tools are callable without sharing signed tokens across rollouts.

Signed-off-by: Chris Wing <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Aug 24, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@cwing-nvidia

cwing-nvidia commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Live Workplace rollout evidence

A real OpenClaw 2026.6.11 rollout called the Gym-exposed Workplace tool through the seeded /mcp endpoint and scored successfully with nvidia/nvidia/nemotron-3.5-lightning.

Selected stored fields:

{
  "response": {
    "output": [
      {
        "type": "function_call",
        "call_id": "chatcmpl-tool-92096782361fe18b",
        "name": "workplace_assistant__email_reply_email",
        "arguments": "{\"email_id\": \"00000057\", \"body\": \"Thanks for the update - I will get back to you tomorrow.\"}"
      },
      {
        "type": "function_call_output",
        "call_id": "chatcmpl-tool-92096782361fe18b",
        "output": "Email replied successfully."
      }
    ]
  },
  "mcp_tool_call_provenance": {
    "chatcmpl-tool-92096782361fe18b": {
      "server_name": "workplace_assistant",
      "tool_name": "email_reply_email"
    }
  },
  "reward": 1.0
}

The stored alias remained OpenClaw-facing, while the sidecar carried the canonical identity under the same call_id. gym eval reverify also returned reward 1; Workplace has unknown/unsupported reverify mode, so the CLI wrote the expected unsafe_-prefixed artifact. The configured workspace directory was empty after completion: its per-rollout subdirectory and signed-token config had been deleted.

Temporary rollout config
workplace_assistant:
  resources_servers:
    workplace_assistant:
      entrypoint: app.py
      domain: agent
      verified: false
      expose_tools_over_mcp: true
      description: Temporary OpenClaw MCP handoff smoke test

workplace_assistant_openclaw_mcp:
  responses_api_agents:
    openclaw_agent:
      entrypoint: app.py
      resources_server:
        type: resources_servers
        name: workplace_assistant
      model_server:
        type: responses_api_models
        name: policy_model
      concurrency: 1
      command: openclaw
      model: ${policy_model_name}
      workspace_root: outputs/issue-2670/workspaces
      openclaw_agent_id: main
      thinking: "off"
      system_prompt: null
      setup_timeout: 900
      timeout: 900
      extra_args: []
      env: {}
      openclaw_config: {}
      context_window: null
      max_output_tokens: null
      openclaw_version: 2026.6.11
      datasets:
        - name: smoke
          type: validation
          jsonl_fpath: issue_2668_workplace_smoke.jsonl
          license: Apache 2.0
issue_2668_workplace_smoke.jsonl
{"id": 0, "responses_create_params": {"input": [{"role": "system", "content": "Use the available workplace tools to complete the requested action."}, {"role": "user", "content": "Reply to email ID 00000057 with exactly: Thanks for the update - I will get back to you tomorrow."}], "tools": [{"type": "function", "name": "email_reply_email", "description": "Replies to an email by its ID.", "parameters": {"type": "object", "properties": {"email_id": {"type": "string"}, "body": {"type": "string"}}, "required": ["email_id", "body"], "additionalProperties": false}, "strict": false}], "parallel_tool_calls": false, "temperature": 0.0}, "ground_truth": [{"name": "email_reply_email", "arguments": "{\"email_id\": \"00000057\", \"body\": \"Thanks for the update - I will get back to you tomorrow.\"}"}], "category": "workplace_assistant_email", "environment_name": "workplace_assistant"}

env.yaml must provide policy_base_url and policy_api_key for the selected model.

Commands:

.venv/bin/gym eval run \
  --config issue_2670_openclaw_mcp_smoke.yaml \
  --model-type vllm_model \
  --agent workplace_assistant_openclaw_mcp \
  --output outputs/issue-2670/openclaw_mcp.jsonl \
  --limit 1 --concurrency 1 --split validation \
  ++policy_model_name=nvidia/nvidia/nemotron-3.5-lightning

.venv/bin/gym eval reverify \
  --config issue_2670_openclaw_mcp_smoke.yaml \
  --model-type vllm_model \
  --inputs outputs/issue-2670/openclaw_mcp_materialized_inputs.jsonl \
  --rollouts outputs/issue-2670/openclaw_mcp.jsonl \
  --output outputs/issue-2670/openclaw_mcp_reverified.jsonl \
  --concurrency 1 --limit 1 --force

Mark the intentional secret-redaction test values so detect-secrets does not treat them as credentials.

Signed-off-by: Chris Wing <[email protected]>
@cmunley1

Copy link
Copy Markdown
Contributor

/claude review

@claude

claude Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

SHIP — LGTM, no reliability concerns.

Reviewed the full diff (README + openclaw_agent/app.py + tests). This wires rollout-scoped Gym MCP tool access into the OpenClaw agent and threads MCP tool-call provenance into /verify.

What I verified against the correctness/async/API bars:

  • Verifier payload contract is sound. run() now always sends mcp_tool_call_provenance (possibly {}) to /verify. Per BaseVerifyRequest (base_resources_server.py:104) an empty mapping is authoritative-complete, which correctly disables the Claude-Code normalize_tool_name mcp__-prefix fallback. That's the right semantics for OpenClaw, which emits bare tool names and canonical provenance from tool-result details — no risk of misattributed tool identities corrupting scores. Non-MCP resources servers are unaffected (the fallback only runs for MCP-exposed servers).
  • Refactor of the removed HTTP self-call is safe. run() dropped the server_client.post(.../v1/responses) self-call in favor of in-process _create_episode/_create_response. Token-capture path prefixing is preserved because it lives on the model-server URL (resolve_model_base_url → apply_rollout_prefix), not the agent self-call. /verify still uses seed-session cookies — correct, since the old self-call hit the agent (which only shells out) and never touched the resources-server session.
  • Async hygiene clean. All I/O goes through server_client (aiohttp) and _run_exec (async subprocess with timeout + kill). No httpx, no ray.get, no dropped awaits. Concurrency stays bounded by self.sem.
  • Secret handling is careful. _rollout_mcp_servers validation errors never interpolate header values; the temp openclaw.json carrying the signed session header is written under the per-rollout workspace and removed in the finally of _run_openclaw on both success and failure.
  • Test coverage is real, not vacuous: transport mapping/rejection, name-collision precedence, static-server preservation, concurrent token isolation, cleanup-on-failure, and token-non-exposure in error paths and logs.

No BLOCKER/RISK/NOTE findings.

Return provenance explicitly, remove the unused response side channel, and clarify OpenClaw-specific configuration translation without changing behavior.

Signed-off-by: Chris Wing <[email protected]>
Adopt the centralized seed metadata contract and explicit execution result while preserving OpenClaw-native config and event parsing.

Signed-off-by: Chris Wing <[email protected]>
@cwing-nvidia

Copy link
Copy Markdown
Contributor Author

/claude review

@claude

claude Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

SHIP — LGTM, no reliability concerns.

Wires rollout-scoped Gym MCP into the OpenClaw agent following the same shared-infra pattern already merged for claude_code_agent/codex_agent. Checked the load-bearing paths:

  • Provenance correctness. openclaw_mcp_tool_call_provenance keys on toolResult.toolCallId, which matches the toolCall.id used for emitted function_call items (parse_openclaw_session_items), so the verifier's mcp_tool_call_provenance[call_id] aligns with the trajectory. OpenClaw reports the canonical mcpServer/mcpTool directly from tool-result metadata rather than inferring from wire names — cleaner than the alias-join path.
  • Authoritative empty dict. run() always sends NEMO_GYM_MCP_TOOL_CALL_PROVENANCE_KEY (even {}), which BaseVerifyRequest treats as authoritative. Correct here since provenance is read from actual session metadata. On TimeoutError the output_items=[]/provenance={} pair is consistent — no calls to misclassify.
  • Async hygiene. No new HTTP client; seed/verify still go through server_client.post with cookie propagation; _create_episode/_create_response run in-process. No httpx, no ray.get.
  • Config merge & collisions. Static mcp.servers are deep-merged first, then servers.update(rollout) — rollout wins same-name, other static servers survive. Matches the README contract and is covered by tests.
  • Token cleanup. The signed-header config lives under work_dir and is removed by finally: shutil.rmtree; tests assert workspace empties after both success and failure, and that concurrent runs isolate tokens.
  • Coverage. New TestRolloutMCPConfig exercises transport translation, unsupported-transport rejection without leaking the token, concurrent isolation, and cleanup; existing tests updated for the new 4-tuple _run_openclaw return.

@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Aug 26, 2026

@adil-a adil-a left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm

@anwithk
anwithk requested a review from ffrujeri August 26, 2026 16:41

@Glorf Glorf left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm

khazic pushed a commit to khazic/Gym-lao that referenced this pull request Oct 13, 2026
## What does this PR do?

README only. Tells OpenClaw users to set `context_window` to the model
server's maximum context length, and explains how OpenClaw uses it and
`max_output_tokens`. Follow-up to NVIDIA-NeMo#4476, which lets sandbox sessions use
`max_output_tokens`; there is no issue.

Why: when `context_window` is unset, OpenClaw assumes 200,000 tokens. On
a server with a smaller limit, it keeps requesting its full output limit
and does not compact in time, so long episodes can send requests the
server rejects. Gym's `vllm_model` returns an empty reply, not an error,
by default, and the run ends early.

Example, worked out from the code and not measured in a run: released
vLLM (up to 0.31) rejects a call when prompt + requested output >
`max_model_len`. At 131,072 with no `context_window`, calls fail once
the prompt passes 122,880 tokens (131,072 − 8,192 default), or 98,304
with `max_output_tokens: 32768` (131,072 − 32,768). With
`context_window: 131072`, OpenClaw lowers each call's output to fit the
room left by its estimate of the input; the estimate can undercount code
or JSON. Unreleased vLLM main (vllm-project/vllm#57035) lowers the
output instead of rejecting, but still rejects a prompt longer than
`max_model_len`.

The sandbox section now also says that the request field is rejected but
the agent config field applies, and that a `max_output_tokens` above
`context_window` is rejected (the check from NVIDIA-NeMo#4476).

## Validation

- Read the OpenClaw npm package at 2026.6.11 (pinned in
`configs/openclaw_agent.yaml`) and at 2026.6.35 (the pin in NVIDIA-NeMo#4082). Both
match the README:
- `contextWindow` defaults to 200,000 and `maxTokens` to min(8,192,
`contextWindow`) (`dist/io-*.js`);
- each call requests at most min(`maxTokens`, `contextWindow` −
estimated input − 1), where the estimate is characters / 4 × 1.25. This
applies to any base URL other than OpenAI's or Azure OpenAI's, which
covers Gym's model server (`dist/openai-transport-stream-*.js`);
- two in-run limits are computed from `contextWindow`. One is the
context guard: once a run passes its limit, OpenClaw compacts and
retries (`installToolResultContextGuard` in `dist/selection-*.js`). The
other is the cap on each tool result's size
(`resolveLiveToolResultMaxChars` in `dist/tool-result-truncation-*.js`).
- Gym code on main: `_build_openclaw_config` writes `contextWindow` and
`maxTokens` only when they are set, and `vllm_model` returns an empty
`length` completion on a context-length error unless
`propagate_context_overflow_errors` is true.
- Open PRs touching OpenClaw: NVIDIA-NeMo#3902 and NVIDIA-NeMo#2733 edit this README, and
NVIDIA-NeMo#4082 moves the pin to 2026.6.35. `git merge-tree` shows this PR adds no
conflicts with any of them.
- `pre-commit run --all-files`: passed.

## Rollouts

N/A: README-only change, with no code or config changes.

## Compatibility and benchmark impact

None from this PR. Following the advice can change rollouts with long
episodes or long tool results, because `context_window` also sets when
OpenClaw compacts and how much of a tool result it keeps.

## Checklist

- [x] I have read the [contributing
guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md).
- [x] The change is focused; unrelated "drive-by" edits are tracked as
separate issues/PRs.
- [x] Tests added or updated and pass locally, or N/A for docs-only /
non-code changes (so CI unit/server checks pass when applicable). N/A:
docs-only.
- [x] Documentation added or updated, or N/A with justification.
- [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so
CI lint/format checks pass).
- [x] New source files include the required Apache-2.0 SPDX header. N/A:
no new files.
- [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check
passes).

Signed-off-by: Abhishree <[email protected]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:agent Agent harnesses and Responses API agent behavior feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 20, 2026

@ffrujeri ffrujeri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for this, and sorry it sat so long. Main has moved on since August: OpenClaw now receives Gym MCP tools through agent-session MCPToolAccess grants (_granted_mcp_servers, #5551), and the direct /run path this PR changes is no longer the main OpenClaw path. This PR also builds on #2673, which hasn't merged, so nemo_gym.mcp and the provenance types don't exist on main. The piece still missing is per-call (server_name, tool_name) provenance; reverification still refuses MCP-exposed servers without it. Would it make sense to close this and re-land the mcpServer/mcpTool extraction on the session path once the provenance contract is settled (a rebased #2673 or a fresh PR)?

@cmunley1

Copy link
Copy Markdown
Contributor

This looks superseded by #5079, which gives OpenClaw MCP tool grants on main, and the nemo_gym.mcp base from #2673 no longer exists there. Closing for now. If #2670 still needs the per-call provenance, could you reopen just that part against main's MCPToolAccess path?

@cmunley1 cmunley1 closed this Nov 13, 2026

This branch was previously deployed

1 inactive deployment
public — fcfebad9 Deployed Aug 26, 2026 by copy-pr-bot[bot] via release / finalize / notify #1858
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(openclaw_agent): consume resources-server MCP metadata from seed_session

6 participants