# Handler contracts

A handler is a plain function in the entry file. It receives one
dictionary and returns one dictionary. Everything is JSON: text stays
text, bytes travel as base64. Phantom checks every reply before using it;
a reply of the wrong shape counts as a failure.

Inside the plugin's process, `import phantom_plugin` gives typed
descriptions of these dictionaries and a few helpers. The module has no
dependencies; it is in `backend/app/core/plugins/sdk/phantom_plugin.py`
if you want it in your editor.

## Report format

```python
import phantom_plugin as sdk

def export_csv(request: sdk.ReportRequest) -> sdk.ReportResult:
    title = request['report']['title']
    return {'content': f'title\n{title}\n'}
```

| Gets | |
|---|---|
| `report` | the report: `title`, `template`, `status`, `branding`, `meta`, `sections` (each with `finding`, `evidence`, `files`), `labels`, `scope`, `generated_at` |
| `view` | `full` or `executive` |
| `redacted` | whether credentials were masked |

Return `{"content": text}` (saved as UTF-8) or
`{"content_base64": base64}` for binary files; at most 32 MiB. The file
name is the report's title with the format's extension.

## Importer

```python
def import_items(request: sdk.ImportRequest) -> sdk.ImportResult:
    data = sdk.file_bytes(request)
    return {'entries': [
        sdk.har_entry('GET', 'https://shop.test/', 200, '2026-01-31T10:00:00.000Z'),
    ]}
```

| Gets | |
|---|---|
| `filename` | the file's name |
| `content_base64` | its bytes |

Return `{"entries": [...]}` with HAR 1.2 entries. Phantom imports them
exactly like a HAR file: every entry is checked, invalid ones are skipped
with a reason, the user sees a preview first, and scope decides
`in_scope`. `sdk.har_entry(...)` builds an entry from method, URL,
status, time, headers and bodies.

## Body view

```python
def show_tokens(request: sdk.RenderRequest) -> sdk.RenderResult:
    return {'text': request['body'].upper()}
```

| Gets | |
|---|---|
| `media_type` | the body's type, without parameters |
| `body` | the body as text |
| `body_base64` | its bytes |
| `headers` | the message's headers as `[name, value]` pairs |
| `masked` | whether credentials were masked |

Return `{"text": text}`. It is shown as plain text, never as HTML, and
cut at two million characters.

## Service adapter

A service adapter sends reviewed tickets to a service Phantom has no
built-in tracker for. The plugin never sees the credential and never
opens a connection: it describes the request, Phantom sends it.

```python
def build(request: sdk.AdapterRequest) -> sdk.AdapterCall:
    ticket = request['ticket']

    return {'method': 'POST', 'path': '/issues.json', 'json': {'issue': {'subject': ticket['title']}}}


def parse(answer: sdk.AdapterAnswer) -> sdk.AdapterIssue:
    number = answer['json']['issue']['id']

    return {'key': f'#{number}', 'url': f"{answer['config']['base_url']}/issues/{number}"}
```

`build` gets `ticket` (the reviewed `title`, `body`, `labels`,
`severity` and `cwe`, credentials masked) and `config` (the tracker's
`base_url`, `project` and `account`, never its token). It returns:

| Field | |
|---|---|
| `method` | `POST`, `PUT` or `PATCH` |
| `path` | a path below the tracker's address, starting with `/` |
| `headers` | up to 16 extra headers; never `Authorization`, `Cookie`, `Host` or the credential header |
| `json` | the body, at most 1 MiB |

Phantom adds the credential as the manifest's `auth` says and sends the
request to the tracker's address through the same checks as every other
outgoing request. A request outside these limits is refused before
anything is sent. A successful answer goes to `parse` as `status`, `json`
and `config`; it returns the issue's `key` (up to 60 characters) and its
http(s) `url`. The tracker is added under **Settings › Integrations ›
Issue trackers** as **Plugin adapter**; `plugins/examples/redmine-issues`
is a complete example.

## Errors

Raise an exception to fail a call; the user sees its type, message and
the line in your file. Anything you `print` goes to the process's error
output, not the reply. A call has 20 seconds.

## Testing a handler

Handlers are plain functions, so test them directly:

```python
import plugin

def test_csv():
    result = plugin.export_csv({'report': {'title': 'T', 'sections': []}, 'view': 'full', 'redacted': True})
    assert result['content'].startswith('id,title')
```

Run with the SDK folder on the path so `import phantom_plugin` works.
Phantom's own compatibility tests run each example plugin end to end
through the real host (`backend/tests/test_plugin_examples.py`).
