Reference
Complete reference for the lakera-red-sdk package.
TypeScript
Python
Requires Node.js 22+. Install with npm install lakera-red-sdk.
LakeraRedClient
The main entry point. Creates targets and initiates scans.
TypeScript
Python
Constructor Options
TypeScript
Python
Creating a Target
Finds or creates a target by name and ensures it has a recon profile. Returns a Target
instance. The profile lives on the target and is reused by every scan, so you create a
target once before scanning.
There are three outcomes, depending on what you pass:
- With
appContext(orappContextFile): the profile is set directly and no recon runs — a handler is not needed. - Without app context, when the target has no profile yet: recon runs by relaying prompts through the handler (relay targets have no URL to probe directly), so the handler is required — omitting it throws.
- Without app context, when the target already has a profile (from a prior run or the dashboard): the existing profile is reused and no recon runs.
You can also attach ground truth — the target’s real system prompt
and/or tool definitions — via groundTruth. Like the recon profile, it lives on the
target and is reused across scans; the judge uses it to evaluate attacks more precisely.
TypeScript
Python
The first argument is an options object; the optional second argument is a session handler, used only when recon needs to run.
Returns a Target.
Fetching a Target
Fetches an existing target by its id. Read-only: unlike createOrGetTarget /
create_or_get_target, it never creates a target or runs recon. Use it to reuse a
target created earlier (for example in the dashboard or a previous run) before creating
a scan. Throws if no target with that id exists or the caller cannot access it.
There are two ways to get a target’s id:
- Read
target.targetIdfrom theTargetreturned bycreateOrGetTargetand store it for later use. - Open the target in the dashboard and copy the id from the URL:
/targets/<targetId>.
TypeScript
Python
Updating a Target
Updates an existing target’s name, recon profile, ground truth and/or response timeout.
When provided, appContext and groundTruth each replace the target’s stored value
wholesale (each is always a complete payload, matching createOrGetTarget). At least
one of name, appContext, groundTruth or responseTimeoutSeconds must be supplied.
Returns a fresh Target reflecting the updated state. Throws if no target with that id
exists or the caller cannot access it.
TypeScript
Python
Running Recon
Re-runs recon on an existing target and returns the freshly-generated recon profile. Relays the recon prompts through the handler (relay targets have no URL to probe directly), and persists the result on the target. Use it when the underlying agent has changed and its profile needs updating.
The server persists the result by sanitizing then merging onto the stored profile, so
what it keeps can differ from this run’s raw output — a total failure is a no-op that
leaves the existing profile in place. This method returns only what this run produced,
or undefined/None when it yielded nothing usable; call getTarget for the persisted
target state. Throws if no target with that id exists or the caller cannot access it.
TypeScript
Python
Target
A handle to a relay target. Returned by createOrGetTarget, getTarget, and
updateTarget; pass its targetId to createScan. It carries the target’s current
recon profile as recon and its ground truth as groundTruth, or undefined/None
when the target has none. hasRecon is a convenience getter derived from recon.
TypeScript
Python
See ReconContext for the recon fields and GroundTruth
for the ground truth fields. Reading groundTruth back returns tools as a list with
one entry per line of the stored value.
Creating a Scan
Creates a scan against a target. Returns a Scan instance. The scan does not begin
execution until scan.run() is called. The recon profile is read from the target — set
it up first with createOrGetTarget and pass its targetId.
For static, crescendo, and tool-response-poisoning, pass at least one ID in
objectives (from the built-in catalog
or your saved custom objectives), or define a custom objective for
this scan in customObjectives (TypeScript) / custom_objectives (Python). You can
combine them. Each custom objective defined in the request needs at least one success
indicator. smoke ignores both options and uses fixed probes.
TypeScript
Python
ReconContext
Describes your application so Red can tailor attacks to its capabilities and restrictions.
TypeScript
Python
YAML file (app-context.yaml):
TypeScript
Python
GroundTruth
The target’s real system prompt and/or tool definitions. The judge uses this ground truth to evaluate attacks more precisely — for example, to confirm a leaked system prompt or an out-of-policy tool call rather than inferring it — which reduces false positives.
Ground truth is attached to the target (via createOrGetTarget or
updateTarget), persisted on it, and reused across every scan. At
least one field must be provided; both are optional, so supply whichever you have.
tools is a list of strings — one entry per tool, commonly each tool’s JSON schema, but
any textual description of a tool works. The entries are joined into a single string
when stored, so reading the target back returns one entry per line.
TypeScript
Python
Ground truth can also be carried in the appContextFile YAML via its
systemPrompt / tools keys, so a single file fully describes a target. When both the
file and an inline groundTruth / ground_truth are supplied, the inline value wins.
CustomObjective
A custom objective defined in a scan request is stored with that scan, without being
added to the objectives library. Supply its full definition in customObjectives
(TypeScript) or custom_objectives (Python). Its key becomes the objectiveId /
objective_id in SDK results; name is the readable label in dashboard scan results.
TypeScript
Python
Custom objectives defined in the request can be combined with built-in or saved custom
IDs in objectives. Their keys must not overlap with those IDs.
Scan
Manages scan execution and result retrieval.
Properties
TypeScript
Python
The dashboardLink property returns the URL to the scan’s page on the Lakera Red
dashboard. The server automatically redirects to the progress view while the scan is
still running. Available immediately after creating the scan.
Run
Executes the scan. Polls the server for attack messages and invokes your handler for each concurrent session. Returns when the scan completes or times out.
TypeScript
Python
Use the finally block to release agent resources (connections, memory) once a session
ends. This is especially important for crescendo sessions that maintain
state across multiple turns.
Behavior:
- Recon runs at target creation, not here — by the time
run()starts, the target already has its profile, so your handler only receives attack sessions. - Manages concurrent sessions up to the configured
concurrencylimit - Retries on network errors with exponential backoff (1s–5s)
- Stops automatically after 3 minutes with no new messages from the server. Time spent waiting on your handler’s reply does not count, so a slow agent does not end the run
- Ends a session when its response timeout passes before your handler replies
- If your handler throws/raises before calling
respond(), the SDK submits an error to the server on your behalf
Get Results
Retrieves evaluated scan results.
TypeScript
Python
Returns a ScanResults object:
Get Dashboard Link
Returns the URL to the scan’s report page on the Lakera Red dashboard. The server automatically redirects to the progress view while the scan is still running.
TypeScript
Python
Write Results
Writes results to a JSON file and returns the resolved absolute path.
TypeScript
Python
Session
Passed to your scan.run() handler. An async iterable that yields attack messages.
TypeScript
Python
A session carries two ids:
relaySessionId(relay_session_idin Python) is Red’s id for the session. It is not the session id your tools report with.sessionId(session_idin Python) is your own session id, as set with setSessionId. It isundefined(Nonein Python) until you set it.
session.id is a deprecated alias of relaySessionId.
SessionMessage
TypeScript
Python
Response Timeout
Red waits a limited time for your handler to answer each prompt. The limit is the
target’s responseTimeoutSeconds, 300 seconds unless you set it on
createOrGetTarget or updateTarget.
When the time runs out before your handler replies, only that session’s conversation ends. Other sessions keep running, including other attacks on the same objective.
- The conversation’s result entry is recorded with a
TARGET_TIMEOUTerror, for exampleRelay target relay:my-agent: SDK did not respond within 300s. - The SDK ends the session. A reply sent after that is dropped, and the session yields no further messages.
scan.run()does not wait for a handler that never returns.
TypeScript
Python
The message’s signal aborts at that point. Pass it to the calls that produce the reply
so they stop too.
setSessionId
Binds this session to the session id your tools report with, so the traced tool activity
joins this scan. Set once, before your agent runs its tools. For
Tool Response Poisoning scans, set it before responding to
the first message. Read it back with session.sessionId (session.session_id in
Python). See Trace Agent Tools.
TypeScript
Python
Tool Tracing
Report each real tool call and its result to Red during a scan, so evaluation reflects
what your agent actually did and not only its final reply. The reported result is
returned unchanged unless a Tool Response Poisoning scan
splices a payload into it. Always use the returned value in your agent. A no-op unless
LAKERA_RED_TOOL_INTERCEPT is set. See Trace Agent Tools
for the full guide.
interceptTool
Call at the tool boundary with your tool’s real result. Returns the result to hand back to your agent: unchanged while tracing, and potentially poisoned during a Tool Response Poisoning scan.
TypeScript
Python
Returns Promise<JsonValue>.
Environment variables
ScanResultEntry
Each entry in the results array:
TypeScript
Python
isSuccessful / is_successful is computed by the platform at its default success
threshold, so it always matches the verdict shown on the dashboard; entries with an
error are never successful. To apply your own pass/fail criteria, read the
evaluation fields instead.
Evaluation
The evaluator’s verdict for one objective. Every field is optional: errored or pre-scoring entries carry a partial or absent evaluation, so custom gating logic should treat missing scores as not successful.
TypeScript
Python
Logging
The SDK outputs structured JSON logs to stderr by default, keeping stdout clean for your application output.
Configuration
Control log verbosity via the logLevel constructor parameter or the
LAKERA_RED_LOG_LEVEL environment variable:
Custom Logger
Provide your own logger to integrate with your existing observability stack:
TypeScript
Python
Logger Utilities
TypeScript
Python
Examples Helper
TypeScript
Python
Installing lakera-red-sdk also installs a lakera-red-sdk command for bootstrapping
example projects.
The bundled examples are pinned to the installed SDK version, so they always match the package you’re using.
Strategies
The strategy controls how the SDK generates adversarial prompts.
TypeScript
Python
Static
Sends a fixed set of adversarial prompts per objective. Each prompt is independent — there is no conversational escalation between turns. This makes static scans fast, deterministic, and well-suited for CI gates where you want quick, reproducible results.
TypeScript
Python
Crescendo
A multi-turn strategy where the attacker gradually escalates over several conversational turns within a single session. Crescendo better simulates real-world persistent attackers and tests whether your agent can maintain its guardrails under sustained conversational pressure.
TypeScript
Python
Smoke
Server-defined canned probes for a quick sanity check. Objectives are ignored — the server uses its own fixed probe set.
TypeScript
Python
Tool Response Poisoning
Indirect attacks reach an agent through content it loads while handling a user’s request, rather than through the user’s message. It may come from a tool response, an MCP response, or a file read by the agent’s harness. Tool Response Poisoning is Red’s first indirect attack strategy. After a greeting that binds the session, each run sends your agent a benign task designed to trigger a tool call. Red splices an adversarial payload into a returned tool result before the agent reads it. The scan tests whether that payload can lead the agent to meet the attack objective. Once the trigger turn returns, Red evaluates the agent’s reply even if no tool call was reported or no result could carry the payload. Red tracks delivery separately; a score alone does not show that the agent resisted a delivered injection.
Requirements:
- For SDK scans, use a relay target. The strategy also supports stateful targets in scans started outside the SDK. Stateless targets and scans in the legacy Evaluation Studio are unsupported.
- Instrument your agent’s tool boundary with
interceptTool(TypeScript) orintercept_tool(Python), and setLAKERA_RED_TOOL_INTERCEPTas described in Trace Agent Tools. Return the function’s value to your agent so it can consume a poisoned result. - Associate traced tool calls with the scan. For an SDK relay target, call
setSessionId(TypeScript) orset_session_id(Python) before responding to the first message in each session. The run fails if no session id is bound at that point. For a stateful target, pass the session id returned by the target assessionId(TypeScript) orsession_id(Python) in each tracing call.
Each run is one session of two turns: a greeting that binds the session, then the
trigger prompt. Red poisons the first reported tool result that can carry text
during the trigger turn. It appends the payload to plain text. For JSON, it appends
inside an existing string field, preferring prose-named fields and skipping fields named
like IDs or URLs. This works for serialized JSON and native objects or arrays, including
the MCP content[].text shape. The returned value keeps its top-level type, and JSON
keeps its structure. Red leaves a result with no suitable string unchanged and tries the
next traced result. Numbers, booleans, and null pass through. If no result can carry the
payload, the attack is not delivered. A non-JSON string is treated as plain text, so an
appended payload may invalidate another structured text format such as CSV or XML.
Red writes the trigger prompts from the target’s recon profile. Give the target ground truth with your tool definitions so the prompts aim at the tools your agent really has.
TypeScript
Python
Red bounds the requested number to 1–100. If generation produces fewer usable trigger-payload pairs, the scan runs those available and logs a warning; if it produces none for an objective, the scan fails before starting sessions.
Choosing a Strategy
Choose static for fast regression checks and crescendo for
deeper adversarial evaluation during pre-release security reviews. Use smoke
for a quick check with canned probes. Choose
tool-response-poisoning when your agent reads tool results
it doesn’t control, such as web pages, emails, documents, or tickets; it needs tool
tracing in place.
Objective IDs
The Default Objectives table is the
current catalog of built-in IDs, names, and descriptions. Pass selected built-in IDs or
saved custom objective IDs in objectives when creating a scan. The
SDK does not automatically select all 23 defaults; pass all their IDs explicitly to run
the full basic scope.
To define a custom objective for this scan, pass its full definition in
customObjectives (TypeScript) or custom_objectives (Python). See
CustomObjective for required fields, including success indicators.
smoke uses fixed probes and ignores either objective option.