Skip to content

Plugin SDK 1.7 ​

lanius_sdk is the stable boundary between a plugin and the engine. Engine modules under app are internal and can change without an SDK compatibility promise.

An SDK plugin exports a synchronous activate(context) function. Activation may register capabilities, return one mitmproxy addon, return a list of addons, or return a Disposable. A plugin can also keep using the legacy Plugin or addons entry point while it migrates.

python
from lanius_sdk import PluginContext, SettingDefinition

def activate(context: PluginContext) -> None:
    context.settings.define(
        SettingDefinition("prefix", "Prefix", default="test-")
    )
    context.actions.register(
        "tag",
        "Tag selected flow",
        lambda event: {"flow_id": event.get("flow_id")},
        locations=("flow", "history"),
    )

Activation itself is synchronous so loading remains transactional. Long lived asynchronous work starts through context.tasks.create(...). The host cancels and awaits those tasks when the plugin is disabled or reloaded.

Owned registrations ​

Every registration belongs to the plugin that created it. Disabling, reloading, deleting, or failing to activate a plugin removes all of its registrations. Calling the returned Disposable.dispose() removes an individual registration earlier.

Contribution IDs use lowercase letters, digits, dashes, and underscores. The host qualifies them with the plugin ID. A local action ID inspect from a plugin named headers becomes headers.inspect. Plugin IDs may contain dots but contribution IDs may not, so the owner is always everything before the last dot and two plugins such as acme and acme.demo cannot claim each other's IDs.

Actions ​

context.actions.register adds a command with one or more UI locations: global, history, flow, request, response, replay, fuzzer, target, or plugin. The plugin location is for a sandboxed plugin view's own actions. Handlers receive a JSON compatible context mapping and may return a value or an awaitable. The contribution catalogue is available at GET /api/plugin-contributions; actions run through POST /api/plugin-actions/{id}/invoke.

The declared locations are rendered in HTTP history, Target, request and response details, Replay, Fuzzer, or the global Plugins toolbar. Synchronous handlers run outside the engine event loop. Actions and payload handlers have a 30 second host timeout, and action results must be JSON compatible and no more than 1 MiB.

Flow locations include flow_id and a serializable flow summary. Request and response detail menus also include the loaded detail and a message field. Replay and Fuzzer include their current raw request and parsed request when valid. A target action is shown on a Target site row and receives a target mapping containing scheme, host, and port. The host adds the exact location chosen by the UI before invocation.

MCP tools ​

context.mcp.register_tool(tool_id, handler, description=None, read_only=False) exposes a typed synchronous or asynchronous handler on the running engine's HTTP MCP endpoint. description and read_only are keyword-only. Tools use plugin-qualified names and the same owned Disposable lifecycle as actions. Inputs are checked against the inferred schema; calls have a 30-second timeout and a 1 MiB JSON result limit. Settings lists the owner and declared read/write behavior, and Plugins includes MCP tool counts and diagnostics.

Safe mode and Lockdown Mode block execution. Arbitrary plugin JSON output does not inherit the built-in flow tools' secret masking. The standalone stdio MCP process does not load plugins. See Plugin MCP Tools for a complete example, client refresh behavior, and cancellation limitations.

Codecs ​

context.codecs.register adds an encoder, a decoder, or both to Decoder. A codec is exposed under its qualified ID and participates in the same decoder chain as built in codecs. An ID collision rejects activation instead of overwriting an existing transform.

Message views (SDK 1.7) ​

context.message_views.register adds a tab beside Pretty, Raw and Hex in HTTP history, the Replay and Fuzzer editors and responses, and Intercept. render(message) returns the tab's text, or None when the view does not apply to that message. The tab then says so instead of showing an error.

With an apply(text, message) function the tab is editable wherever Raw is editable: the Replay and Fuzzer request editors and the Modified version in Intercept. Edited text is passed to apply, and the complete raw message it returns replaces Raw. What is sent is still exactly the Raw text, so a failed apply leaves Raw unchanged and shows the error in the tab.

python
import base64

from lanius_sdk import PluginContext

def activate(context: PluginContext) -> None:
    def decrypt(message):
        if not message["body"]:
            return None
        return my_decrypt(base64.b64decode(message["body"])).decode()

    def encrypt(text, message):
        head = message["raw"][: len(message["raw"]) - len(message["body"])]
        return head + base64.b64encode(my_encrypt(text.encode())).decode()

    context.message_views.register(
        "e2e", "E2E", decrypt, apply=encrypt, sides=("request", "response"),
    )

message contains:

KeyMeaning
side"request" or "response"
location"history", "replay", "fuzzer" or "intercept"
flow_idThe captured or result flow, when there is one
rawThe whole message as text: start line, headers, blank line, body
start_line, headers, bodyraw split up; headers is a list of [name, value]
body_truncatedThe body is a display preview. Use context.flows.get(flow_id) for exact bytes
editableWhether the tab is being shown with apply enabled

Both callbacks may be sync or async and share the 30 second contribution timeout and plugin diagnostics. sides limits which half of an exchange offers the tab. While plugins are suspended, for example in Lockdown Mode, the tabs disappear and the endpoints refuse with LOCKDOWN_MODE_BLOCKED.

Fuzzer payload extensions ​

