DeepSeek Harness Tool Execution Pipeline and Permission Gating
In previous chapters we learned to register tools with defineTool and to listen to various extension points with the event system.
But a question remains: after the model issues a tool call, until the tool actually executes and the result returns to the model, what stages does it go through?
This chapter explains dsh's 'tool execution pipeline' and how to implement permission gating with hook plugins.
In short: a tool call passes through multiple stages in a fixed order, each handling a class of policy, and hook plugins can allow, deny or ask within them.
Overall Order of the Pipeline
Tool execution is not as simple as 'calling a function'; it is a pipeline with a fixed order.
The official docs summarize the order as: tools/pre-execute → monotonic guard → tools/execute → tools/post-execute → finalizeContent → tools/result.
The first three are waterfalls that can rewrite a call, while finalizeContent and tools/result, controlled by the definition itself, run afterwards.
First, two easily confused concepts:
A waterfall is an event dispatch pattern in which a listener can call next() to delegate the decision onward, or return a decision directly to short-circuit.
A monotonic guard is a final line of defense that only reduces and cannot be revoked.
Let's examine each stage in turn.
tools/pre-execute: the reorderable policy layer
tools/pre-execute It is the first waterfall in the pipeline, carrying reorderable policies such as 'hooks, permissions, sandbox'.
It is called 'reorderable' because a listener can next() pass the decision to the next listener, and the order of multiple policy plugins can be adjusted in configuration.
This waterfall returns a typed decision, PreToolDecision, with three values:
| Decision | Meaning | Subsequent Behavior |
|---|---|---|
{ kind: 'allow' } |
Allow this call | Continue through the monotonic guard and later stages |
{ kind: 'deny'; reason: string } |
Deny this call | Materialize as an error result; the tool body is skipped |
{ kind: 'ask'; reason?: string } |
Ask the user | Continue only if the approval service returns allowed-once approval; otherwise deny |
Note ask Branch: it triggers ctx.approval one-time ask; this is left for the next article.
Arguments cannot be rewritten because history, audit, UI and execution must stay consistent.
When to use pre-execute?
Use it when a policy needs one of the three actions 'allow, deny or ask' and you want policies freely orderable.
Sandbox, permission, plan-mode and similar plugins all use this extension point.
Monotonic guard: the irrevocable final denial
The drawback of a waterfall is that a later-registered listener can overturn an earlier listener's decision.
When an invariant needs 'final denial that no one can revoke', use ctx.tools.guard()。
The guard type is ToolGuard, which deliberately has no allow result: returning a string means deny, returning undefined means maintain the status quo.
// ToolGuard: The ultimate pre-dispatch strategy with scope awareness
type ToolGuard = (execution: Readonly) => string | undefined
Because guards have no allow result, listener order can never turn a denial back into an allowance.
This is the meaning of 'monotonic': only decrease, never increase; only take permissions away, never grant them.
Practical principle: put reorderable policies in tools/pre-execute; put invariants that must be 'final and irrevocable' in ctx.tools.guard()。
tools/execute and tools/post-execute
tools/execute They handle 'around dispatch', wrapping the actual invocation of the tool body.
Timeouts, retries and metrics are handled at this layer, which wraps the actual dispatch lifecycle.
The view it receives is ToolDispatchExecution: this is the only view that can replace the required exec.signalto impose a deadline.
The replacement rule: it can be replaced but not removed; the registry re-merges the caller's signal before invoking the tool body.
tools/post-execute It performs checks or rewrites after the tool executes and before the result is normalized; it returns PostToolDecision:
| Decision | Meaning |
|---|---|
{ kind: 'accept'; content? } |
Accept the result; display content may be replaced (canonical value and metadata preserved) |
{ kind: 'accept'; value } |
Accept the result; canonical value may be replaced (revalidated and content recomputed) |
{ kind: 'block'; feedback } |
Block the result, turning corrective feedback into an error result |
Content replacement is a presentation policy, not a confidentiality policy.
To hide a programmatic value you must replace that value or block the result.
finalizeContent and tools/result
finalizeContent is a callback owned by the tool definition (ToolDefinition) itself, called exactly once by the registry.
It is the 'last content-only invariant': executed synchronously, only final content-level fixes are allowed.
After this, the registry materializes and freezes the accepted result, then triggers tools/result。
tools/result which is a synchronous notification for observing the frozen, immutable authoritative result.
Observers cannot transform the result, and observer failures are isolated without affecting the main flow.
Use it for 'audit, metrics, capturing the final result'; only use [the other] when you need to 'transform the result or attach context' tools/post-execute。
Memory aid for selection: pre-execute decides 'whether it can be done', execute decides 'how it is done', post-execute decides 'how the result is presented', and result only 'takes a look at the final result'.
Hands-on example: writing a permission gate plugin
The official docs use 'permission gating' as an example to show how hook plugins use tools/pre-execute。
A hook plugin is just an ordinary Cordis plugin; no external protocol is needed.
Example
// File path: my-plugins/permission-gate/src/index.ts
// A permission gate plugin based on tools/pre-execute.
// It returns a typed decision: deny on a blacklist hit, otherwise call next() to delegate.
import
type
{
Context
}
from
'@deepseek-ai/cordis'
import
type
{
PreToolDecision
,
ToolExecution
}
from
'@deepseek-ai/dsh-tools'
// Blacklist: tools forbidden from writing directly to the filesystem in the runoob project.
// A simple set is used here for demonstration; a real project can query a database or ask an approval service.
const
DENY_TOOLS
=
new
Set
(
[
'fs_write'
,
'fs_edit'
]
)
// Policy decision function: returns whether this call is allowed.
// exec carries the immutable call identity (callId, name, arguments, agent, token, signal).
async
function
isAllowed
(
exec
:
ToolExecution
)
:
Promise
<
boolean
{
if
(DENY_TOOLS.
has
(
exec.
name
)
)
return
false
// Extra example: the runoob demo forbids modifying .env files (arguments are frozen before entering policy).
const
raw
=
exec.
arguments
as
{
path
?:
string
}
if
(
typeof
raw.
path
===
'string'
&&
raw.
path
.
includes
(
'.env'
)
)
return
false
return
true
}
export
const
name
=
'permission-gate'
export
function
apply
(
ctx
:
Context
)
{
// tools/pre-execute is a waterfall: a listener can return a decision or call next() to delegate.
ctx.
on
(
'tools/pre-execute'
,
async
(
exec
,
next
)
:
Promise
<
PreToolDecision
=>
{
if
(!
(
await isAllowed
(
exec
)
)
)
{
// Returning deny terminates the call immediately; later listeners do not run.
return
{
kind
:
'deny'
,
reason
:
'Denied by policy: this tool is not allowed in the runoob workspace.'
}
}
// Allow: pass the decision to later listeners in the pipeline.
return
next
(
)
}
)
}
Once this plugin is loaded, every model tool call goes through it first.
A blacklisted tool gets an error result with a reason, and the tool body is skipped.
Because it returns a typed decision, other policy plugins can still participate after it.
Hands-on example: adding a timeout with tools/execute
Timeouts are an 'around dispatch' concern and should be handled with tools/execute rather than written into the tool body.
Example
// File path: my-plugins/tool-guard/src/index.ts
// Use tools/execute to wrap the actual dispatch lifecycle: add a 30-second timeout to each tool call.
import
type
{
Context
}
from
'@deepseek-ai/cordis'
export
const
name
=
'tool-guard'
export
function
apply
(
ctx
:
Context
)
{
// tools/execute is a waterfall: next() must be called for the real tool body to execute.
ctx.
on
(
'tools/execute'
,
async
(
exec
,
next
)
=>
{
// Note: only the tools/execute view can replace exec.signal.
// Here the caller's signal is merged with a 30-second deadline, overriding the original signal.
const
originalSignal
=
exec.
signal
const
deadline
=
AbortSignal.
timeout
(
30
_000
)
exec.
signal
=
AbortSignal.
any
(
[
originalSignal
,
deadline
]
)
try
{
// Delegate to the real tool execute(); timeout or caller cancellation triggers abort.
return
await next
(
)
}
finally
{
// Restore the original signal afterwards to avoid polluting later calls.
exec.
signal
=
originalSignal
}
}
)
}
Rule: exec.signal can be replaced but not removed.
The registry re-merges the caller's signal before invoking the tool body, so replacing the signal in the wrapper is safe.
Hands-on example: monotonic denial with ctx.tools.guard()
When an invariant needs 'final, irrevocable denial', use ctx.tools.guard()。
Note the guard's return type is string | undefined, with no allow branch.
Example
// File path: my-plugins/invariant-guard/src/index.ts
// An irrevocable final denial: forbid run_code in the runoob demo environment.
import
type
{
Context
}
from
'@deepseek-ai/cordis'
export
const
name
=
'invariant-guard'
export
function
apply
(
ctx
:
Context
)
{
// Register a monotonic guard. Returning a string denies; returning undefined maintains the status quo.
const
disposer
=
ctx.
tools
.
guard
(
(
execution
)
=>
{
if
(
execution.
name
===
'run_code'
)
{
return
'run_code is disabled in the runoob demo profile.'
}
return
undefined
// Allow: leave the pre-execute decision unchanged
}
)
// guard() returns an exact unload function; the framework calls it automatically when the plugin unloads.
ctx.
effect
(
(
)
=>
disposer
)
}
Because guards have no allow result, even if a later listener wants to allow run_code, it cannot turn this denial back into an allowance.
Summary and self-test
The tool execution pipeline decouples 'policy' from 'tool body', letting hooks span different tool families without coupling tools to a particular policy service.
Self-test questions:
| Problem | Reference |
|---|---|
| To make a tool 'impossible for anyone to allow', should you use pre-execute or guard? | guard, because guards have no allow result and are irrevocable |
| To add a uniform timeout to all tools, which event should you listen to? | tools/execute, it wraps dispatch and can replace signal |
| To only record the final result for audit without changing anything, which stage should you use? | tools/result, it observes the frozen authoritative result |