Pi Agent Custom Tool Development
Register custom tools through an Extension so the AI can call functions you write to accomplish specific tasks.
Tool registration basics
Use pi.registerTool() to register a tool the AI can call:
Example
// File path: ~/.pi/agent/extensions/todo-tool.ts
import
type
{
ExtensionAPI
}
from
"@earendil-works/pi-coding-agent"
;
import
{
Type
}
from
"typebox"
;
import
{
StringEnum
}
from
"@earendil-works/pi-ai"
;
// Define a to-do list (in-memory storage)
let todos
:
string
[
]
=
[
]
;
export
default
function
(
pi
:
ExtensionAPI
)
{
// Restore state from the session at startup
pi.
on
(
"session_start"
,
async
(
_event
,
ctx
)
=>
{
todos
=
[
]
;
for
(
const
entry of ctx.
sessionManager
.
getBranch
(
)
)
{
if
(
entry.
type
===
"message"
&&
entry.
message
.
role
===
"toolResult"
&&
entry.
message
.
toolName
===
"todo"
)
{
todos
=
entry.
message
.
details
?
.
todos
??
[
]
;
}
}
}
)
;
pi.
registerTool
(
{
name
:
"todo"
,
label
:
"To-do list"
,
description
:
"Manage the project's to-do list"
,
// Short description shown in the Available tools section of the system prompt
promptSnippet
:
"Manage project to-dos: list to list, add to add, done to complete"
,
// Usage guide appended to the Guidelines section of the system prompt
promptGuidelines
:
[
"Use the todo tool for task planning; do not edit to-do files directly"
,
]
,
parameters
:
Type.
Object
(
{
// StringEnum ensures compatibility with the Google API
action
:
StringEnum
(
[
"list"
,
"add"
,
"done"
]
as
const
)
,
text
:
Type.
Optional
(
Type.
String
(
{
description
:
"When adding: item description. When completing: item number or description"
}
)
)
,
}
)
,
// Compatible with old parameter format
prepareArguments
(
args
)
{
if
(
!
args
||
typeof
args
!==
"object"
)
return
args
;
const
input
=
args as
{
action
?:
string
;
oldAction
?:
string
}
;
// Map old fields to new fields
if
(
typeof
input.
oldAction
===
"string"
&&
input.
action
===
undefined
)
{
return
{
...
input
,
action
:
input.
oldAction
}
;
}
return
args
;
}
,
async execute
(
toolCallId
,
params
,
signal
,
onUpdate
,
ctx
)
{
if
(
signal
?
.
aborted
)
{
return
{
content
:
[
{
type
:
"text"
,
text
:
"Operation cancelled"
}
]
}
;
}
// Send a progress update
onUpdate
?
.
(
{
content
:
[
{
type
:
"text"
,
text
:
`Processing
:
$
{
params.
action
}
`
}
]
,
}
)
;
switch
(
params.
action
)
{
case
"list"
:
return
{
content
:
[
{
type
:
"text"
,
text
:
todos.
length
===
0
?
"To-do list is empty"
:
todos.
map
(
(
t
,
i
)
=>
`$
{
i
1
}
. $
{
t
}
`
)
.
join
(
"\n"
)
,
}
]
,
details
:
{
todos
:
[
...
todos
]
}
,
}
;
case
"add"
:
if
(
!
params.
text
)
{
throw
new
Error
(
"add operation requires the text parameter"
)
;
}
todos.
push
(
params.
text
)
;
// The 5th parameter ctx is the extension context; here it's used to pop a notification in the terminal
ctx.
ui
.
notify
(
`To-do added: $
{
params.
text
}
`
,
"info"
)
;
return
{
content
:
[
{
type
:
"text"
,
text
:
`Added
:
$
{
params.
text
}
(total $
{
todos.
length
}
items)`
,
}
]
,
details
:
{
todos
:
[
...
todos
]
}
,
}
;
case
"done"
:
if
(
!
params.
text
)
{
throw
new
Error
(
"done operation requires the text parameter"
)
;
}
const
idx
=
todos.
findIndex
(
t
=>
t.
includes
(
params.
text
!
)
)
;
if
(
idx
===
1
)
{
return
{
content
:
[
{
type
:
"text"
,
text
:
`No matching item found
:
$
{
params.
text
}
`
}
]
,
details
:
{
todos
:
[
...
todos
]
}
,
}
;
}
const
removed
=
todos.
splice
(
idx
,
1
)
[
0
]
;
return
{
content
:
[
{
type
:
"text"
,
text
:
`Completed
:
$
{
removed
}
(remaining $
{
todos.
length
}
items)`
,
}
]
,
details
:
{
todos
:
[
...
todos
]
}
,
}
;
default
:
throw
new
Error
(
"Unknown operation"
)
;
}
}
,
}
)
;
}
After registration, the AI decides on its own when to call the todo tool based on description and promptSnippet.
For example, if the user says 'help me add writing the weekly report to my to-dos', the AI makes the following call:
tool_call: todo
{
"action": "add",
"text": "写周报"
}
After execute runs, the text returned to the AI is as follows:
待办已新增:写周报(共 1 项)
After receiving this result, the AI confirms with the user in natural language, e.g. 'Added "write weekly report" to the to-do list, 1 item total now'.
Besides rebuilding state from toolResult's details, there's another path for cross-restart persistence: pi.appendEntry().
It writes custom entries directly into the session file, and with pi.registerEntryRenderer() they can be rendered in the conversation history.
Custom entries don't enter the LLM context, so they don't consume tokens.
But they're saved with the session and preserved in /tree branches.
Tool definition in detail
The registerTool configuration object contains the following fields, of which name, parameters, and execute are core.
| Field | Type | Required | Description |
|---|---|---|---|
| name | string | Is | The tool's unique identifier; the AI calls it by this name |
| label | string | Is | Tool display name |
| description | string | Is | Tool functionality description; the AI uses this to decide when to use it |
| parameters | TypeBox Schema | Is | Type definition of the tool's parameters |
| promptSnippet | string | No | Single-line summary in the Available tools section |
| promptGuidelines | string[] | No | Guidelines appended to the system prompt's Guidelines section |
| prepareArguments | function | No | Transform parameters before Schema validation, for compatibility with old formats |
| execute | async function | Is | The tool's actual execution logic |
Every guideline in promptGuidelines mustexplicitly state the tool name。
Don't write 'when using this tool…'; write 'when using my_tool…' instead, because the AI can't tell which tool 'this' refers to.
The execute function in detail
The execute function receives the following parameters:
| Parameters | Type | Description |
|---|---|---|
| toolCallId | string | Unique ID of the tool call |
| params | Generic type T | Schema-validated parameter object |
| signal | AbortSignal | undefined | Cancellation signal, triggered when the user presses Escape |
| onUpdate | function | Callback for sending progress updates |
| ctx | ExtensionContext | Extension context, providing UI, session, and other capabilities |
Return value format:
Example
// File path: ~/.pi/agent/extensions/todo-tool.ts (return value of the execute function)
return
{
// Content sent to the LLM (required)
content
:
[
{
type
:
"text"
,
text
:
"Operation complete"
}
]
,
// Custom detail data for state rebuilding and rendering (optional)
details
:
{
result
:
"..."
}
,
// Usage statistics for nested LLM calls (optional)
usage
:
nestedModelUsage
,
// Termination flag: when all tools in the same batch return terminate
// Skip subsequent LLM calls (optional)
terminate
:
true
,
}
;
To mark a tool execution as failed, use throw new Error(), do not try to set an error flag in the return value.
Only by throwing an exception can you set isError to true and notify the LLM that an error occurred.
StringEnum and type safety
Use StringEnum instead of Type.Union/Type.Literal to define enum parameters:
Example
// File path: ~/.pi/agent/extensions/todo-tool.ts (parameters field)
import
{
StringEnum
}
from
"@earendil-works/pi-ai"
;
// Correct: Google API compatible
parameters
:
Type.
Object
(
{
action
:
StringEnum
(
[
"list"
,
"add"
,
"done"
]
as
const
)
,
}
)
// Wrong: Google API incompatible
parameters
:
Type.
Object
(
{
action
:
Type.
Union
(
[
Type.
Literal
(
"list"
)
,
Type.
Literal
(
"add"
)
,
Type.
Literal
(
"done"
)
,
]
)
,
}
)
File modification safety queue
If your tool modifies files, use withFileMutationQueue() to participate in the file modification queue:
Example
// File path: ~/.pi/agent/extensions/note-edit.ts
import
{
withFileMutationQueue
}
from
"@earendil-works/pi-coding-agent"
;
import
{
mkdir
,
readFile
,
writeFile
}
from
"node:fs/promises"
;
import
{
dirname
,
resolve
}
from
"node:path"
;
// The following snippet is inside the execute function of registerTool
async execute
(
_toolCallId
,
params
,
_signal
,
_onUpdate
,
ctx
)
{
// Resolve the path to an absolute path
const
absolutePath
=
resolve
(
ctx.
cwd
,
params.
path
)
;
return
withFileMutationQueue
(
absolutePath
,
async
(
)
=>
{
// Ensure the directory exists
await mkdir
(
dirname
(
absolutePath
)
,
{
recursive
:
true
}
)
;
// Read the current content
const
current
=
await readFile
(
absolutePath
,
"utf8"
)
;
// Apply the modification
const
next
=
current.
replace
(
params.
oldText
,
params.
newText
)
;
// Write back to the file
await writeFile
(
absolutePath
,
next
,
"utf8"
)
;
return
{
content
:
[
{
type
:
"text"
,
text
:
`Updated $
{
params.
path
}
`
}
]
,
details
:
{
}
,
}
;
}
)
;
}
The file modification queue ensures concurrent modifications to the same file don't overwrite each other—when the built-in edit tool and your custom tool modify the same file at the same time, they're queued.
Output truncation
Tool output must be truncated to avoid filling the LLM context window. Built-in limits are 50KB (about 10,000 tokens) and 2000 lines:
Example
// File path: ~/.pi/agent/extensions/read-log.ts
import
{
truncateHead
,
formatSize
,
DEFAULT_MAX_BYTES
,
DEFAULT_MAX_LINES
,
}
from
"@earendil-works/pi-coding-agent"
;
import
{
readFile
}
from
"node:fs/promises"
;
import
{
resolve
}
from
"node:path"
;
// The following snippet is inside the execute function of registerTool
async execute
(
_toolCallId
,
params
,
_signal
,
_onUpdate
,
ctx
)
{
// Read a real file to get the text to be returned
const
output
=
await readFile
(
resolve
(
ctx.
cwd
,
params.
file
)
,
"utf8"
)
;
// Keep the beginning portion (suitable for file reads, search results)
const
truncation
=
truncateHead
(
output
,
{
maxLines
:
DEFAULT_MAX_LINES
,
maxBytes
:
DEFAULT_MAX_BYTES
,
}
)
;
let result
=
truncation.
content
;
// When truncated, append a line of explanation so the AI knows the content is incomplete
if
(
truncation.
truncated
)
{
result
+=
`\n\n
[
Output truncated: $
{
truncation.
outputLines
}
/
`
;
result
+=
`$
{
truncation.
totalLines
}
lines`
;
result
+=
`($
{
formatSize
(
truncation.
outputBytes
)
}
/
`
;
result
+=
`$
{
formatSize
(
truncation.
totalBytes
)
}
)
]
`
;
}
return
{
content
:
[
{
type
:
"text"
,
text
:
result
}
]
,
}
;
}
For a large log file exceeding the limit, the tool's returned text ends with a truncation note:
[2026-08-31 10:02:11] server started on port 3000
[2026-08-31 10:02:12] GET / 200 12ms
[2026-08-31 10:02:12] GET /static/app.js 200 4ms
...
[输出已截断:2000/8642 行(49.9KB/210.3KB)]
Truncation is not optional。
Oversized tool output causes context overflow, compaction failure, and degraded model performance; always truncate tool output.
override the built-in tool
You can override built-in tools (read, bash, powershell, edit, write, grep, find, ls) by registering a tool with the same name.
$ pi -e ./tool-override.ts
Below, registerTool is used to override the built-in read tool, adding a log line for each file read:
Example
// File path: ~/.pi/agent/extensions/read-logger.ts
import
type
{
ExtensionAPI
}
from
"@earendil-works/pi-coding-agent"
;
import
{
Type
}
from
"typebox"
;
import
{
readFile
}
from
"node:fs/promises"
;
import
{
resolve
}
from
"node:path"
;
export
default
function
(
pi
:
ExtensionAPI
)
{
// Same name as a built-in tool overrides it; here we only add logging to read
pi.
registerTool
(
{
name
:
"read"
,
label
:
"Read file"
,
description
:
"Read file content and log access in the terminal"
,
parameters
:
Type.
Object
(
{
path
:
Type.
String
(
{
description
:
"Path of the file to read"
}
)
,
}
)
,
async execute
(
_toolCallId
,
params
,
_signal
,
_onUpdate
,
ctx
)
{
const
absolutePath
=
resolve
(
ctx.
cwd
,
params.
path
)
;
const
text
=
await readFile
(
absolutePath
,
"utf8"
)
;
// Extra capability: record one access log
console.
log
(
`
[
read
]
$
{
params.
path
}
($
{
text.
length
}
characters)`
)
;
// Keep the return structure consistent with the built-in read
return
{
content
:
[
{
type
:
"text"
,
text
}
]
,
}
;
}
,
}
)
;
}
After loading this extension, the AI prints a [read] log line in the terminal every time it reads a file.
When overriding, renderers (renderCall/renderResult) are inherited by slot—if you omit renderCall, the built-in renderCall is still used.
This lets you add logging or access control to built-in tools without rewriting the UI.
But promptSnippet and promptGuidelines are not inherited from the built-in tool and must be defined explicitly.
There's an even more subtle constraint: your implementation must match the built-in tool's result shape exactly, including the details field.
Taking read as an example, the input must support the two optional parameters offset and limit so the AI gets the expected content when reading large files by pagination.
The details in the return value must also match the shape of the built-in read's ReadToolDetails, otherwise UI rendering lacks information and session state tracking is affected.
The logging extension example above is only for demonstration; when actually overriding the built-in read, complete the parameters and details according to the built-in implementation.