Extension API: Context, State & Tools
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 |
|---|---|---|
|
|
Interactive TUI (default, no |
|
|
|
|
|
ACP server mode ( |
MCP note: MCP (
--mode mcp) is orthogonal to the output environment. It controls whether MCP-backed tools are loaded at startup, not whichRunEnvironmentis active. You can run with MCP tools in TUI, Headless, or Server mode simultaneously βctx.environmentreflects 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
ToolCallinterceptor registered in your script fires for all tool calls regardless of source β including calls to MCP-backed tools. Guard byevent.toolNameif 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.ToolExecutionEndfire 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 |
|---|---|---|
|
|
|
|
|
|
|
|
|
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 |
Text content |
Any other value |
|
|
Normal result |
|
Error result (agent told the tool failed) |
|
Multi-modal image result β the LLM receives the image as a native vision attachment, not as text |
|
Mixed text + image β both parts are forwarded; text appears in the |
Content.Image field reference:
| Field | Type | Description |
|---|---|---|
|
|
Base64-encoded image bytes (no |
|
|
MIME type string, e.g. |
How image forwarding works:
KoogAgent.buildKoogPrompt()detectsContent.Imageparts inToolResultMessageand emits a syntheticuser {}block immediately after thetool { result(…) }block, carrying the image as aContentPart.Image. This is necessary because Koog 0.8.0’sMessage.Tool.Resultis text-only. The domain model is unchanged β the promotion to a follow-up user message is a provider concern confined tobuildKoogPrompt()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")))
}
}