Metadata-Version: 2.5
Name: pyfsr
Version: 0.35.0
Summary: Python implementation of the FortiSOAR REST API
Project-URL: Homepage, https://github.com/ftnt-dspille/pyfsr
Project-URL: Bug Tracker, https://github.com/ftnt-dspille/pyfsr/issues
Project-URL: Documentation, https://ftnt-dspille.github.io/pyfsr/
Author-email: Dylan Spille <dspille@fortinet.com>
License: MIT
License-File: LICENSE
Keywords: api,fortinet,fortisoar,rest
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: pydantic>=2.1
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: requests>=2.31.0
Provides-Extra: docs
Requires-Dist: furo>=2024.8.6; extra == 'docs'
Requires-Dist: myst-parser>=4.0.0; extra == 'docs'
Requires-Dist: sphinx-autoapi<4,>=3.8; extra == 'docs'
Requires-Dist: sphinx-autodoc-typehints>=3.0.0; extra == 'docs'
Requires-Dist: sphinx-copybutton>=0.5.2; extra == 'docs'
Requires-Dist: sphinx-design>=0.6.1; extra == 'docs'
Requires-Dist: sphinx<10,>=9.1; (python_version >= '3.12') and extra == 'docs'
Provides-Extra: icons
Requires-Dist: pillow>=10; extra == 'icons'
Provides-Extra: mcp
Requires-Dist: mcp<3,>=2; extra == 'mcp'
Provides-Extra: playbooks
Requires-Dist: fsr-playbooks<0.13,>=0.12.1; extra == 'playbooks'
Provides-Extra: test
Requires-Dist: coverage>=7.6.9; extra == 'test'
Requires-Dist: mcp<3,>=2; extra == 'test'
Requires-Dist: pillow>=10; extra == 'test'
Requires-Dist: pytest; extra == 'test'
Requires-Dist: pytest-cov; extra == 'test'
Requires-Dist: pytest-mock; extra == 'test'
Requires-Dist: tomli; (python_version < '3.11') and extra == 'test'
Provides-Extra: typecheck
Requires-Dist: mypy>=1.13; extra == 'typecheck'
Requires-Dist: types-pyyaml; extra == 'typecheck'
Description-Content-Type: text/markdown

# pyfsr

