Part of the Extension API Guide. Covers ExtensionContext, RunEnvironment, session state, and custom tool registration.

ExtensionContext Reference

ExtensionContext is the second parameter of every handler lambda. It provides access to session state and TUI utilities.

interface ExtensionContext {
    /** Absolute path of the current working directory when Book was launched. */
    val cwd: String

    /** The runtime environment Book is running in.
     *  Use this to distinguish between TUI, headless (-p), and ACP server mode.
     *  See xref:api-context.adoc#_runenvironment_reference[Β§2a] below for the full `RunEnvironment` reference. */
    val environment: RunEnvironment

    /** True when Book is NOT running in interactive TUI mode.
     *  This is `true` for both `RunEnvironment.Headless` (-p / --prompt flag)
     *  and `RunEnvironment.Server` (ACP server mode).
     *  Equivalent to: `environment != RunEnvironment.Tui`.
     *  Scripts can inspect this to bypass interactive prompts in any non-TUI context. */
    val isHeadless: Boolean

    /** Read/write access to the current session's persistent storage. */
    val sessionManager: SessionManagerInterface

    /** Interactive UI methods (notify, confirm, select, input). */
    val ui: ExtensionUI

    /** Coroutine Job representing the current agent turn, or null outside a turn.
     *  Can be used to check for cancellation. */
    val signal: Job?

    /** Print a line of text to the TUI output panel. */
    fun displayMessage(message: String)

    /** Return the current system prompt string (read-only). */
    fun getSystemPrompt(): String
}

ExtensionCommandContext extends ExtensionContext and is passed to slash-command handlers:

interface ExtensionCommandContext : ExtensionContext {
    /** Suspend until any currently-running agent turn completes before acting. */
    suspend fun waitForIdle()
}

RunEnvironment Reference

ctx.environment exposes the sealed type RunEnvironment, which describes the runtime context Book is operating in. Scripts should prefer inspecting ctx.environment when they need to distinguish all three modes, and ctx.isHeadless when any non-TUI mode should be treated identically.

sealed interface RunEnvironment {
    /** Full Mordant TUI β€” the default interactive mode. */
    data object Tui : RunEnvironment

    /** Headless / piped-input mode β€” launched with `-p` / `--prompt`. */
    data object Headless : RunEnvironment

    /** ACP server mode β€” Book is acting as a protocol server (e.g. for Xcode).
     *  There is no interactive terminal in this environment. */
    data object Server : RunEnvironment
}

isHeadless derivation:

// isHeadless is a computed default on ExtensionContext:
val isHeadless: Boolean get() = environment != RunEnvironment.Tui

This means isHeadless is true for both Headless and Server β€” any script that guards interactive prompts with if (ctx.isHeadless) will correctly skip them in all non-TUI contexts.

Environment value summary:

ctx.environment ctx.isHeadless How Book was launched

RunEnvironment.Tui

false

Interactive TUI (default, no -p flag)

RunEnvironment.Headless

true

-p / --prompt flag (piped / CI mode)

RunEnvironment.Server

true

ACP server mode (bk serve / --mode acp)

MCP note: MCP (--mode mcp) is orthogonal to the output environment. It controls whether MCP-backed tools are loaded at startup, not which RunEnvironment is active. You can run with MCP tools in TUI, Headless, or Server mode simultaneously β€” ctx.environment reflects the output context only.

Example β€” environment-aware behaviour:

registerEventHandler(BookEvent.SessionStart::class) { _, ctx ->
    when (ctx.environment) {
        RunEnvironment.Tui     -> ctx.displayMessage("[MyExt] Running in interactive TUI")
        RunEnvironment.Headless -> ctx.displayMessage("[MyExt] Running headless (-p mode)")
        RunEnvironment.Server  -> ctx.displayMessage("[MyExt] Running as ACP server")
    }
}

Example β€” guard interactive prompts in all non-TUI contexts:

registerInterceptor(ToolCall::class) { event, ctx ->
    // isHeadless covers both Headless and Server β€” no prompts in either
    if (ctx.isHeadless) return@registerInterceptor ToolCallResult(block = false)

    val decision = ctx.ui.approveToolCall(event.toolName, event.input.toString().take(60))
    when (decision) {
        ApprovalDecision.APPROVE        -> ToolCallResult(block = false)
        ApprovalDecision.ALWAYS_APPROVE -> ToolCallResult(block = false)
        ApprovalDecision.DENY, null     -> ToolCallResult(block = true, reason = "User denied")
    }
}

State Management with SessionManager

Use ctx.sessionManager to persist custom data across turns and sessions.

interface SessionManagerInterface {
    fun getSessionId(): String
    fun getSessionFile(): String?
    fun getSessionName(): String?
    fun getSessionLogger(): SessionLogger
    fun close()

    /** Write a custom entry to the session file.
     *  @param customType Namespaced type string, e.g. "myext.counter".
     *  @param data Optional JSON payload.
     *  @return The ID of the written entry. */
    fun appendEntry(customType: String, data: JsonObject? = null): String
}

Persist custom state markers

var myState = 0

registerEventHandler(BookEvent.SessionStart::class) { _, ctx ->
    // Extension API exposes metadata + append hooks.
    // Restore from your own storage if you need readback.
    ctx.displayMessage("session: ${ctx.sessionManager.getSessionId()}")
}

