Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,50 @@

## [Unreleased]

Defaults are unchanged for API errors and QUARANTINE: a `ShieldCortexError`
from a scan is still logged and skipped, and QUARANTINE still does not act,
unless you opt in with the new options below.

### Added

- LangChain handlers: `fail_closed` (default `False`). With
`raise_on_block=True`, a `ShieldCortexError` from a scan (401, 429, 5xx,
timeout, and every other API error) raises `ContentBlockedError` with
`result=None` and the original error as `__cause__`, so the run stops
(except for sync-only tools under `ainvoke` with the async handler; see
Known limitation). `fail_closed=True` without `raise_on_block=True` raises `ValueError` at
construction.
- `ContentBlockedError.result` is now typed `ScanResult | None`. It is only
`None` with `fail_closed=True`, so default-option callers never see `None`
at runtime, but type checkers will ask them to narrow before reading
`error.result.firewall`:
`if error.result is not None: print(error.result.firewall.reason)`.
- LangChain handlers: `block_on_quarantine` (default `False`). When `True`,
a QUARANTINE verdict is treated exactly like BLOCK.

### Fixed

- LangChain `on_tool_end` now scans structured tool outputs (ToolMessage
content, content blocks, dicts) instead of skipping them. Non-string
outputs are reduced to text (`.content` string, joined text parts of a
content-block list, or JSON with a `str()` fallback); non-text blocks in a
content list are dropped, not JSON-encoded; `None` and outputs
that reduce to empty text are not scanned. String outputs are scanned as
before.
- Path parameters (ids, device UUIDs, export manifest ids) are now
percent-encoded as a single URL segment, so `/`, `?`, `#`, `%`, spaces and
non-ASCII characters can no longer change the route. Empty, `.` and `..`
values raise `ValueError` before any request is sent.

### Known limitation

- With the async handler, a sync-only tool (no coroutine) called through
`ainvoke` runs in a worker thread where LangChain logs and swallows every
exception the handler raises. Neither BLOCK verdicts nor `fail_closed`
scan-error raises stop that tool: it runs and `ainvoke` returns its output.
Give the tool an async implementation, or pass the sync handler (with a
sync client) for those calls; its exceptions propagate on that route.

## 0.4.0 — 2026-10-16

Minor release: the LangChain integration now stops the run on BLOCK, scans
Expand Down
56 changes: 49 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ except MemoryBlockedError as e:
## LangChain Integration

The callbacks scan chain inputs, LLM prompts, text in chat messages, tool inputs,
LLM outputs, and string tool outputs. Use the async handler for `ainvoke` and
LLM outputs, and tool outputs. Use the async handler for `ainvoke` and
`astream`, or the sync handler for `invoke`:

```python
Expand All @@ -140,8 +140,8 @@ with ShieldCortex(api_key="sc_live_...") as client:
reply = model.invoke("Hello", config={"callbacks": [handler]})
```

Only `BLOCK` verdicts act today. With `raise_on_block=True`, a block stops the
run with `ContentBlockedError`; otherwise it logs a warning. Use the matching
By default only `BLOCK` verdicts act. With `raise_on_block=True`, a block stops
the run with `ContentBlockedError`; otherwise it logs a warning. Use the matching
handler for the call mode: LangChain cannot propagate an async handler's block
from `invoke`.

Expand All @@ -153,10 +153,52 @@ from `invoke`.
output block stops the run after delivery and cannot prevent exposure.
Buffer the stream yourself if blocked output must never be shown. Input
scans still run before the model starts.
- **Scan errors:** a `ShieldCortexError` from the scan call (HTTP error,
timeout) is logged and that scan is skipped. Other exceptions, such as
connection errors, are not caught: with `raise_on_block=True` they stop the
run, otherwise LangChain logs them.
- **Tool outputs** are reduced to text before scanning: strings as is; objects
with string `.content` (such as `ToolMessage`) by that content; a list
`.content` by its string items and the string `text` of its dict items,
joined by newlines; anything else as JSON (`default=str`), falling back to
`str()`. Other blocks in a list `.content`, such as images or dicts without
a string `text` (for example `{"payload": "..."}`), are dropped rather than
JSON-encoded, so their contents are not scanned. `None` and non-string outputs that reduce
to empty text are not scanned.
- **Sync-only tools under `ainvoke`:** LangChain runs a tool that has no
coroutine in a worker thread and logs and swallows every exception the
async handler raises there. Neither a `BLOCK` verdict nor a `fail_closed`
scan error stops that tool: it runs and `ainvoke` returns its output. Give
the tool an async implementation (`coroutine=` on `StructuredTool`, or
`_arun`), or pass the sync handler with a sync client for those calls,
e.g. `await tool.ainvoke(args, config={"callbacks": [sync_handler]})`; its
exceptions do propagate on that route.
- **Scan errors:** by default a `ShieldCortexError` from the scan call (any
HTTP error such as 401, 429 or 5xx, or a timeout) is logged and that scan is
skipped, so the content passes. Other exceptions, such as connection errors,
are not caught: with `raise_on_block=True` they stop the run, otherwise
LangChain logs them.

