Skip to main content

Guardrails

Guardrails are checks around model and tool calls. Configure them to inspect requests, restrict which tools can access files or execute commands, protect secret values, and validate tool results before they return to the model.

from ish import Agent, BaseInterceptor, GuardrailInterceptor, LifecycleContext


class SecurityGuardrail(BaseInterceptor):
def __init__(self, forbidden_keywords: list[str]):
self.forbidden_keywords = forbidden_keywords

async def before_tool(self, ctx: LifecycleContext) -> None:
payload = ctx.input_payload
if isinstance(payload, dict):
for param, val in payload.items():
if isinstance(val, str):
for keyword in self.forbidden_keywords:
if keyword.lower() in val.lower():
raise ValueError(
f"Action blocked by SecurityGuardrail: '{keyword}' is forbidden in {param}."
)


agent = Agent(
name="secured_agent",
model="gpt-4o-mini",
tools=[execute_query],
interceptors=[
GuardrailInterceptor(denied_commands=["rm -rf"], blocked_keywords=["DROP TABLE", "SHUTDOWN"]),
SecurityGuardrail(forbidden_keywords=["--"]),
],
)

The guides below separate four kinds of controls: content checks, tool permissions, data access policy, and secret handling. They run in the shared Rust runtime; the language SDKs provide configuration and callbacks.

How a tool call is checked​

When secret references are allowed​

Secret references are resolved only when the current run is authorized to use them. The runtime checks that a reference was issued for the active session, belongs to the same tenant, is allowed for the calling tool and argument path, and has not expired or been revoked. Secret masking and data-access rules are applied before the value reaches a tool.

The checks fail closed: an invalid reference is rejected instead of being passed through as ordinary text.

Validation order​

CheckWhat it protects
Reference and ownershipPrevents reuse across sessions or tenants
Caller and destinationRestricts which tools can receive a secret
Argument pathLimits which tool fields accept secret values
Expiration and revocationBlocks stale or withdrawn references
Masking policyPrevents secrets from leaking in tool output

Where guardrails run​

The runtime can inspect the user's request, tool arguments, tool results, and final response. Configure only the stages you need; checks run before content is exposed to the next step. A failed check blocks that content and returns a clear error.

StageCheck
InputUser request before the first model call
Tool inputProposed arguments before a tool runs
Tool outputResult before it enters context or the next prompt
Final outputCompleted response before it is streamed or returned

Use permission rules for filesystem and command access, data policies for sensitive values, and content guardrails for application-specific terms or patterns. The permissions reference lists available controls.

Custom Guardrails​

To abort a dangerous action, raise an exception or return an error inside before_tool (either via a custom interceptor / lifecycle hook or the built-in GuardrailInterceptor / GuardrailChecker):


Argument Sanitization​

Interceptors and lifecycle hooks can also normalize or sanitize tool arguments (input_payload) before the tool receives them:

from ish import BaseInterceptor, LifecycleContext


class EmailSanitizerInterceptor(BaseInterceptor):
async def before_tool(self, ctx: LifecycleContext) -> None:
if (
ctx.entity_name == "send_email"
and isinstance(ctx.input_payload, dict)
and isinstance(ctx.input_payload.get("recipient"), str)
):
# Force lowercase and trim whitespace
ctx.input_payload["recipient"] = ctx.input_payload["recipient"].strip().lower()

Filesystem Permissions (PermissionsManager / PermissionsInterceptor)​

For filesystem operations, ish provides PermissionsManager and PermissionRule (with PermissionsInterceptor as a convenience wrapper in Python). The examples deny secret paths first, then allow reads and writes for all other paths relative to the sandbox root; the first matching rule decides the result:

from ish import (
Agent,
LocalSandbox,
PermissionRule,
PermissionsInterceptor,
PermissionsManager,
filesystem_tools,
)

sandbox = LocalSandbox("./workspace")

rules = [
PermissionRule(paths=[".env*", "secrets/**"], operations=["*"], mode="deny"),
PermissionRule(paths=["**"], operations=["read", "write"], mode="allow"),
]
permissions = PermissionsManager(rules=rules, default_mode="deny")

agent = Agent(
name="sandboxed_bot",
model="gpt-4o-mini",
tools=filesystem_tools(sandbox),
interceptors=[PermissionsInterceptor(permissions)],
)

Guarantees, limits​

  • Literal vs. handle-backed arguments: Enable sanitize_literal_arguments to run host-policy sanitizers on plain literal strings inside tool arguments; handle-backed and [SECRET:...] references always traverse their typed resolver (SecretMasker / Core vs HostAdapter resolution mode).
  • Stage rollback safety: Tool backends staging shared-context side data during execution must wait for finish_tool_output(true)—if the tool_output guardrail rejects the response, the runtime rejects the staged result so rejected outputs are never published to ContextStore.