Upgrading from 4.x? 5.x needs Node 22.14+ or 24+; Node 20 and 23 are unsupported. On Node 20, npm warns and still installs unless engine-strict is set; the database engine will not load. Read the guide.
Python SDK
v0.5.0Scan AI agent memory for prompt injection and credential leaks in 3 lines of code.
The SDK sends the content you scan to the ShieldCortex Cloud API (https://api.shieldcortex.ai). It needs an API key. Free tier: 500 scans/month. It does not scan on the machine. For a local scan, run shieldcortex api and call POST /api/v1/scan on 127.0.0.1:3001.
Installation
Requires Python 3.9+. Zero required dependencies beyond httpx.
Quick Start
Get an API key from the Cloud Dashboard, then scan content before it reaches your agent's memory.
from shieldcortex import ShieldCortex
client = ShieldCortex(api_key="sc_live_...")
result = client.scan("user input to remember")
if result.allowed:
save_to_memory(result)
else:
print(f"Blocked: {result.firewall.reason}")
print(f"Threats: {result.firewall.threat_indicators}")
Async Support
Full async/await support with AsyncShieldCortex.
from shieldcortex import AsyncShieldCortex, BatchItem
async with AsyncShieldCortex(api_key="sc_live_...") as client:
result = await client.scan("user input")
# Batch scan up to 100 items
batch = await client.scan_batch([
BatchItem(content="item 1"),
BatchItem(content="item 2"),
])
API Reference
| Category | Methods |
|---|---|
| Scanning | scan(), scan_batch(), scan_skill() |
| Audit | get_audit_logs(), get_audit_entry(), get_audit_stats(), get_audit_trends(), export_audit_logs(), iter_audit_logs() |
| Quarantine | get_quarantine(), get_quarantine_item(), review_quarantine_item() |
| API Keys | create_api_key(), list_api_keys(), revoke_api_key() |
| Teams | get_team(), update_team(), get_team_members(), get_usage() |
| Invites | create_invite(), list_invites(), delete_invite(), resend_invite() |
| Devices | get_devices(), register_device(), update_device(), device_heartbeat() |
| Alerts | get_alerts(), create_alert(), update_alert(), delete_alert() |
| Webhooks | get_webhooks(), create_webhook(), update_webhook(), delete_webhook(), test_webhook() |
| Firewall Rules | get_firewall_rules(), get_active_firewall_rules(), create_firewall_rule(), update_firewall_rule(), delete_firewall_rule() |
| Iron Dome Patterns | get_injection_patterns(), create_injection_pattern(), update_injection_pattern(), test_injection_pattern(), delete_injection_pattern() |
| Iron Dome Policies | get_iron_dome_policies(), create_iron_dome_policy(), update_iron_dome_policy(), set_default_iron_dome_policy(), delete_iron_dome_policy() |
Since 0.5.0, path parameters (ids, device UUIDs, export manifest ids) are percent-encoded as a single URL segment, and empty, . and .. values raise ValueError before any request is sent.
CrewAI Integration
ShieldCortexMemoryGuard is a pre-write check. It does not hook into CrewAI: content is scanned when you call guard.check() before saving it, and a threat raises MemoryBlockedError.
from shieldcortex import ShieldCortex
from shieldcortex.integrations.crewai import ShieldCortexMemoryGuard, MemoryBlockedError
client = ShieldCortex(api_key="sc_live_...")
guard = ShieldCortexMemoryGuard(client, mode="strict")
try:
guard.check("content to remember")
except MemoryBlockedError as e:
print(f"Blocked: {e.result.firewall.reason}")
mode (strict, balanced by default, or permissive) is sent to the server as the scan's defence mode. It does not change what the guard raises on: a BLOCK verdict raises, and so does QUARANTINE while block_on_quarantine is True (the default).
LangChain Integration
Add ShieldCortex as a LangChain callback handler. The callbacks scan chain inputs, LLM prompts, text in chat messages, tool inputs, LLM outputs, and tool outputs, whenever LangChain fires the matching callback. Use the async handler for ainvoke and astream, or the sync handler for invoke.
from langchain_openai import ChatOpenAI # or any LangChain chat model / LLM
from shieldcortex import AsyncShieldCortex, ShieldCortex
from shieldcortex.integrations.langchain import (
ContentBlockedError,
ShieldCortexCallbackHandler,
ShieldCortexSyncCallbackHandler,
)
model = ChatOpenAI()
async with AsyncShieldCortex(api_key="sc_live_...") as client:
handler = ShieldCortexCallbackHandler(client, raise_on_block=True)
try:
reply = await model.ainvoke("Hello", config={"callbacks": [handler]})
except ContentBlockedError as error: # also a ValueError
if error.result is not None:
print(error.result.firewall.reason, error.source_identifier)
with ShieldCortex(api_key="sc_live_...") as client:
handler = ShieldCortexSyncCallbackHandler(client, raise_on_block=True)
reply = model.invoke("Hello", config={"callbacks": [handler]})
By default only BLOCK verdicts act. With raise_on_block=True, a block stops the run with ContentBlockedError; otherwise it logs a warning. 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.
- Tool outputs, including structured ones such as
ToolMessagecontent, content blocks and dicts, are reduced to text before scanning. Non-text blocks in a content list are dropped rather than JSON-encoded, so their contents are not scanned.Noneand non-string outputs that reduce to empty text are not scanned; raw string outputs are scanned as-is. - Streaming: LLM output is scanned when the model finishes. With
streamorastream, an output block stops the run after the chunks were delivered. - LLM cache: a bare (non-chat) LLM call answered entirely from a LangChain LLM cache fires no callbacks, so neither the prompt nor the cached output is scanned and no block can stop that call. Set
cache=Falseon LLMs whose calls must be scanned. Chat models fire their start callback before the cache lookup, so a cached chat call still has its input scanned. - Sync-only tools under
ainvoke: with the async handler, a tool that has no coroutine runs in a worker thread where LangChain logs and swallows every exception the handler raises. Neither aBLOCKverdict nor afail_closedscan error stops that tool. Give the tool an async implementation, or pass the sync handler with a sync client for those calls.
Two opt-in options, available on both handlers (new in 0.5.0):
| 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). 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). |
from langchain_openai import ChatOpenAI
from shieldcortex import ShieldCortex
from shieldcortex.integrations.langchain import (
ContentBlockedError,
ShieldCortexSyncCallbackHandler,
)
model = ChatOpenAI()
with ShieldCortex(api_key="sc_live_...") as client:
handler = ShieldCortexSyncCallbackHandler(
client, raise_on_block=True, fail_closed=True, block_on_quarantine=True
)
try:
reply = model.invoke("Hello", config={"callbacks": [handler]})
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)
ContentBlockedError.result is typed ScanResult | None. Without fail_closed it is never None at runtime, but type checkers will ask you to narrow it before reading error.result.firewall.
Error Handling
from shieldcortex import ShieldCortex, AuthError, RateLimitError, ValidationError
client = ShieldCortex(api_key="sc_live_...")
try:
result = client.scan("content")
except AuthError:
print("Invalid API key")
except RateLimitError as e:
print(f"Rate limited, retry after {e.retry_after}s")
except ValidationError as e:
print(f"Invalid input: {e}")
Resources
- PyPI Package
- GitHub Repository
- Get an API Key — free tier includes 500 scans/month
- Full Documentation