Two opt-in options, available on both handlers:

| Option | Default | Effect |
|---|---|---|
| `fail_closed` | `False` | With `raise_on_block=True`, a `ShieldCortexError` from a scan raises `ContentBlockedError` instead of being logged and skipped (except for sync-only tools under `ainvoke` with the async handler, see above). `error.result` is `None` and `error.__cause__` is the original error. Requires `raise_on_block=True`; otherwise the constructor raises `ValueError`. |
| `block_on_quarantine` | `False` | Treat `QUARANTINE` verdicts exactly like `BLOCK` (warn, or raise with `raise_on_block=True`). |

```python
handler = ShieldCortexSyncCallbackHandler(
client, raise_on_block=True, fail_closed=True, block_on_quarantine=True
)
```

`ContentBlockedError.result` is typed `ScanResult | None`. Without
`fail_closed` it is never `None` at runtime, but type checkers will still ask
you to narrow it before reading `error.result.firewall`:

```python
except ContentBlockedError as error:
if error.result is None: # fail_closed: the scan itself failed
print("scan failed:", error.__cause__)
else:
print(error.result.firewall.reason)
```

## Audit Logs

Expand Down
152 changes: 124 additions & 28 deletions src/shieldcortex/integrations/langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,50 @@

The async handler is for ``ainvoke``/``astream``; the sync handler is for
``invoke``. They scan chain inputs, LLM prompts, chat message text, tool inputs,
LLM outputs, and string tool outputs. Chat message text means string content,
string blocks, and dict blocks whose ``text`` is a string and whose ``type`` is
``"text"`` or absent. Only ``BLOCK`` verdicts act today. With
``raise_on_block=True``, a block raises :class:`ContentBlockedError`.
LLM outputs, and tool outputs. Chat message text means string content, string
blocks, and dict blocks whose ``text`` is a string and whose ``type`` is
``"text"`` or absent.

Tool outputs are reduced to text before scanning: a string is scanned as is;
an object with string ``.content`` (such as a ``ToolMessage``) is scanned by
that content; a list ``.content`` is scanned as its string items and the
string ``text`` of its dict items, joined by newlines (other blocks, such as
images or dicts without a string ``text``, are dropped, not JSON-encoded);
anything else is JSON-encoded (``default=str``), falling back to ``str()``.
``None``, and non-string outputs that reduce to empty text, are not scanned.

By default only ``BLOCK`` verdicts act. ``block_on_quarantine=True`` treats
``QUARANTINE`` the same way. With ``raise_on_block=True``, a block raises
:class:`ContentBlockedError`; otherwise it is logged as a warning.

LLM output is scanned in ``on_llm_end``, after the model finishes. With
``stream``/``astream`` every chunk has already reached the caller by then, so
an output block stops the run after delivery and cannot prevent exposure.

A :class:`~shieldcortex.errors.ShieldCortexError` from the scan call (HTTP
error, timeout) is logged and that scan is skipped. Other exceptions, such as
connection errors, are not caught: with ``raise_on_block=True`` they stop the
run, otherwise LangChain logs them.
By default a :class:`~shieldcortex.errors.ShieldCortexError` from the scan
call (any HTTP error such as 401, 429 or 5xx, or a timeout) is logged and that
scan is skipped, so the content passes (fail open). With ``fail_closed=True``
and ``raise_on_block=True``, such an error instead raises
:class:`ContentBlockedError` with ``result=None`` and the original error as
``__cause__``, stopping the run. ``fail_closed=True`` without
``raise_on_block=True`` raises ``ValueError`` at construction, because there
would be nothing to stop the run with. Other exceptions, such as connection
errors, are not caught: with ``raise_on_block=True`` they stop the run,
otherwise LangChain logs them.