[![PyPI version](https://badge.fury.io/py/pyfsr.svg)](https://badge.fury.io/py/pyfsr)
[![Python versions](https://img.shields.io/pypi/pyversions/pyfsr)](https://pypi.org/project/pyfsr/)
[![License: MIT](https://img.shields.io/pypi/l/pyfsr)](https://github.com/ftnt-dspille/pyfsr/blob/main/LICENSE)
[![Tests](https://github.com/ftnt-dspille/pyfsr/actions/workflows/pr-tests.yml/badge.svg)](https://github.com/ftnt-dspille/pyfsr/actions/workflows/pr-tests.yml)
[![Documentation Status](https://github.com/ftnt-dspille/pyfsr/actions/workflows/docs.yml/badge.svg)](https://github.com/ftnt-dspille/pyfsr/actions/workflows/docs.yml)
[![codecov](https://codecov.io/gh/ftnt-dspille/pyfsr/branch/main/graph/badge.svg)](https://codecov.io/gh/ftnt-dspille/pyfsr)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)

[Documentation](https://ftnt-dspille.github.io/pyfsr/) · [Installation](#installation) · [Quick start](#quick-start) · [CLI](#command-line-tools) · [AI / agents](#ai--agent-friendly)

**pyfsr** is a batteries-included Python client for the FortiSOAR REST API. It
gives you a typed query/CRUD layer over any module, picklist resolution,
connector execution, playbook-run history, safe deletes -- and a ready-made
**AI/agent surface** (tool-schema registry + an optional MCP server) so an agent
can drive FortiSOAR with no glue code.

There's also a `pyfsr` CLI for the things you reach for outside a script:
poking at an appliance's health and services, and authoring playbooks in YAML
and pushing them to a live instance.

Python 3.10+ · Pydantic v2 · MIT.

## Installation

```bash
pip install pyfsr
# with the optional generic MCP server:
pip install 'pyfsr[mcp]'
```

## Quick start

```python
from pyfsr import FortiSOAR, Query

# API-key auth, or ("username", "password")
client = FortiSOAR("soar.example.com", "your-api-key")

# Generic, typed CRUD for ANY module via client.records(module)
incidents = client.records("incidents")

inc = incidents.get("0d2c...")          # by uuid, "module:uuid", or full IRI
inc["name"], inc.uuid                    # records are dict- AND attribute-accessible

# Structured queries with a fluent builder -> a HydraPage you can iterate
page = incidents.query(
    Query().eq("status.itemValue", "Open").like("name", "phish").limit(50)
)
for inc in incidents.iterate(Query().eq("status.itemValue", "Open")):
    ...                                  # lazily walks every page

# Create / update / delete (soft by default; hard= for permanent)
new = incidents.create({"name": "Suspicious login", "severity": "High"},
                       resolve_picklists=True)   # friendly values -> IRIs
incidents.update(new.uuid, {"status": "Closed"}, resolve_picklists=True)
incidents.delete(new.uuid)               # delete(..., hard=True) to purge
```

### Configure from the environment

```python
from pyfsr import EnvConfig

# reads FSR_BASE_URL (+ FSR_API_KEY or FSR_USERNAME/FSR_PASSWORD),
# FSR_PORT, FSR_VERIFY_SSL, FSR_TIMEOUT
client = EnvConfig.from_env().client()
```

## Features

- **Generic record access** -- `client.records(module)` for CRUD on any module;
  no hand-built `/api/3/...` URLs or Hydra unwrapping.
- **Query DSL** -- `Query().eq(...).in_(...).group(...).sort(...).limit(...)`,
  compiled to the FortiSOAR query-body shape (pagination handled for you).
- **Typed models** -- Alert/Incident/Task/Comment come back as Pydantic v2
  models that are also dict-compatible; unknown modules fall back to a lenient
  `BaseRecord`, so custom fields/modules never break.
- **Picklists** -- `client.picklists` resolves friendly values (`"High"`) to
  IRIs and discovers which picklist a `(module, field)` binds to.
- **Connectors** -- `client.connectors` lists configured connectors, runs
  healthchecks, and executes operations.
- **Playbooks** -- `client.playbooks` merges live + historical run history and
  resumes manual-input steps.
- **Safe deletes** -- soft-delete/restore + guarded single-row hard delete.
- **Schema discovery** -- `client.list_modules()` / `client.describe_module()`.
- **Resilient transport** -- configurable `timeout=`, automatic retry with
  backoff on idempotent requests (429/5xx), and secrets masked in verbose logs.
- **Bundled OpenAPI spec** -- `pyfsr.spec.load_spec()` for offline reference and
  `drift(client)` to compare the spec against a live appliance.

## AI / agent-friendly

The agent layer (tool registry, MCP server, workflows) lives in
[`fsr-agentic-toolkit`](https://pypi.org/project/fsr-agentic-toolkit/); the
`pyfsr-mcp` command hands off to it when it is installed.

Reads accept `summary=True` or `fields=[...]` to keep payloads small:

```python
client.records("alerts").query(Query().limit(20), summary=True)
```

### Generic MCP server

Point any MCP-capable agent at any FortiSOAR with one command:

```bash
pip install 'pyfsr[mcp]'
FSR_BASE_URL=soar.example.com FSR_API_KEY=... python -m pyfsr.agent.mcp
```

It exposes the same registry (record CRUD, schema discovery, picklists,
connectors, playbook runs) as MCP tools -- generic and dependency-light,
distinct from any domain-specific FortiSOAR MCP.

## Command-line tools

Installing pyfsr puts a `pyfsr` command on your path with seven groups.

**`pyfsr instances`** -- add boxes to the named-instance registry
(`~/.pyfsr/instances.toml`) and inspect it. Every `--instance` flag resolves
against it:

```bash
pyfsr instances add                  # guided: URL, API key or login, TLS; connects before saving
pyfsr instances list                 # every alias: base URL, auth kind, SSH profile
pyfsr instances show 206             # one instance's resolved settings (no secrets)
pyfsr instances check                # connect to each box; exit 1 if any fails
```

`check` probes the version endpoint and then an authenticated read, so a
registered-but-broken alias shows up as `unreachable` or `auth-failed` before a
script fails on it.

`add` keeps the secret in a 0600 `<alias>.env` beside the registry, never in the
TOML or on the command line, and saves nothing if the connection fails. The
first box added becomes the default. For FortiSOC, answer yes to the API-key
question. Without prompts: `FSR_API_KEY=... pyfsr instances add soc --url
soc.example.com --no-input`.

**`pyfsr appliance`** -- operational verbs against a FortiSOAR box (most run over
SSH/sudo and stay dependency-light on the far end):

```bash
pyfsr appliance info                 # host, version, content DB, device UUID
pyfsr appliance host                 # mem / swap / load / per-service RSS / disk
pyfsr appliance service restart cyops-postman --yes
pyfsr appliance db                   # Postgres verbs, multi-DB aware
pyfsr appliance es                   # Elasticsearch health + shard state
pyfsr appliance license              # licensing / identity, drift check
pyfsr appliance content-hub sync     # pull the Content Hub catalog + artifacts
```

Other appliance subgroups: `mq` (RabbitMQ), `ha`, `certs`, `logs`, and
`diagnose` (runs `fsr_diagnose.sh`). `--help` on any of them lists the verbs.

**`pyfsr playbook`** -- author playbooks as YAML and deploy them:

```bash
pyfsr playbook steps                 # list every step type you can write
pyfsr playbook step-help TYPE        # keys + a compiling example for one type
pyfsr playbook examples              # foundational playbook library (--intent/--stage/--manifest)
pyfsr playbook show SLUG             # print one library playbook's metadata + YAML
pyfsr playbook validate flow.yaml    # compile + report diagnostics (offline)
pyfsr playbook compile flow.yaml     # emit the FSR import envelope (offline)
pyfsr playbook lint flow.yaml        # live preflight: connector steps missing config
pyfsr playbook deploy flow.yaml      # compile and create it on the appliance
```

**`pyfsr records`** -- query and manage FortiSOAR records over the API:

```bash
pyfsr records alerts [--status Open] [--severity High]
pyfsr records incidents '<field=value or Query DSL JSON>'
pyfsr records delete <module> <uuid...> [--yes]
```

**`pyfsr repo`** -- discover and download from Fortinet's content repo (no
appliance needed).

**`pyfsr widget`** -- upload and publish widgets on a live appliance.

**`pyfsr mcp`** -- call FortiSOAR's own native MCP tool gateway
(`list-tools` / `call`), distinct from the generic `pyfsr.agent.mcp` server.

## Development

```bash
uv sync
uv run pytest -q                 # unit tests (live tests deselected by default)
uvx ruff check src tests
```

Live integration tests run with `pytest -m integration` against the instance
named by `FSR_INSTANCE` (an alias from `~/.pyfsr/instances.toml`), the `FSR_*`
environment variables, or `examples/config.toml`, in that order. The AI tests
(`test_ai_integration.py`) make no LLM calls, so they spend no AI tokens.

## License

MIT -- see [LICENSE](LICENSE).
