Repository navigation
fix(langchain): opt-in fail-closed and quarantine blocking; scan structured tool outputs (#7) - #9
Merged
Merged
Conversation
…ctured tool outputs (#7) - fail_closed (default False) on both handlers: with raise_on_block=True a ShieldCortexError from a scan raises ContentBlockedError (result=None, original error chained as __cause__). fail_closed=True without raise_on_block=True raises ValueError at construction. - block_on_quarantine (default False): QUARANTINE is handled exactly like BLOCK. - on_tool_end reduces non-string outputs to text via one shared helper (.content string, joined text parts of a content-block list, JSON with str() fallback) and scans them; None and empty reductions are skipped. - Docstrings, README and CHANGELOG updated; defaults unchanged for API errors and QUARANTINE. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in PR #8 (path-parameter encoding). CHANGELOG.md conflict in [Unreleased] resolved by keeping both entries under one "Fixed" heading. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r ainvoke; add regression matrix B1: with the async handler, LangChain runs a sync-only tool's ainvoke through invoke in a worker thread and logs and swallows every exception the async handler raises (callbacks/manager.py _run_coros ignores raise_error). Neither BLOCK nor fail_closed scan-error raises stop that tool. Enforcing this from the handler would mean patching LangChain, so the contract is narrowed in the module docstring, README and CHANGELOG (new "Known limitation"), with the workarounds: give the tool a coroutine, or pass the sync handler with a sync client, whose exceptions propagate on that route. Tests: - Real sync-only StructuredTool (no coroutine) under ainvoke: the async handler with fail_closed lets the tool run and return on BLOCK and 503, for tool_input and tool_output (characterises LangChain's behaviour so a change is noticed); the sync handler raises, and on tool_input the tool never runs. - N2: ToolMessage list content with a non-text dict block is dropped, not JSON-encoded; a bare list return is stringified by LangChain and scanned. - N3: fail_closed matrix over chain, LLM, chat and tool input/output hooks x 401/429/503/timeout/base ShieldCortexError in sync and async handlers, plus raw httpx.ConnectError propagating unwrapped. N1: README and CHANGELOG migration note for ContentBlockedError.result being typed ScanResult | None (never None without fail_closed, but type checkers ask callers to narrow). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor
Author
|
Independent review (OpenAI-family lane), round 2 delta at exact head
Merged with the head pinned. |
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #7
Design
Defaults are unchanged for API errors and QUARANTINE. The only default behaviour change is the tool-output scanning fix.
fail_closed: bool = False(both handlers, shared_configure)fail_closed=Trueandraise_on_block=True, aShieldCortexErrorfrom a scan (401, 429, 5xx, timeout, and any other subclass the clients raise) is re-raised asContentBlockedErrorviaraise ... from exc.error.resultisNone,error.__cause__is the original error, and the message isShieldCortex blocked <source>: scan failed: <error>. LangChain stops the run.fail_closed=Truewithraise_on_block=FalseraisesValueErrorat construction. Without raising there is nothing that can stop the run, so a silent no-op option would be misleading.ContentBlockedError.__init__takesresult: ScanResult | Noneand an optionalreason. The attribute's static type widens toOptional, but runtime behaviour for verdict blocks is unchanged.block_on_quarantine: bool = FalseTrue, a QUARANTINE verdict goes through the same path as BLOCK: a warning, orContentBlockedErrorwithraise_on_block=True.Tool output reduction (
_tool_output_text, used by bothon_tool_end)str: scanned as is. Empty strings are still scanned, so the existingtest_empty_tool_input_and_output_are_still_scannedkeeps passing..content(ToolMessage/BaseMessage): that content..content(content blocks): str items plus the string"text"of dict items, joined with\n.json.dumps(obj, default=str), falling back tostr(obj)onTypeError/ValueError(for example circular references).None, and non-string outputs that reduce to empty text, are not scanned.The module docstring, both class docstrings, the README LangChain section (with an options table) and the CHANGELOG
[Unreleased]section are updated.LangChain caveat, now documented in the README: under
ainvoke, a tool with no coroutine has its async-handler callbacks run by LangChain's_run_coros, which logs and swallows exceptions. A block there is scanned and logged but does not propagate. Tools with a coroutine propagate normally. This is the same family as the existing "async handler cannot propagate frominvoke" note.Tests added (
tests/integrations/test_langchain.py, each sync and async)fail_closed=True, raise_on_block=True: 401, 503 and aReadTimeoutraiseContentBlockedErrorwith__cause__set to theShieldCortexError(AuthErrorfor 401,status_code == 503) andresult is None.fail_closed=Truewithoutraise_on_blockraisesValueError.block_on_quarantine=True: QUARANTINE raises. Default: QUARANTINE does not raise.StructuredTool(langchain_core.tools) invoked with a tool call returns aToolMessage, which is scanned and raises. A content-blockToolMessagescans"first\nsecond". A dict output is scanned as JSON and raises. ANoneoutput makes no request.default=strpath and the circular-referencestr()fallback.Gate receipts (mine, local venv with
.[dev,langchain], langchain-core 1.6.12)ruff check src/: exit 0,All checks passed!mypy src/shieldcortex/ --ignore-missing-imports: exit 0,Success: no issues found in 12 source filespython -m pytest -q: exit 0,162 passed in 2.18s🤖 Generated with Claude Code