Exception: with the async handler, a tool without a coroutine (a sync-only
tool) called through ``ainvoke`` runs in a worker thread, and LangChain logs
and swallows every exception the async handler raises there. Neither a block
nor a ``fail_closed`` scan error stops that tool: it runs and its output is
returned. Give such tools a coroutine, or attach the sync handler (with a
sync client) to those calls; its exceptions do propagate on that route.

Install with ``pip install shieldcortex[langchain]``.
"""

from __future__ import annotations

import json
import logging
from typing import Any, Literal

Expand All @@ -43,12 +68,22 @@


class ContentBlockedError(ValueError):
"""A ``BLOCK`` verdict, with the scan result and source identifier."""
"""Blocked content, with the scan result and source identifier.

def __init__(self, result: ScanResult, source_identifier: str) -> None:
Raised for a ``BLOCK`` verdict (or ``QUARANTINE`` with
``block_on_quarantine=True``). With ``fail_closed=True`` it is also raised
when the scan itself fails: then ``result`` is ``None`` and the
:class:`~shieldcortex.errors.ShieldCortexError` is the ``__cause__``.
"""

def __init__(
self, result: ScanResult | None, source_identifier: str, reason: str | None = None
) -> None:
self.result = result
self.source_identifier = f"langchain:{source_identifier}"
super().__init__(f"ShieldCortex blocked {source_identifier}: {result.firewall.reason}")
if reason is None:
reason = result.firewall.reason if result is not None else "scan failed"
super().__init__(f"ShieldCortex blocked {source_identifier}: {reason}")


def _chat_texts(messages: list[list[BaseMessage]]) -> list[str]:
Expand All @@ -72,6 +107,31 @@ def _chat_texts(messages: list[list[BaseMessage]]) -> list[str]:
return texts


def _tool_output_text(output: Any) -> str | None:
"""Reduce a tool output to the text to scan, or ``None`` to skip it."""
if output is None:
return None
if isinstance(output, str):
return output
content = getattr(output, "content", None)
if isinstance(content, str):
text = content
elif isinstance(content, list):
parts: list[str] = []
for block in content:
if isinstance(block, str):
parts.append(block)
elif isinstance(block, dict) and isinstance(block.get("text"), str):
parts.append(block["text"])
text = "\n".join(part for part in parts if part)
else:
try:
text = json.dumps(output, default=str)
except (TypeError, ValueError):
text = str(output)
return text or None


def _output_texts(response: LLMResult) -> list[str]:
return [
generation.text for group in response.generations for generation in group if generation.text
Expand All @@ -85,15 +145,27 @@ class _ScanLogic:
scan_inputs: bool
scan_outputs: bool
raise_on_block: bool
fail_closed: bool
block_on_quarantine: bool
audit_ids: list[int]

def _configure(
self, mode: Mode, scan_inputs: bool, scan_outputs: bool, raise_on_block: bool
self,
mode: Mode,
scan_inputs: bool,
scan_outputs: bool,
raise_on_block: bool,
fail_closed: bool = False,
block_on_quarantine: bool = False,
) -> None:
if fail_closed and not raise_on_block:
raise ValueError("fail_closed=True requires raise_on_block=True")
self.mode = mode
self.scan_inputs = scan_inputs
self.scan_outputs = scan_outputs
self.raise_on_block = raise_on_block
self.fail_closed = fail_closed
self.block_on_quarantine = block_on_quarantine
self.audit_ids = []

def _scan_options(self, source_identifier: str) -> dict[str, Any]:
Expand All @@ -102,9 +174,15 @@ def _scan_options(self, source_identifier: str) -> dict[str, Any]:
"config": ScanConfig(mode=self.mode),
}

def _handle_error(self, exc: ShieldCortexError, source_identifier: str) -> None:
if self.fail_closed:
raise ContentBlockedError(None, source_identifier, f"scan failed: {exc}") from exc
logger.warning("ShieldCortex scan error: %s", exc)

def _handle_result(self, result: ScanResult, source_identifier: str) -> None:
self.audit_ids.append(result.audit_id)
if result.firewall.result == "BLOCK":
verdict = result.firewall.result
if verdict == "BLOCK" or (verdict == "QUARANTINE" and self.block_on_quarantine):
error = ContentBlockedError(result, source_identifier)
if self.raise_on_block:
raise error
Expand All @@ -115,10 +193,14 @@ class ShieldCortexCallbackHandler(_ScanLogic, AsyncCallbackHandler):
"""Async LangChain handler for ``ainvoke`` and ``astream``.

