Skip to content

feat(security): add ToolShieldLLMSecurityAnalyzer - #4

Closed
xli04 wants to merge 1 commit into
mainfrom
feat/toolshield-llm-analyzer
Closed

xli04 wants to merge 1 commit into
mainfrom
feat/toolshield-llm-analyzer

Conversation

@xli04

@xli04 xli04 commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

PR 1 — feat(security): add ToolShieldLLMSecurityAnalyzer

Target repo: OpenHands/software-agent-sdk
Target branch: main
Related issue: This PR implements the feature described in
OpenHands/OpenHands#14040 —
motivation, evaluation (MT-AgentRisk ASR drop from 75–88% → 14–18%),
cost analysis, and design discussion all live there. A follow-up
frontend PR (dropdown entry in Settings) will land on
All-Hands-AI/OpenHands.

Summary

Adds ToolShieldLLMSecurityAnalyzer, a new SecurityAnalyzerBase
subclass that evaluates each ActionEvent via a separate guardrail
LLM
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 (OpenHands#14040) 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

  • New file: openhands-sdk/openhands/sdk/security/toolshield_llm_analyzer.py
  • New file: openhands-sdk/openhands/sdk/security/toolshield_helpers.py —
    helper functions for populating safety_experiences:
    default_safety_experiences() (terminal + filesystem seed),
    load_safety_experiences(tool_names), and
    auto_detect_safety_experiences() which probes localhost for active
    MCP servers.
  • Updated: openhands-sdk/openhands/sdk/security/__init__.py — export
    ToolShieldLLMSecurityAnalyzer and the helpers.
  • Updated: 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 other
analyzer. Pairs with ConfirmRisky unchanged.

API

from openhands.sdk.llm import LLM
from openhands.sdk.security import ToolShieldLLMSecurityAnalyzer, ConfirmRisky

guardrail_llm = LLM(model="gpt-4o-mini", api_key=...)
analyzer = ToolShieldLLMSecurityAnalyzer(
    llm=guardrail_llm,
    history_window=20,       # default
    safety_experiences="",   # optional per-tool guidelines; see below
)

Optional — combine with the toolshield PyPI package for distilled
per-tool safety experiences:

pip install openhands-sdk[toolshield]

Three ways to populate safety_experiences:

from openhands.sdk.security import (
    ToolShieldLLMSecurityAnalyzer,
    default_safety_experiences,
    load_safety_experiences,
    auto_detect_safety_experiences,
)

# 1) Default seed (terminal + filesystem)
analyzer = ToolShieldLLMSecurityAnalyzer(
    llm=guardrail_llm,
    safety_experiences=default_safety_experiences(),
)

# 2) Explicit tool list (e.g., override with a different model's set)
analyzer = ToolShieldLLMSecurityAnalyzer(
    llm=guardrail_llm,
    safety_experiences=load_safety_experiences(
        ["terminal-mcp", "postgres-mcp"], model="gemini-3-flash-preview"
    ),
)

# 3) Auto-detect: probe localhost ports, load experiences for whatever
#    MCP servers are actually running
analyzer = ToolShieldLLMSecurityAnalyzer(
    llm=guardrail_llm,
    safety_experiences=auto_detect_safety_experiences(),
)

safety_experiences accepts any string; callers with their own source
of guidelines can bypass the helpers and pass a custom string directly.

Configurable Pydantic fields:

Field Type Default Purpose
llm LLM (required) Guardrail LLM instance; can be cheaper/smaller than the actor.
history_window int 20 Number of prior actions to include as context.
safety_experiences str "" Optional pre-generated safety guidelines injected into the system prompt.

Risk-level handling

Guardrail output Returns Rationale
Parseable RISK: LOW/MEDIUM/HIGH Matching SecurityRisk Normal path.
Text without a RISK: line SecurityRisk.HIGH + warning log Conservative: mangled response shouldn't silently allow action.
LLM infrastructure error (network, rate limit) SecurityRisk.UNKNOWN + error log Lets ConfirmRisky apply its configured fallback; failing-closed every transient blip would block every action.

Why not return HIGH on 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 HIGH here would make a single OpenRouter
hiccup 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

  1. Single string field for experiences, not a structured dict. Any
    caller (ToolShield users, in-house experience generators, manual
    policy authors) can populate safety_experiences without a new
    SDK-side schema. The canonical rendering lives in the caller's
    package.
  2. ToolShield as an optional PyPI dep, not a new SDK submodule.
    toolshield is 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.
  3. Per-tool experiences as an extension point. The ToolShield
    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 changes
    needed, and no lock-in to ToolShield-generated content.
  4. Split UNKNOWN vs HIGH on guardrail failure. See table above —
    this is the most common reviewer question we've anticipated.

Known limitations / out of scope

  • Bundled experience set covers the tools evaluated in OpenHands#14040
    (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 toolshield package; see the Issue's
    "Future work" section.
  • English-only prompts for now.

Backwards compatibility

Purely additive. The default analyzer remains LLMSecurityAnalyzer.

Test plan

  • Unit tests for _parse_risk (all three labels, parse failure path)
  • Unit test for security_risk with mocked LLM returning each label
  • Unit test for security_risk with mocked LLM raising an exception
    (verify returns UNKNOWN, not HIGH)
  • Unit test for history rendering (empty, partial, at-capacity)
  • Integration test: pair with ConfirmRisky, verify a HIGH
    decision pauses the conversation

Non-goals for this PR

  • UI surfacing (dropdown entry in Settings) — comes in a follow-up PR
    on the All-Hands-AI/OpenHands repo (see pr2_frontend.md).

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)
- Ships toolshield_helpers with default_safety_experiences(), load_safety_experiences(), and auto_detect_safety_experiences() that probe localhost for running MCP servers
- toolshield added as an optional PyPI extra

Evaluation on a 100-task MT-AgentRisk subset drops ASR from 75-88% to 14-18% across three frontier models, with 0% false positives on 50 benign Terminal-Bench tasks.

Tests: 32 unit tests. Live-smoke-tested against gemini-2.5-flash-lite classifying benign (LOW) vs destructive (HIGH) correctly.
@xli04
xli04 force-pushed the feat/toolshield-llm-analyzer branch from 0685cc8 to e00de21 Compare April 21, 2026 13:55
@xli04 xli04 closed this Apr 21, 2026
@xli04
xli04 deleted the feat/toolshield-llm-analyzer branch April 21, 2026 14:08
xli04 added a commit that referenced this pull request May 15, 2026
Addresses review #4 on OpenHands#2911.

Previously the field defaulted to ``None``, which triggered auto-load of
the ToolShield terminal + filesystem seed at ``model_post_init``. The
behavior diverged based on whether the ``[toolshield]`` optional extra
was installed: with it the seed loaded; without it the constructor
silently fell back to an empty experiences block plus a warning log.
The call site had no way to tell which path it got without inspecting
logs -- a non-determinism reviewers correctly flagged.

This commit switches to ``str = ""`` as the default. The analyzer now
runs as a bare guardrail by default (no distilled guidance, no
``toolshield`` dependency at construction time). Callers who want the
ToolShield seed opt in explicitly:

  analyzer = ToolShieldLLMSecurityAnalyzer(
      llm=guardrail_llm,
      safety_experiences=default_safety_experiences(),  # explicit
  )

``model_post_init`` loses its None-handling branch and just renders the
system prompt with whatever string the caller passed. The class
docstring and field description document the new contract.

Tests: ``test_default_none_auto_loads_terminal_and_filesystem`` and
``test_default_falls_back_gracefully_when_toolshield_missing`` (and
``test_explicit_empty_string_opts_out``) are replaced by
``test_default_is_bare_guardrail`` and ``test_opt_in_to_default_seed``.
xli04 added a commit that referenced this pull request Jun 9, 2026
toolshield 0.1.2's wheel was missing files the public API needs
(mcp_scan.py, experience_store.py, the bundled experiences) — see
CHATS-lab/ToolShield#4. 0.1.3 fixes the packaging and adds a CI guard
that builds from a clean `git archive HEAD` and asserts the wheel
contents match what the API imports, so this specific failure mode
cannot regress.

No SDK-side code change required; pure pin bump.
xli04 added a commit that referenced this pull request Jun 9, 2026
Adopts the .pr/ artefacts convention @enyst requested in PR review:
evidence that the fix works lives in version control, not just in
comment threads.

The bundle answers both blockers on this PR:

- @VascoSch92 ("fix package at source"): toolshield 0.1.3 is on PyPI
  with the issue-4 fix. `pypi-0.1.3.json` + `01-pypi-metadata.txt`
  pin the published artefacts; `02-reproducible-build.txt` shows the
  wheel + sdist built locally from `git archive HEAD` are sha256
  byte-identical to PyPI (the source tree and the published package
  are in sync, which is exactly what #4 said was broken in 0.1.2).
  `03-wheel-contents.txt` confirms the previously-untracked files
  (mcp_scan, experience_store, claude-sonnet-4.5 experiences) ship.
  `04-pypi-install-smoke.txt` is the reporter's exact smoke test
  passing against the published wheel.

- @enyst (".pr/ artefacts convention"): this directory itself.
  `05-sdk-test-fix.md` documents the small skipif marker added in
  dfa5451 so the four toolshield-dependent tests no-op cleanly
  in the sdk-tests job (which doesn't install optional extras) and
  run normally where the [toolshield] extra is present.
xli04 added a commit that referenced this pull request Jun 9, 2026
Adopts the .pr/ artefacts convention @enyst requested in PR review:
evidence that the fix works lives in version control, not just in
comment threads.

The bundle answers both blockers on this PR:

- @VascoSch92 ("fix package at source"): toolshield 0.1.3 is on PyPI
  with the issue-4 fix. `pypi-0.1.3.json` + `01-pypi-metadata.txt`
  pin the published artefacts; `02-reproducible-build.txt` shows the
  wheel + sdist built locally from `git archive HEAD` are sha256
  byte-identical to PyPI (the source tree and the published package
  are in sync, which is exactly what #4 said was broken in 0.1.2).
  `03-wheel-contents.txt` confirms the previously-untracked files
  (mcp_scan, experience_store, claude-sonnet-4.5 experiences) ship.
  `04-pypi-install-smoke.txt` is the reporter's exact smoke test
  passing against the published wheel.

- @enyst (".pr/ artefacts convention"): this directory itself.
  `05-sdk-test-fix.md` documents the small skipif marker added in
  dfa5451 so the four toolshield-dependent tests no-op cleanly
  in the sdk-tests job (which doesn't install optional extras) and
  run normally where the [toolshield] extra is present.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant