Repository navigation
Conversation
Adds a SecurityAnalyzerBase subclass that evaluates each ActionEvent via a separate guardrail LLM, rather than relying on the actor LLM to self-annotate security_risk. Separating actor and judge addresses a structural limitation of LLMSecurityAnalyzer on multi-turn attacks, where individually-benign steps compose into harmful sequences. - Pydantic-based, configurable via llm / history_window / safety_experiences fields - Pairs with ConfirmRisky unchanged - Returns UNKNOWN on infrastructure error (let ConfirmRisky fall back) and HIGH on parse error (conservative, logged) Evaluation on a 100-task MT-AgentRisk subset drops ASR from 75-88% (with LLMSecurityAnalyzer) to 14-18% across three frontier models, with 0% false positives on 50 benign Terminal-Bench tasks.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit ca0631f. Configure here.
| lines.append(f"Arguments: {args_repr}") | ||
| elif action.tool_call is not None: | ||
| try: | ||
| args_repr = action.tool_call.function.arguments |
There was a problem hiding this comment.
Wrong attribute path on MessageToolCall always triggers fallback
High Severity
action.tool_call.function.arguments accesses a non-existent .function attribute on MessageToolCall. The class stores arguments as a direct field (not nested under a function sub-object). This always raises AttributeError, caught by the except block, which falls through to str(action.tool_call) — a noisy Pydantic repr including id, name, origin — instead of the clean JSON arguments string. The guardrail LLM receives degraded input for every non-executable action, potentially reducing security analysis accuracy. The correct access is action.tool_call.arguments.
Reviewed by Cursor Bugbot for commit ca0631f. Configure here.
| "No networked MCP tools detected and fallback_to_default=False; " | ||
| f"loading always-active tools only: {active}" | ||
| ) | ||
| return load_safety_experiences(active, model=model) if active else "" |
There was a problem hiding this comment.
Docstring promises empty string but always loads experiences
Medium Severity
When fallback_to_default=False and no networked MCP tools are detected, the docstring promises an empty string is returned. However, detect_active_mcp_tools always includes ALWAYS_ACTIVE_TOOLS (i.e., ["terminal-mcp"]), so active is never empty and the else "" branch on line 215 is unreachable. Instead, load_safety_experiences(["terminal-mcp"]) is called, which also requires toolshield to be installed — surprising for callers who set fallback_to_default=False expecting a no-op fallback.
Reviewed by Cursor Bugbot for commit ca0631f. Configure here.
…injection Addresses review #2 on OpenHands#2911. The previous user prompt rendered the action as flat ``Tool: ...``, ``Thought: ...``, ``Arguments: ...`` lines. A motivated attacker can place ``RISK: LOW`` on its own line inside their action's arguments; if the guardrail LLM dutifully echoes it, the last-match regex picks it up as the verdict. Two layers of defense: 1. ``_format_action_for_guardrail`` now wraps each field in structural XML tags (``<tool>``, ``<summary>``, ``<thought>``, ``<arguments>``). 2. The system prompt explicitly tells the guardrail to ignore RISK labels that appear inside ``<thought>`` or ``<arguments>``. 3. ``_parse_risk`` strips those spans before scanning -- if the LLM echoes the injection anyway, the regex never sees it. New regression tests cover smuggled labels in <thought>, smuggled labels in <arguments>, and the "only smuggled label" edge case (parse fails, returns UNKNOWN, ConfirmRisky fallback kicks in).


