PyRIT CLI - Command-line interface for running security scenarios.
This module provides the main entry point for the pyrit_scan command. It is a thin REST client that talks to the PyRIT backend server over HTTP. No heavy pyrit imports — all operations go through the REST API.
Functions¶
add_results_arguments¶
add_results_arguments(parser: argparse.ArgumentParser) → NoneAdd the shared scenario-results selection flags to parser.
Registers --view, --attack-result-ids, and --limit in a
scenario results group so that pyrit_scan (its scenario-results
sub-parser) and pyrit_shell (build_scenario_results_parser) expose an
identical results interface. Both surfaces take the scenario-result id as a
positional, added by the caller.
--view defaults to None (not OVERVIEW) so callers can tell an
explicit --view apart from an omitted one; resolve it with
pyrit.cli._results.resolve_view.
| Parameter | Type | Description |
|---|---|---|
parser | argparse.ArgumentParser | The parser to extend. |
build_dataset_request_fields¶
build_dataset_request_fields(args: dict[str, Any]) → dict[str, Any]Build the same edit-only dataset request for scanner and shell.
Returns:
dict[str, Any]— dict[str, Any]: Either the new request or legacy dataset fields.
Raises:
ValueError— If new and deprecated flags are mixed.
build_parameters_from_api¶
build_parameters_from_api(api_params: list[Parameter]) → list[Parameter] | NoneReturn a scenario catalog’s supported_parameters as coercion-ready Parameter objects.
The REST client deserializes catalog payloads directly into Parameter,
which reconstructs each parameter’s live param_type from its serialized
display fields (type_name / choices / is_list). The parameters are
therefore already coercion-ready, so the shell parser can apply per-element
coercion and treat list parameters as multi_value without further mapping.
| Parameter | Type | Description |
|---|---|---|
api_params | list[Parameter] | Scenario-declared parameters from GET /api/scenarios/catalog/{name}. |
Returns:
list[Parameter] | None— list[Parameter] | None: Parameter list whenapi_paramsis non-empty, elseNone.
main¶
main(args: list[str] | None = None) → intStart the PyRIT scanner CLI.
Returns:
int— Exit code (0 for success, 1 for error).
parse_args¶
parse_args(args: list[str] | None = None) → NamespaceParse command-line arguments (pass 1 — tolerant of scenario-declared flags).
The raw argv is first run through _move_verb_to_front, so global options
work before or after the verb. Pass 1 then uses parse_known_args so scenario-specific flags (e.g.
--max-turns 7) don’t error before we’ve fetched the scenario’s declared
parameters. Unknown leftovers are stashed on the Namespace as _unknown_args,
and the reordered argv as _translated_args, for the run reparse.
| Parameter | Type | Description |
|---|---|---|
args | list[str] | None | Argument list (sys.argv[1:] when None). Defaults to None. |
Returns:
Namespace— Parsed command-line arguments.
parse_dataset_filter¶
parse_dataset_filter(arg: str) → tuple[str, str]Parse a single KEY=VALUE dataset-filter token from the CLI.
Note: The arg parameter is positional (not keyword-only) so it can be used directly
as an argparse type= callable and an _ArgSpec parser. This mirrors
_parse_initializer_arg and is an intentional exception to the keyword-only style rule
for argparse compatibility.
| Parameter | Type | Description |
|---|---|---|
arg | str | The raw KEY=VALUE token. |
Returns:
tuple[str, str]— tuple[str, str]: The (key, value) pair. The value keeps its raw string form so the server can coerce and validate it.
Raises:
ValueError— If the token is not inKEY=VALUEform or the key is empty. Argparse converts this into a clean CLI error; the shell catches it directly.
parse_dataset_limit¶
parse_dataset_limit(value: str) → int | Literal['all', 'default']Parse a positive total limit, default, or all.
Returns:
int | Literal['all', 'default']— int | Literal[“all”, “default”]: The requested total limit.
Raises:
ValueError— If the value is not a supported dataset limit.
parse_dataset_source¶
parse_dataset_source(value: str) → AnyParse a named source with an optional source cap.
Returns:
Any— Validated named source.
Raises:
ValueError— If the token is malformed.
validate_log_level_argparse¶
validate_log_level_argparse(value: Any) → intArgparse-compatible wrapper around validate_log_level.
Adapts the keyword-only validator to argparse’s positional type= calling
convention and converts ValueError to argparse.ArgumentTypeError.
| Parameter | Type | Description |
|---|---|---|
value | Any | Log level string supplied by argparse. |
Returns:
int— Validated log level as aloggingmodule constant.
Raises:
argparse.ArgumentTypeError— Ifvalueis not a valid log level.
CredentialSource¶
A target credential source selected on the command line.
Parameter¶
Bases: BaseModel
Describes a parameter that a PyRIT component accepts.
This is the single JSON-serializable parameter descriptor reused across the
registry, scenarios, the backend API, and the CLI. param_type carries the
value’s live Python type and its allowed set (a Literal[...] or Enum
is the allowed set) and drives coerce_value / validate; it is not
serialized. Serialization instead projects the type into the display fields
type_name, choices, is_list, sensitive, multiline,
identity_conflicting, and copy_locked (plus required from the REQUIRED_VALUE
sentinel), so a consumer can rebuild a usable contract from the registry
without the live type travelling on the wire.
reference, when set, marks the parameter as a registry reference: its value
is supplied by name and resolved to a registered instance by the registry
layer (Parameter itself never resolves references). The live reference is
excluded from serialization; reference_type exposes its component family,
while type_name and is_list expose whether clients supply one name or a
list of names.
Coercion, strict supplied-value checks, and scalar JSON projection live here.
validate checks declarations; validate_value checks an existing value,
while validate_json_value applies the opt-in strict external-input contract.
Methods:
coerce_value¶
coerce_value(raw_value: Any) → AnyCoerce raw_value to this parameter’s declared type.
An opaque or reference parameter passes its value through unchanged (by
identity — the registry layer resolves a reference by name; an opaque
value is a live object owned by the caller). Otherwise it branches by
shape: None passes through (deep-copied), a list coerces per
element, and a scalar form (including Literal/Enum) coerces and
validates membership. Arbitrary defaulted types pass through unchanged.
| Parameter | Type | Description |
|---|---|---|
raw_value | Any | The raw value to coerce. |
Returns:
Any— The coerced value (the raw value unchanged for opaque/reference/ arbitrary types, a deep copy for theNonepassthrough, a coerced list for list types, or a coerced scalar for scalar types).
Raises:
ValueError— If the value cannot be coerced to a constrained scalar or list element type.
for_external_catalog¶
for_external_catalog() → ParameterDescribe this parameter in the form external callers send it.
A flat Collection or Sequence is described as a list, and a union as its first
alternative in declaration order that external callers can send, so
font_size: int | tuple[int, int] is described as int; Path | str keeps its own
form. Other alternatives are still accepted and coercion is unchanged; only the
catalog description changes, and registry metadata keeps the full annotation. A default the
described form cannot hold is left out, so callers omit the value and the constructor
default applies.
SeedPrompt values are described as multiline text, including loaded defaults.
Returns:
Parameter— This parameter, or a copy whoseparam_typeis the external form.
is_allowed_external_input¶
is_allowed_external_input(allowed_path_params: frozenset[str] = frozenset()) → boolReturn whether an external caller may set this parameter.
A parameter that can name a file or folder on the server is allowed only when
it is in allowed_path_params.
| Parameter | Type | Description |
|---|---|---|
allowed_path_params | frozenset[str] | Path parameters the caller has made safe. Defaults to none. |
Returns:
bool— True for an external input that names no server path, or whose path is allowed.
is_reference_to¶
is_reference_to(component_type: ComponentType) → boolWhether this parameter is a registry reference to the given component family.
A reference parameter is supplied by name and resolved to a registered
instance by the registry layer. This is the single source of truth for
“does this parameter point at a TARGET / CONVERTER / SCORER”,
so callers never re-derive it from reference internals.
| Parameter | Type | Description |
|---|---|---|
component_type | ComponentType | The component family to test against. |
Returns:
bool— True when this parameter is a reference tocomponent_type.
project_json_value¶
project_json_value(value: Any) → JsonValueProject a scalar source value without reconstructing opaque or structured state.
Returns:
JsonValue— A lossless JSON-native value for a supported scalar or list.
Raises:
ValueError— If the source requires a structured or Python-only representation.
validate¶
validate() → NoneReject a declaration with an unsupported param_type.
Supported forms are a plain scalar, a constrained scalar
(Literal/Enum), a list of any of those, a registry reference,
an opaque passthrough, or None. An otherwise-unsupported type is
tolerated only when the parameter declares a default (the builder simply
does not supply it, and the value passes through unchanged).
Raises:
ValueError— Ifparam_typeis unsupported and no default is declared.
validate_json_value¶
validate_json_value(value: Any) → AnyValidate a supplied JSON value without enabling CLI-style scalar coercion.
Enum names and values retain their declared coercion. Structured values are validated recursively by registry resolution, not by this lightweight model.
Returns:
Any— The validated value, with constrained scalars converted to their declared members.
Raises:
ValueError— If this parameter requires a Python object or the JSON type is invalid.
validate_value¶
validate_value(value: Any) → NoneCheck a resolved scalar or list without coercing or replacing it.
| Parameter | Type | Description |
|---|---|---|
value | Any | The resolved parameter value. |
Raises:
ValueError— If the value does not match its declared type or choices.
PyRITApiClient¶
Lightweight async REST client for the PyRIT backend.
No heavy pyrit imports.
Use as an async context manager::
async with PyRITApiClient(base_url="http://localhost:8000") as client:
scenarios = await client.list_scenarios_async()Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
base_url | str | Base URL of the PyRIT backend (e.g., "http://localhost:8000"). |
request_timeout | float | None | Read timeout in seconds applied to every non-polling request (catalog, results, cancel, start, etc.). Polling the live scenario-run endpoint always uses read=None regardless of this value, because the server may legitimately take many seconds to respond while a scenario is executing. Defaults to 60.0. |
auth_mode | AuthMode | Authentication behavior for protected remote backends. Defaults to 'none'. |
interactive | bool | None | Optional terminal-interactivity override. Defaults to None. |
Methods:
cancel_scenario_run_async¶
cancel_scenario_run_async(scenario_result_id: str) → ScenarioRunSummaryCancel a running scenario.
Returns:
ScenarioRunSummary— Updated summary reflecting the cancellation request.
close_async¶
close_async() → NoneClose the underlying HTTP client.
get_conversation_messages_async¶
get_conversation_messages_async(attack_result_id: str, conversation_id: str) → dict[str, Any]Get all messages for one conversation belonging to an attack result.
Returns the raw ConversationMessagesResponse payload (rather than a
typed backend view model) so the thin client stays decoupled from
pyrit.backend.models; pyrit.cli._results maps it into its own
view payload.
| Parameter | Type | Description |
|---|---|---|
attack_result_id | str | The attack result whose conversation to read. |
conversation_id | str | The conversation whose messages to return. |
Returns:
dict[str, Any]— dict[str, Any]: TheConversationMessagesResponsepayload (conversation_idplus an orderedmessageslist).
get_scenario_async¶
get_scenario_async(scenario_name: str) → RegisteredScenario | NoneGet metadata for a single scenario.
Returns:
RegisteredScenario | None— RegisteredScenario | None: The scenario, orNoneif 404.
Raises:
httpx.HTTPStatusError— For non-404 HTTP error responses.
get_scenario_run_async¶
get_scenario_run_async(scenario_result_id: str) → ScenarioRunSummaryGet the current status of a scenario run.
This is the endpoint the CLI polls while waiting for a run to finish.
It uses read=None (wait indefinitely for a response) so a server
busy executing a long-running scenario doesn’t trip the client’s
default read timeout. The other endpoints keep the configured timeout.
Returns:
ScenarioRunSummary— The current state of the scenario run.
Raises:
ServerNotAvailableError— If the server cannot be reached.
get_scenario_run_results_async¶
get_scenario_run_results_async(scenario_result_id: str) → ScenarioResultGet detailed results for a completed scenario run.
Returns:
ScenarioResult— The full scenario result deserialized from the server payload.
get_target_async¶
get_target_async(target_registry_name: str) → TargetInstance | NoneGet one registered target.
Returns:
TargetInstance | None— TargetInstance | None: The target as seen by this caller, orNoneif it is not registered.
Raises:
httpx.HTTPStatusError— For non-404 HTTP error responses.
health_check_async¶
health_check_async() → boolProbe the server health endpoint.
Returns:
bool—Trueif the server returned a healthy response.
Raises:
CompatibilityError— If the client is blocked by a compatibility failure.
list_converters_async¶
list_converters_async() → dict[str, Any]List all registered converter instances.
Returns:
dict[str, Any]—ConverterInstanceListResponsepayload.
list_datasets_async¶
list_datasets_async() → dict[str, Any]List all available datasets.
Returns:
dict[str, Any]—DatasetListResponsepayload.
list_initializers_async¶
list_initializers_async(limit: int | None = None) → list[RegisteredInitializer]List all available initializers.
| Parameter | Type | Description |
|---|---|---|
limit | int | None | Maximum number of initializers to return. None returns all initializers. Defaults to None. |
Returns:
list[RegisteredInitializer]— list[RegisteredInitializer]: Initializers in catalog order.
list_operations_async¶
list_operations_async() → list[Operation]Read the saved Operation directory without registering or resolving names.
Returns:
list[Operation]— Saved Operations in directory order.
list_scenario_runs_async¶
list_scenario_runs_async(limit: int = 100) → list[ScenarioRunListItem]List tracked scenario runs.
Returns:
list[ScenarioRunListItem]— list[ScenarioRunListItem]: All tracked scenario runs.
Raises:
ValueError— If the requested limit is invalid or a paginated response has no cursor.
list_scenarios_async¶
list_scenarios_async(limit: int | None = None) → list[RegisteredScenario]List all available scenarios.
| Parameter | Type | Description |
|---|---|---|
limit | int | None | Maximum number of scenarios to return. None returns all scenarios. Defaults to None. |
Returns:
list[RegisteredScenario]— list[RegisteredScenario]: Scenarios in catalog order.
list_targets_async¶
list_targets_async(limit: int | None = None) → list[TargetInstance]List all available targets.
| Parameter | Type | Description |
|---|---|---|
limit | int | None | Maximum number of targets to return. None returns all targets. Defaults to None. |
Returns:
list[TargetInstance]— list[TargetInstance]: Registered targets in catalog order.
register_initializer_async¶
register_initializer_async(name: str, script_content: str) → RegisteredInitializerRegister a custom initializer by uploading Python source code.
| Parameter | Type | Description |
|---|---|---|
name | str | Registry name for the initializer. |
script_content | str | Python source code containing a PyRITInitializer subclass. |
Returns:
RegisteredInitializer— The newly registered initializer.
Raises:
ServerNotAvailableError— If custom initializers are disabled (403).
set_target_credential_async¶
set_target_credential_async(target_registry_name: str, credential: str, header: str | None = None, expected_private: bool | None = None) → TargetInstanceReplace the API key, or one request header, of a target that allows credential updates.
| Parameter | Type | Description |
|---|---|---|
target_registry_name | str | The registry name of the target. |
credential | str | The new API key, access token, or header value. It is sent only in the request body. |
header | str | None | The request header to set, or None to set the API key. Defaults to None. |
expected_private | bool | None | Whether the target is expected to be private; the server refuses the update with 409 when it isn’t. None skips the check. Defaults to None. |
Returns:
TargetInstance— The updated target.
start_scenario_run_async¶
start_scenario_run_async(request: RunScenarioRequest) → ScenarioRunSummaryStart a new scenario run.
| Parameter | Type | Description |
|---|---|---|
request | RunScenarioRequest | Typed run request describing the scenario, initializers, and overrides. |
Returns:
ScenarioRunSummary— The newly-created scenario run.
RunScenarioRequest¶
Bases: _DatasetRequestModel, _ScenarioLaunchOptions
Request body for starting a scenario run.
ScenarioRunSummary¶
Bases: BaseModel
Response for a scenario run (status + result details).