context.payloads.register_generator produces payload strings from a JSON options mapping. register_processor transforms a payload before use. Both forms may be synchronous or asynchronous. The host limits a single generator call to 100,000 values.

The HTTP bridge exposes generators and processors at:

  • POST /api/plugin-payload-generators/{id}/generate
  • POST /api/plugin-payload-processors/{id}/process

Settings and storage ​

context.settings.define declares typed fields. Supported kinds are string, boolean, integer, number, and enum. Project settings live in the project database and are included in project export. User settings live in plugin-values.json under the Lanius data directory. The Plugins tab renders the schema and edits values through /api/plugins/{plugin}/settings.

context.storage stores arbitrary JSON compatible values without exposing the database. Keys are automatically namespaced by plugin. Project and user scopes are supported, and a value is limited to 1 MiB. Stored values survive plugin disable and reload; uninstall can explicitly remove them later.

Logging and tasks ​

context.log is a logger named lanius.plugin.{plugin_id}. Use context.tasks.create(awaitable) for background work so shutdown, reload, and failure cleanup can cancel it deterministically.

The host combines five sources in a plugin-owned, in-memory log stream:

  • sdk: context.log
  • logging: the plugin module's standard Python logger and descendants
  • stdout: print() and direct stdout writes, recorded at info
  • stderr: direct stderr writes, recorded at error
  • host: load, activation, managed task, action, scanner, and traffic-hook failures observed by Lanius

Each entry contains sequence, timestamp, plugin, source, level, and message. The host retains the latest 500 entries per plugin and limits each message to 16 KiB. Buffers exist only for the current engine session: they are not persisted in the project, exported, or copied to the Logger tab. Incremental clients use GET /api/plugins/{id}/logs?after={sequence}&limit=500, and DELETE /api/plugins/{id}/logs clears only that plugin's log buffer.

Output attribution covers host-managed import, activation, mitmproxy hooks, SDK actions, MCP tools, payload handlers, scanner handlers, and managed tasks. File descriptor output from a subprocess and output from unmanaged native threads are outside this contract. Writes made outside a plugin execution context pass through to the engine's original stdout or stderr.

The performance panel measures SDK action, MCP tool, payload, and scanner contribution calls. It shows call and error counts, average and maximum duration, and the last error. Resetting diagnostics resets those counters and resumes a suspended scanner check without deleting logs. A passive or active scanner check is suspended after five consecutive errors so one broken check cannot fail for every captured request indefinitely.

Package resources ​

Files stored under a package's resources/ directory are available through context.resources.list(), read_bytes(path), and read_text(path). Paths are relative to resources/, cannot escape that directory, and a single read is capped at 10 MiB. Resource files remain covered by the package manifest's integrity map. Legacy loose-file plugins do not receive a resource directory.

Captured flows ​

SDK 1.4 adds context.flows.get(flow_id, in_scope_only=True). It returns a copy of one captured HTTP exchange, with exact request_body_base64 and response_body_base64, captured byte counts, omission flags, and response_present. Text previews decode at most the first 16 KiB of each body without decompression, with explicit *_preview_truncated flags. The combined captured bodies must fit within 16 MiB; larger exchanges fail without silently truncating the raw data. None and empty response bodies stay distinct. Unknown IDs, non-HTTP records, and out-of-scope selections are refused. An explicit UI or agent selection may opt out of scope filtering, as with pages.

SDK 1.4 also adds context.storage.batch(values, delete=()), an atomic project storage operation. Every key is namespaced to its owner and validated before writing. Values retain the 1 MiB per-value limit; a batch permits up to 4096 writes, 100000 deletions, and 48 MiB of encoded values. Related metadata and snapshot chunks commit together, and a failed write rolls back all changes. This API does not support user-scoped values.

context.flows.page(limit=50, cursor=None, anchor=None, in_scope_only=True, body_limit=32768) reads a bounded page of captured HTTP snapshots. The host limits pages to 100 flows and each rendered request/response body to 65,536 characters. Pages include items, has_more, anchor, and next_cursor; pass the first page's anchor and each next cursor to traverse a stable History snapshot. Scope rules are applied before items are returned by default. This is read-only and uses the project store without opening a network connection.

Scanner checks and issues ​

context.scanner.register_passive analyzes captured responses without sending traffic. register_active receives bounded insertion points and a rate-limited request sender. Checks return ScanIssue values, which the host validates, deduplicates, persists, and displays. The full scheduler contract is in plugin-scanner.md.

An active check registered with request_level=True runs once for a selected flow and can call scan.send_with(kind, name, value) to append a query, header, cookie, form, or top-level JSON input. Calling scan.send_with() sends the unchanged control request. All such requests share the active job's limits and Replay/scope egress path. await context.scanner.start(check_id, flow_id) starts the plugin's own check from an explicit UI action and returns job status.

Shared view styles ​

SDK 1.5 adds the theme.get UI bridge method and live lanius.theme.changed messages. Views receive the host's shared CSS and resolved palette/typography roles rather than copying application CSS or defining their own theme. See Shared appearance for the contract.

Compatibility ​

lanius_sdk.API_VERSION and context.api_version currently report 1.7. Minor additions remain backward compatible. A future breaking API uses a new major version and package manifests declare which major versions they accept.

Distribution, compatibility fields, integrity, signatures, sandboxed UI, and development linking are specified in plugin-packages.md.