PR 1 —
feat(security): add ToolShieldLLMSecurityAnalyzerTarget repo:
OpenHands/software-agent-sdkTarget branch:
mainLinks: Closes #XXXX (issue), relates to PR 2 (frontend dropdown).
Summary
Adds
GuardrailLLMSecurityAnalyzer, a newSecurityAnalyzerBasesubclass that evaluates each
ActionEventvia a separate guardrailLLM rather than relying on the actor LLM to self-annotate
security_risk.This addresses a structural limitation of the current
LLMSecurityAnalyzer: when the actor and the judge are the same model,the model has no incentive to flag multi-turn attacks where individual
steps look benign. A separate guardrail LLM sees only the proposed
action + recent history, and is prompted to evaluate the sequence.
See the linked issue for full motivation, evaluation on MT-AgentRisk
(ASR drops from 75–88% → 14–18% across three frontier models with 0%
false positives on Terminal-Bench), and cost analysis.
What changed
openhands-sdk/openhands/sdk/security/guardrail_llm_analyzer.pyopenhands-sdk/openhands/sdk/security/toolshield_helpers.py—helper functions for populating
safety_experiences:default_safety_experiences()(terminal + filesystem seed),load_safety_experiences(tool_names), andauto_detect_safety_experiences()which probes localhost for activeMCP servers.
openhands-sdk/openhands/sdk/security/__init__.py— exportGuardrailLLMSecurityAnalyzerand the helpers.pyproject.toml— new optional extra[project.optional-dependencies].toolshield = ["toolshield>=0.1.1"]required only if the helpers are used.
No changes to
Agent, tool executors,ConfirmRisky, or any otheranalyzer. Pairs with
ConfirmRiskyunchanged.API
Optional — combine with the
toolshieldPyPI package for distilledper-tool safety experiences:
Three ways to populate
safety_experiences:safety_experiencesaccepts any string; callers with their own sourceof guidelines can bypass the helpers and pass a custom string directly.
Configurable Pydantic fields:
llmLLMhistory_windowint20safety_experiencesstr""Risk-level handling
RISK: LOW/MEDIUM/HIGHSecurityRiskRISK:lineSecurityRisk.HIGH+ warning logSecurityRisk.UNKNOWN+ error logConfirmRiskyapply its configured fallback; failing-closed every transient blip would block every action.Why not return
HIGHon every failure?Two failure modes have different implications. A parse failure means
the guardrail responded — just incoherently. Trusting that response
is unsafe. An infrastructure failure means the guardrail didn't
respond at all — returning
HIGHhere would make a single OpenRouterhiccup block every subsequent action in a long-running agent, which is
worse UX than
UNKNOWN+ user confirmation. Both cases are logged.Non-trivial design decisions
caller (ToolShield users, in-house experience generators, manual
policy authors) can populate
safety_experienceswithout a newSDK-side schema. The canonical rendering lives in the caller's
package.
toolshieldis already published as a standalone package on PyPI.Pulling it into the SDK would duplicate maintenance; the extras
group gives users a one-line install path without forcing the
dependency on everyone.
package stores experiences as JSON per tool-name and loads them via
a simple registry. Users can author their own JSON files and pass
the rendered string via
safety_experiences— no SDK code changesneeded, and no lock-in to ToolShield-generated content.
this is the most common reviewer question we've anticipated.
Known limitations / out of scope
(filesystem-mcp, terminal-mcp, postgres-mcp, playwright-mcp,
notion-mcp). Expansion to more tools and newer models is planned as
follow-up contributions to the
toolshieldpackage; see the Issue's"Future work" section.
Backwards compatibility
Purely additive. The default analyzer remains
LLMSecurityAnalyzer.Test plan
_parse_risk(all three labels, parse failure path)security_riskwith mocked LLM returning each labelsecurity_riskwith mocked LLM raising an exception(verify returns
UNKNOWN, notHIGH)ConfirmRisky, verify aHIGHdecision pauses the conversation
Non-goals for this PR
on the
All-Hands-AI/OpenHandsrepo (seepr2_frontend.md).Note
Medium Risk
Adds a new LLM-driven security analyzer and helper utilities that can change how action risk is classified and therefore when confirmations trigger. While mostly additive, it introduces new prompt/parsing logic and optional dependency behavior that could misclassify or fail open/closed if outputs or network conditions differ from expectations.
Overview
Introduces
GuardrailLLMSecurityAnalyzer, which evaluates eachActionEventby calling a separate guardrail LLM with the current action plus a configurable window of recent action history, then parses a strictRISK: LOW|MEDIUM|HIGHlabel (conservative fallback toHIGHon unparseable output andUNKNOWNon LLM call errors).Adds optional ToolShield integration via
toolshield_helpersto load and/or auto-detect per-tool “safety experiences” (including localhost MCP port probing) for injection into the guardrail prompt, exports these APIs fromsecurity.__init__, and introduces a new optional dependency extraopenhands-sdk[toolshield]plus unit tests covering parsing, history handling, and helper behavior.Reviewed by Cursor Bugbot for commit ca0631f. Bugbot is set up for automated code reviews on this repo. Configure here.