Scans chain inputs, LLM prompts, chat message text, tool inputs, LLM
outputs, and string tool outputs. ``raise_on_block=True`` propagates
:class:`ContentBlockedError` (a ``ValueError``). Only ``BLOCK`` acts.
Streamed output is scanned after delivery; see the module docstring for
that and for which scan errors are logged.
outputs, and tool outputs (structured outputs are reduced to text).
``raise_on_block=True`` propagates :class:`ContentBlockedError` (a
``ValueError``). ``BLOCK`` acts; ``block_on_quarantine=True`` (default
``False``) makes ``QUARANTINE`` act too. ``fail_closed=True`` (default
``False``, requires ``raise_on_block=True``) raises on scan errors instead
of logging and skipping them. Streamed output is scanned after delivery,
and nothing this handler raises stops a sync-only tool under ``ainvoke``;
see the module docstring for both and for the reduction rules.
"""

def __init__(
Expand All @@ -129,9 +211,13 @@ def __init__(
scan_inputs: bool = True,
scan_outputs: bool = True,
raise_on_block: bool = False,
fail_closed: bool = False,
block_on_quarantine: bool = False,
) -> None:
self.client = client
self._configure(mode, scan_inputs, scan_outputs, raise_on_block)
self._configure(
mode, scan_inputs, scan_outputs, raise_on_block, fail_closed, block_on_quarantine
)
self.raise_error = raise_on_block

async def on_chain_start(
Expand Down Expand Up @@ -166,14 +252,16 @@ async def on_tool_start(
await self._scan(input_str, "tool_input")

async def on_tool_end(self, output: Any, **kwargs: Any) -> None:
if self.scan_outputs and isinstance(output, str):
await self._scan(output, "tool_output")
if self.scan_outputs:
text = _tool_output_text(output)
if text is not None:
await self._scan(text, "tool_output")

async def _scan(self, content: str, source_identifier: str) -> None:
try:
result = await self.client.scan(content, **self._scan_options(source_identifier))
except ShieldCortexError as exc:
logger.warning("ShieldCortex scan error: %s", exc)
self._handle_error(exc, source_identifier)
return
self._handle_result(result, source_identifier)

Expand All @@ -182,9 +270,11 @@ class ShieldCortexSyncCallbackHandler(_ScanLogic, BaseCallbackHandler):
"""Sync LangChain handler for ``invoke`` with the same scanning options.

``raise_on_block=True`` propagates :class:`ContentBlockedError` (a
``ValueError``). Only ``BLOCK`` acts. Streamed output is scanned after
delivery; see the module docstring for that and for which scan errors
are logged.
``ValueError``). ``BLOCK`` acts; ``block_on_quarantine=True`` (default
``False``) makes ``QUARANTINE`` act too. ``fail_closed=True`` (default
``False``, requires ``raise_on_block=True``) raises on scan errors instead
of logging and skipping them. Streamed output is scanned after delivery;
see the module docstring for that and for the reduction rules.
"""

def __init__(
Expand All @@ -195,9 +285,13 @@ def __init__(
scan_inputs: bool = True,
scan_outputs: bool = True,
raise_on_block: bool = False,
fail_closed: bool = False,
block_on_quarantine: bool = False,
) -> None:
self.client = client
self._configure(mode, scan_inputs, scan_outputs, raise_on_block)
self._configure(
mode, scan_inputs, scan_outputs, raise_on_block, fail_closed, block_on_quarantine
)
self.raise_error = raise_on_block

def on_chain_start(
Expand Down Expand Up @@ -228,13 +322,15 @@ def on_tool_start(self, serialized: dict[str, Any], input_str: str, **kwargs: An
self._scan(input_str, "tool_input")

def on_tool_end(self, output: Any, **kwargs: Any) -> None:
if self.scan_outputs and isinstance(output, str):
self._scan(output, "tool_output")
if self.scan_outputs:
text = _tool_output_text(output)
if text is not None:
self._scan(text, "tool_output")

def _scan(self, content: str, source_identifier: str) -> None:
try:
result = self.client.scan(content, **self._scan_options(source_identifier))
except ShieldCortexError as exc:
logger.warning("ShieldCortex scan error: %s", exc)
self._handle_error(exc, source_identifier)
return
self._handle_result(result, source_identifier)
Loading
Loading