registerEventHandler(BookEvent.ToolExecutionEnd::class) { event, ctx ->
    // Persist on every change
    myState++
    ctx.sessionManager.appendEntry("myext.mystate", buildJsonObject { put("tool", event.name) })
}

Best practice: Namespace your entry types (e.g., "myext.counter" not just "counter") to avoid collisions with built-in types.


Custom Tool Registration (tool { })

Use the tool { } DSL to add a new tool that the agent can call, just like the built-in bash, read_file, and write_file tools. The tool becomes available to the LLM immediately after the script loads β€” no restart required.

Tool sources and coexistence

Every tool in the registry carries a ToolSource tag that records where it was registered:

enum class ToolSource {
    BUILTIN,    // Compiled-in tools: bash, read_file, write_file, grep, find, etc.
    EXTENSION,  // Registered via `tool { }` in a .bk.kts script
    MCP,        // Provided by an MCP server connected via mcp.json (optional feature)
}

All three sources share the same ToolRegistry and are presented to the LLM identically β€” there is no visible difference from the agent’s perspective. Practically, this means:

  • A ToolCall interceptor registered in your script fires for all tool calls regardless of source β€” including calls to MCP-backed tools. Guard by event.toolName if you only want to intercept specific tools.

  • An extension tool with the same name as a built-in or MCP tool replaces it in the registry. Use this intentionally (to override behaviour) or avoid duplicate names to prevent surprises.

  • BookEvent.ToolExecutionStart / BookEvent.ToolExecutionEnd fire for all three sources β€” your observability scripts work transparently across built-in, extension, and MCP tools.

ToolBuilder DSL reference

tool {
    // Required: unique snake_case name the LLM uses to call the tool
    name = "my_tool"

    // Required: clear description telling the LLM what the tool does and when to use it
    description = "Fetches the current UTC time as an ISO-8601 string"

    // Parameter declarations β€” each returns a ParameterKey<T> for type-safe arg extraction
    val city   = string("city",    "City name to look up",   required = true)
    val metric = boolean("metric", "Use metric units",        required = false)
    val limit  = integer("limit",  "Maximum results to show", required = false)

    // execute { args -> ... } β€” called when the LLM invokes the tool
    // Return any value; non-ToolResult values are wrapped in Content.Text automatically
    execute { args ->
        val cityName = args[city]     // typed String
        val useMetric = args[metric]  // typed Boolean
        val maxItems = args[limit]    // typed Int
        "Result for $cityName (metric=$useMetric, limit=$maxItems)"
    }
}

Parameter types

Function Kotlin type JSON Schema type

string(name, description, required)

String

"string"

integer(name, description, required)

Int

"integer"

boolean(name, description, required)

Boolean

"boolean"

All parameters default to required = true. Pass required = false for optional parameters (the value will be "", 0, or false when absent).

Return values

What you return What the agent sees

A plain String

Text content

Any other value

toString() wrapped as text content

ToolResult(listOf(Content.Text("…")), isError = false)

Normal result

ToolResult(listOf(Content.Text("…")), isError = true)

Error result (agent told the tool failed)

ToolResult(listOf(Content.Image(data, mimeType)), isError = false)

Multi-modal image result β€” the LLM receives the image as a native vision attachment, not as text

ToolResult(listOf(Content.Text("…"), Content.Image(data, mimeType)), isError = false)

Mixed text + image β€” both parts are forwarded; text appears in the tool { result(…​) } block, the image in a follow-up user {} block

Content.Image field reference:

Field Type Description

data

String

Base64-encoded image bytes (no data: URI prefix β€” raw base64 only)

mimeType

String

MIME type string, e.g. "image/png", "image/jpeg", "image/gif", "image/webp"

How image forwarding works: KoogAgent.buildKoogPrompt() detects Content.Image parts in ToolResultMessage and emits a synthetic user {} block immediately after the tool { result(…​) } block, carrying the image as a ContentPart.Image. This is necessary because Koog 0.8.0’s Message.Tool.Result is text-only. The domain model is unchanged β€” the promotion to a follow-up user message is a provider concern confined to buildKoogPrompt() in :core:providers:koog.

Example β€” screenshot tool:

tool {
    name = "take_screenshot"
    description = "Takes a screenshot of the current screen and returns it as an image"
    execute { _ ->
        val bytes = captureScreenshot()          // returns ByteArray
        val b64 = java.util.Base64.getEncoder().encodeToString(bytes)
        ToolResult(
            content = listOf(
                Content.Text("Screenshot captured"),
                Content.Image(data = b64, mimeType = "image/png")
            ),
            isError = false
        )
    }
}

Streaming updates (long-running tools)

Use the two-argument execute overload to push intermediate output while the tool runs:

tool {
    name = "long_runner"
    description = "Runs a slow operation with progress updates"
    execute { args, onUpdate ->
        onUpdate(ToolResult(listOf(Content.Text("Starting…"))))
        // ... do work ...
        onUpdate(ToolResult(listOf(Content.Text("50% done…"))))
        // ... finish ...
        ToolResult(listOf(Content.Text("Complete")))
    }
}