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.
- Python
- TypeScript
- Rust
- Go
- C#
- Java
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=["--"]),
],
)
import { Agent, GuardrailChecker, IshClient } from "ish-harness";
const client = new IshClient();
const guardrail = new GuardrailChecker(
client,
["rm -rf"],
["DROP TABLE", "SHUTDOWN"],
);
const agent = new Agent({
name: "secured_agent",
model: { provider: "openai_chat", name: "gpt-4o-mini" },
lifecycle: ({ event, context }) => {
if (event === "before_tool") {
const payload = JSON.stringify(context.input_payload ?? {});
const violation = guardrail.check(payload);
if (violation) {
throw new Error(`Action blocked (${violation.type}): ${violation.message}`);
}
}
},
});
use async_trait::async_trait;
use ish_harness::interceptors::{LifecycleContext, LifecycleEvent, LifecycleObserver};
use ish_harness::GuardrailChecker;
struct SecurityGuardrail {
checker: GuardrailChecker,
}
#[async_trait]
impl LifecycleObserver for SecurityGuardrail {
async fn dispatch(
&self,
event: LifecycleEvent,
context: &mut LifecycleContext,
_chunk: Option<&str>,
) -> Result<(), String> {
if event == LifecycleEvent::BeforeTool {
let payload = context
.input_payload
.as_ref()
.map(|value| value.to_string())
.unwrap_or_default();
if let Some((kind, reason)) = self.checker.check(&payload) {
return Err(format!("Action blocked ({kind}): {reason}"));
}
}
Ok(())
}
}
let guardrail = SecurityGuardrail {
checker: GuardrailChecker::new(
vec!["rm -rf".into()],
vec!["DROP TABLE".into(), "SHUTDOWN".into()],
),
};
guardrail, err := ish.NewGuardrailChecker(
client,
[]string{"rm -rf"},
[]string{"DROP TABLE", "SHUTDOWN"},
)
if err != nil {
panic(err)
}
defer guardrail.Close()
lifecycle := func(req map[string]any) (any, bool, error) {
if req["event"] == "before_tool" {
ctxMap, _ := req["context"].(map[string]any)
raw, _ := json.Marshal(ctxMap["input_payload"])
violation, err := guardrail.Check(string(raw))
if err != nil {
return nil, false, err
}
if violation != nil {
return nil, false, fmt.Errorf("action blocked (%v): %v", violation["type"], violation["message"])
}
}
return nil, false, nil
}
using System.Text.Json;
using Ish.Harness;
using var client = new IshClient();
using var guardrail = new GuardrailChecker(
client,
deniedCommands: ["rm -rf"],
blockedKeywords: ["DROP TABLE", "SHUTDOWN"]);
using var request = new AgentRunRequest
{
AgentName = "secured_agent",
Model = new AgentModel { Provider = "openai_chat", Name = "gpt-4o-mini" },
UserPrompt = "Inspect recent logs.",
Lifecycle = req =>
{
if (req.GetProperty("event").GetString() == "before_tool")
{
var payload = req.GetProperty("context").TryGetProperty("input_payload", out var input)
? input.GetRawText()
: "{}";
var violation = guardrail.Check(payload);
if (violation is { } v)
{
throw new InvalidOperationException(
$"Action blocked ({v.GetProperty("type").GetString()}): {v.GetProperty("message").GetString()}");
}
}
return null;
},
};
import io.github.ishharness.GuardrailChecker;
import io.github.ishharness.IshClient;
import java.util.List;
try (var guardrail = new GuardrailChecker(
client, List.of("rm -rf"), List.of("DROP TABLE", "SHUTDOWN"));
var request = new IshClient.AgentRequest(
"gpt-4o-mini",
"Help safely inspect database diagnostics.",
"Check table row counts.")
.provider("openai_chat")
.agentName("secured_agent")
.lifecycle(req -> {
if ("before_tool".equals(req.path("event").asText())) {
String payload = req.path("context").path("input_payload").toString();
var violation = guardrail.check(payload);
if (violation != null) {
throw new SecurityException(
"Action blocked (" + violation.path("type").asText() + "): "
+ violation.path("message").asText());
}
}
return null;
})) {
var result = client.runAgent(request);
System.out.println(result);
}
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
| Check | What it protects |
|---|---|
| Reference and ownership | Prevents reuse across sessions or tenants |
| Caller and destination | Restricts which tools can receive a secret |
| Argument path | Limits which tool fields accept secret values |
| Expiration and revocation | Blocks stale or withdrawn references |
| Masking policy | Prevents 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.
| Stage | Check |
|---|---|
| Input | User request before the first model call |
| Tool input | Proposed arguments before a tool runs |
| Tool output | Result before it enters context or the next prompt |
| Final output | Completed 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:
- Python
- TypeScript
- Rust
- Go
- C#
- Java
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()
import { Agent } from "ish-harness";
const agent = new Agent({
name: "email_assistant",
model: { provider: "openai_chat", name: "gpt-4o-mini" },
lifecycle: ({ event, context }) => {
if (
event === "before_tool" &&
context.entity_name === "send_email" &&
context.input_payload &&
typeof context.input_payload === "object" &&
!Array.isArray(context.input_payload) &&
typeof context.input_payload.recipient === "string"
) {
return {
...context,
input_payload: {
...context.input_payload,
recipient: context.input_payload.recipient.trim().toLowerCase(),
},
};
}
},
});
use async_trait::async_trait;
use ish_harness::interceptors::{LifecycleContext, LifecycleEvent, LifecycleObserver};
struct EmailSanitizerInterceptor;
#[async_trait]
impl LifecycleObserver for EmailSanitizerInterceptor {
async fn dispatch(
&self,
event: LifecycleEvent,
context: &mut LifecycleContext,
_chunk: Option<&str>,
) -> Result<(), String> {
if event == LifecycleEvent::BeforeTool && context.entity_name == "send_email" {
if let Some(args) = context.input_payload.as_mut().and_then(|v| v.as_object_mut()) {
if let Some(rec) = args.get("recipient").and_then(|v| v.as_str()) {
args.insert(
"recipient".to_string(),
serde_json::Value::String(rec.trim().to_lowercase()),
);
}
}
}
Ok(())
}
}
lifecycle := func(req map[string]any) (any, bool, error) {
ctxMap, _ := req["context"].(map[string]any)
if req["event"] == "before_tool" && ctxMap["entity_name"] == "send_email" {
if args, ok := ctxMap["input_payload"].(map[string]any); ok {
if rec, ok := args["recipient"].(string); ok {
args["recipient"] = strings.ToLower(strings.TrimSpace(rec))
return ctxMap, true, nil
}
}
}
return nil, false, nil
}
using System.Text.Json;
using System.Text.Json.Nodes;
using Ish.Harness;
LifecycleHook sanitizeEmail = req =>
{
if (req.GetProperty("event").GetString() != "before_tool")
{
return null;
}
var ctx = JsonNode.Parse(req.GetProperty("context").GetRawText())!.AsObject();
if (ctx["entity_name"]?.GetValue<string>() == "send_email" &&
ctx["input_payload"] is JsonObject args &&
args["recipient"]?.GetValue<string>() is string recipient)
{
args["recipient"] = recipient.Trim().ToLowerInvariant();
return JsonDocument.Parse(ctx.ToJsonString()).RootElement.Clone();
}
return null;
};
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.ishharness.IshClient;
request.lifecycle(req -> {
JsonNode contextNode = req.path("context");
if ("before_tool".equals(req.path("event").asText())
&& "send_email".equals(contextNode.path("entity_name").asText())) {
ObjectNode updated = ((ObjectNode) contextNode).deepCopy();
JsonNode args = updated.get("input_payload");
if (args instanceof ObjectNode obj && obj.hasNonNull("recipient")) {
obj.put("recipient", obj.get("recipient").asText().trim().toLowerCase());
return updated;
}
}
return null;
});
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:
- Python
- TypeScript
- Rust
- Go
- C#
- Java
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)],
)
import { Agent, IshClient, PermissionsManager, Sandbox } from "ish-harness";
const client = new IshClient();
const sandbox = new Sandbox(client, "./workspace");
const permissions = new PermissionsManager(
client,
[
{ paths: [".env*", "secrets/**"], operations: ["*"], mode: "deny" },
{ paths: ["**"], operations: ["read", "write"], mode: "allow" },
],
"deny",
);
const agent = new Agent({
name: "sandboxed_bot",
model: { provider: "openai_chat", name: "gpt-4o-mini" },
tools: sandbox.agentTools(),
lifecycle: ({ event, context }) => {
if (
event === "before_tool" &&
context.input_payload &&
typeof context.input_payload === "object" &&
!Array.isArray(context.input_payload) &&
typeof context.input_payload.path === "string"
) {
const allowed = permissions.checkFileTool(
context.entity_name,
context.input_payload.path,
);
if (allowed === false) {
throw new Error(`Permission denied for ${context.entity_name}`);
}
}
},
});
use ish_harness::permissions::{PermissionRule, PermissionsManager};
use ish_harness::LocalSandbox;
let _sandbox = LocalSandbox::new("./workspace");
let rules = vec![
PermissionRule {
paths: vec![".env*".into(), "secrets/**".into()],
operations: vec!["*".into()],
mode: "deny".into(),
},
PermissionRule {
paths: vec!["**".into()],
operations: vec!["read".into(), "write".into()],
mode: "allow".into(),
},
];
let permissions = PermissionsManager::new(rules, "deny");
assert!(!permissions.check("read", ".env.production"));
assert_eq!(permissions.check_file_tool("read_file", ".env.production"), Some(false));
assert!(permissions.check("write", "workspace/output.txt"));
sandbox, err := ish.NewSandbox(client, "./workspace")
if err != nil {
panic(err)
}
defer sandbox.Close()
tools, err := sandbox.AgentTools()
if err != nil {
panic(err)
}
permissions, err := ish.NewPermissionsManager(client, []ish.PermissionRule{
{Paths: []string{".env*", "secrets/**"}, Operations: []string{"*"}, Mode: "deny"},
{Paths: []string{"**"}, Operations: []string{"read", "write"}, Mode: "allow"},
}, "deny")
if err != nil {
panic(err)
}
defer permissions.Close()
result, err := client.Run(ctx, ish.AgentRunRequest{
AgentName: "sandboxed_bot",
Model: &ish.AgentModel{Provider: "openai_chat", Name: "gpt-4o-mini"},
Tools: tools,
Lifecycle: func(req map[string]any) (any, bool, error) {
ctxMap, _ := req["context"].(map[string]any)
if req["event"] == "before_tool" {
args, _ := ctxMap["input_payload"].(map[string]any)
if path, ok := args["path"].(string); ok {
toolName, _ := ctxMap["entity_name"].(string)
if okPtr, err := permissions.CheckFileTool(toolName, path); err != nil {
return nil, false, err
} else if okPtr != nil && !*okPtr {
return nil, false, fmt.Errorf("permission denied for %s on %s", toolName, path)
}
}
}
return nil, false, nil
},
})
using Ish.Harness;
using var client = new IshClient();
using var sandbox = new Sandbox(client, "./workspace");
using var permissions = new PermissionsManager(
client,
[
new PermissionRule([".env*", "secrets/**"], ["*"], "deny"),
new PermissionRule(["**"], ["read", "write"], "allow"),
],
defaultMode: "deny");
using var request = new AgentRunRequest
{
AgentName = "sandboxed_bot",
Model = new AgentModel { Provider = "openai_chat", Name = "gpt-4o-mini" },
Tools = sandbox.AgentTools(),
UserPrompt = "List workspace files.",
Lifecycle = req =>
{
if (req.GetProperty("event").GetString() == "before_tool")
{
var ctx = req.GetProperty("context");
if (ctx.TryGetProperty("input_payload", out var input) &&
input.TryGetProperty("path", out var pathProp) &&
pathProp.GetString() is string targetPath)
{
var toolName = ctx.GetProperty("entity_name").GetString() ?? "";
if (permissions.CheckFileTool(toolName, targetPath) == false)
{
throw new UnauthorizedAccessException($"Permission denied for {toolName} on {targetPath}");
}
}
}
return null;
},
};
import io.github.ishharness.IshClient;
import io.github.ishharness.PermissionsManager;
import io.github.ishharness.Sandbox;
import java.util.List;
try (var sandbox = new Sandbox(client, "./workspace");
var permissions = new PermissionsManager(
client,
List.of(
new PermissionsManager.Rule(List.of(".env*", "secrets/**"), List.of("*"), "deny"),
new PermissionsManager.Rule(List.of("**"), List.of("read", "write"), "allow")),
"deny");
var request = new IshClient.AgentRequest(
"gpt-4o-mini",
"Stay inside workspace files.",
"List workspace files.")
.provider("openai_chat")
.agentName("sandboxed_bot")) {
for (var tool : sandbox.agentTools()) {
request.operationTool(tool);
}
request.lifecycle(req -> {
if ("before_tool".equals(req.path("event").asText())) {
var ctx = req.path("context");
var pathNode = ctx.path("input_payload").path("path");
if (pathNode.isTextual()) {
String toolName = ctx.path("entity_name").asText();
Boolean allowed = permissions.checkFileTool(toolName, pathNode.asText());
if (Boolean.FALSE.equals(allowed)) {
throw new SecurityException("Permission denied for " + toolName + " on " + pathNode.asText());
}
}
}
return null;
});
var result = client.runAgent(request);
System.out.println(result);
}
Guarantees, limits
- Literal vs. handle-backed arguments: Enable
sanitize_literal_argumentsto run host-policy sanitizers on plain literal strings inside tool arguments; handle-backed and[SECRET:...]references always traverse their typed resolver (SecretMasker/CorevsHostAdapterresolution mode). - Stage rollback safety: Tool backends staging shared-context side data during execution must wait for
finish_tool_output(true)—if thetool_outputguardrail rejects the response, the runtime rejects the staged result so rejected outputs are never published toContextStore.