Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

pyrit.cli.pyrit_scan

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) → None

Add 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.

ParameterTypeDescription
parserargparse.ArgumentParserThe 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:

Raises:

build_parameters_from_api

build_parameters_from_api(api_params: list[Parameter]) → list[Parameter] | None

Return 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.

ParameterTypeDescription
api_paramslist[Parameter]Scenario-declared parameters from GET /api/scenarios/catalog/{name}.

Returns:

main

main(args: list[str] | None = None) → int

Start the PyRIT scanner CLI.

Returns:

parse_args

parse_args(args: list[str] | None = None) → Namespace

Parse 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.

ParameterTypeDescription
argslist[str] | NoneArgument list (sys.argv[1:] when None). Defaults to None.

Returns:

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.

ParameterTypeDescription
argstrThe raw KEY=VALUE token.

Returns:

Raises:

parse_dataset_limit

parse_dataset_limit(value: str) → int | Literal['all', 'default']

Parse a positive total limit, default, or all.

Returns:

Raises:

parse_dataset_source

parse_dataset_source(value: str) → Any

Parse a named source with an optional source cap.

Returns:

Raises:

validate_log_level_argparse

validate_log_level_argparse(value: Any) → int

Argparse-compatible wrapper around validate_log_level.

Adapts the keyword-only validator to argparse’s positional type= calling convention and converts ValueError to argparse.ArgumentTypeError.

ParameterTypeDescription
valueAnyLog level string supplied by argparse.

Returns:

Raises:

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) → Any

Coerce 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.

ParameterTypeDescription
raw_valueAnyThe raw value to coerce.

Returns:

Raises:

for_external_catalog

for_external_catalog() → Parameter

Describe 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:

is_allowed_external_input

is_allowed_external_input(allowed_path_params: frozenset[str] = frozenset()) → bool

Return 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.

ParameterTypeDescription
allowed_path_paramsfrozenset[str]Path parameters the caller has made safe. Defaults to none.

Returns:

is_reference_to

is_reference_to(component_type: ComponentType) → bool

Whether 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.

ParameterTypeDescription
component_typeComponentTypeThe component family to test against.

Returns:

project_json_value

project_json_value(value: Any) → JsonValue

Project a scalar source value without reconstructing opaque or structured state.

Returns:

Raises:

validate

validate() → None

Reject 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:

validate_json_value

validate_json_value(value: Any) → Any

Validate 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:

Raises:

validate_value

validate_value(value: Any) → None

Check a resolved scalar or list without coercing or replacing it.

ParameterTypeDescription
valueAnyThe resolved parameter value.

Raises:

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:

ParameterTypeDescription
base_urlstrBase URL of the PyRIT backend (e.g., "http://localhost:8000").
request_timeoutfloat | NoneRead 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_modeAuthModeAuthentication behavior for protected remote backends. Defaults to 'none'.
interactivebool | NoneOptional terminal-interactivity override. Defaults to None.

Methods:

cancel_scenario_run_async

cancel_scenario_run_async(scenario_result_id: str) → ScenarioRunSummary

Cancel a running scenario.

Returns:

close_async

close_async() → None

Close 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.

ParameterTypeDescription
attack_result_idstrThe attack result whose conversation to read.
conversation_idstrThe conversation whose messages to return.

Returns:

get_scenario_async

get_scenario_async(scenario_name: str) → RegisteredScenario | None

Get metadata for a single scenario.

Returns:

Raises:

get_scenario_run_async

get_scenario_run_async(scenario_result_id: str) → ScenarioRunSummary

Get 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:

Raises:

get_scenario_run_results_async

get_scenario_run_results_async(scenario_result_id: str) → ScenarioResult

Get detailed results for a completed scenario run.

Returns:

get_target_async

get_target_async(target_registry_name: str) → TargetInstance | None

Get one registered target.

Returns:

Raises:

health_check_async

health_check_async() → bool

Probe the server health endpoint.

Returns:

Raises:

list_converters_async

list_converters_async() → dict[str, Any]

List all registered converter instances.

Returns:

list_datasets_async

list_datasets_async() → dict[str, Any]

List all available datasets.

Returns:

list_initializers_async

list_initializers_async(limit: int | None = None) → list[RegisteredInitializer]

List all available initializers.

ParameterTypeDescription
limitint | NoneMaximum number of initializers to return. None returns all initializers. Defaults to None.

Returns:

list_operations_async

list_operations_async() → list[Operation]

Read the saved Operation directory without registering or resolving names.

Returns:

list_scenario_runs_async

list_scenario_runs_async(limit: int = 100) → list[ScenarioRunListItem]

List tracked scenario runs.

Returns:

Raises:

list_scenarios_async

list_scenarios_async(limit: int | None = None) → list[RegisteredScenario]

List all available scenarios.

ParameterTypeDescription
limitint | NoneMaximum number of scenarios to return. None returns all scenarios. Defaults to None.

Returns:

list_targets_async

list_targets_async(limit: int | None = None) → list[TargetInstance]

List all available targets.

ParameterTypeDescription
limitint | NoneMaximum number of targets to return. None returns all targets. Defaults to None.

Returns:

register_initializer_async

register_initializer_async(name: str, script_content: str) → RegisteredInitializer

Register a custom initializer by uploading Python source code.

ParameterTypeDescription
namestrRegistry name for the initializer.
script_contentstrPython source code containing a PyRITInitializer subclass.

Returns:

Raises:

set_target_credential_async

set_target_credential_async(target_registry_name: str, credential: str, header: str | None = None, expected_private: bool | None = None) → TargetInstance

Replace the API key, or one request header, of a target that allows credential updates.

ParameterTypeDescription
target_registry_namestrThe registry name of the target.
credentialstrThe new API key, access token, or header value. It is sent only in the request body.
headerstr | NoneThe request header to set, or None to set the API key. Defaults to None.
expected_privatebool | NoneWhether 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:

start_scenario_run_async

start_scenario_run_async(request: RunScenarioRequest) → ScenarioRunSummary

Start a new scenario run.

ParameterTypeDescription
requestRunScenarioRequestTyped run request describing the scenario, initializers, and overrides.

Returns:

RunScenarioRequest

Bases: _DatasetRequestModel, _ScenarioLaunchOptions

Request body for starting a scenario run.

ScenarioRunSummary

Bases: BaseModel

Response for a scenario run (status + result details).