FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Tool Input and Output Validation

Validate typed tool arguments before execution and treat tool output as untrusted data afterward.

Freshness: current•15 min read•Security, Safety, and Governance

Key Learning Outcomes

  • ✓Explain the operating model behind Tool Input and Output Validation.
  • ✓Evaluate trade-offs and failure modes for Tool Input and Output Validation.
  • ✓Apply Tool Input and Output Validation to a production decision.
Full Technical Reference Document

Mental model

A JSON Schema confirms field data types rather than authorization safety or semantic truth. Secure AI tool boundaries enforce two orthogonal checks on every call: inbound validation canonicalizes inputs (resolve paths, strip SSRF hosts, reject extra keys) ahead of authorization checks cleanly, while outbound handling clamps size, verifies real content types, escapes markup, and fences tool responses strictly as untrusted external data before models see them.

Model JSON args
Canonicalize once + reject extra keys
Authorize normalized domain bounds
Execute tool cleanly
Clamp bytes, escape XSS & tag untrusted
Feed clean data back to model
Conceptual teaching model synthesized from:Model Context Protocol Architecture and Tools SpecificationOWASP Top 10 for LLM Applications

Learning outcomes

  • Enforce "canonicalize once, validate once, execute from canonical output" preventing Unicode homoglyph and ../ path-traversal bypasses (TOCTOU).
  • Protect HTTP fetch/webhook tools cleanly against Server-Side Request Forgery (SSRF targeting private VPC/metadata IPs).
  • Prevent context-window flooding and indirect prompt injection on returning tool results via strict truncation and delimiter tagging.

Theory

Teams routinely trust model-supplied arguments simply because a schema library validated { "url": "string", "path": "string" }! An attacker hiding instructions inside an analyzed ticket can instruct the tool cleanly cleanly to call url = "http://169.254.169.254/latest/meta-data/" or path = "/workspace/./../../etc/passwd"—both 100% valid JSON strings that pass Pydantic/Zod defaults unless semantic domain validation enforces boundaries explicitly:

Validation DirectionTarget DefectMandatory Control PatternAnti-Pattern to Reject
Inbound SchemaUnexpected privileged fields (role: "admin", force_bypass: true)extra="forbid" (Pydantic) / .strict() (Zod)Permitting arbitrary unknown JSON properties by default
Inbound Filesystem & URLDirectory traversal (..%2F), symlink escapes, cloud IMDS SSRFResolve os.path.realpath() under fixed root; resolve IP & block RFC1918/link-localRegex string checks (not "../" in path) easily bypassed via URL decode
Outbound Payload SizeTool returning 12 MB log dump crashing context budget or causing OOMHard truncate output bytes (max_chars) + signal "truncated: true" + pagination handleForwarding whole un-truncated raw database or grep dumps cleanly
Outbound Trust IsolationRetrieved issue prose containing "Ignore previous rules..." injectionWrap inside <tool_result untrusted="true"> + HTML escape UI embeds + magic-byte checksBlending tool text seamlessly alongside system prompts or trusting .pdf filename claims
python
import ipaddress
import os
import socket
from urllib.parse import urlparse
​
def validate_safe_file_read(root_dir: str, requested_path: str) -> str:
"""Resolve symlinks and relative segments once before enforcing directory root confinement."""
root_real = os.path.realpath(root_dir)
candidate_real = os.path.realpath(os.path.join(root_real, requested_path))
if candidate_real != root_real and not candidate_real.startswith(root_real + os.sep):
raise PermissionError("Path traversal or symlink escape outside authorized root")
return candidate_real # Caller MUST use returned canonical path directly!
​
def validate_safe_external_https(raw_url: str) -> str:
"""Reject non-HTTPS schemes and private/link-local SSRF targets (cloud IMDS)."""
parsed = urlparse(raw_url.strip())
if parsed.scheme != "https" or not parsed.hostname:
raise ValueError("Only valid external https:// URLs permitted")
resolved_ip = ipaddress.ip_address(socket.gethostbyname(parsed.hostname))
if resolved_ip.is_private or resolved_ip.is_loopback or resolved_ip.is_link_local or resolved_ip.is_multicast:
raise PermissionError(f"Blocked internal/SSRF IP target: {resolved_ip}")
return raw_url.strip()

Trade-offs

Strict strictness rules (additionalProperties: false, tight numeric ranges, binary magic-byte inspection, deterministic outbound truncation) shrink the attack surface cleanly and prevent sudden context explosions across unverified third-party endpoints. Overly brittle regex allowlists occasionally reject benign future schema additions or non-ASCII customer names unless teams test strict schemas against realistic noisy inputs cleanly alongside clean structured validation hints so models self-correct harmless format slips within 1–2 turns cleanly.

Failure modes and misconceptions

  • Checking Un-Normalized Input Strings Then Opening Raw Paths: Validating raw_path cleanly before URL-decoding or symlink traversal enables classic %2e%2e/ escapes cleanly.
  • Trusting User-Supplied MIME Extensions: Accepting "report.png" purely by file suffix allows HTML/SVG script payloads (<script>) cleanly if content bytes aren't inspected.
  • Toggling System Rules Based on Schema-Valid Tool Data: Letting retrieved support tickets containing schema-valid JSON "instructions": "override refund cap" steer control logic cleanly without delimiter firewalls.
  • Silent Output Dropping Without Truncation Flags: Truncating long search logs silently at 2KB without informing the model "Showing lines 1..80 of 4,200" causes premature false conclusions cleanly.

Decision scenario

A documentation research assistant offers tools read_workspace_file(path) and fetch_reference_url(url) running inside shared Kubernetes pods. Red-teamers just demonstrated reading /etc/shadow via symlink paths, querying internal Kubernetes metadata (169.254.169.254), and blowing context budgets via 10MB HTML responses carrying embedded prompt overrides cleanly. Design end-to-end inbound canonicalization, SSRF filtering, outbound truncation, and untrusted tagging cleanly.

Reflect before revealing the guide

Why must an agent runtime still treat a schema-valid external tool output strictly as untrusted data rather than clean context instructions?

Prerequisites & Related Concepts (3)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-301Agentic Systems Engineer

Engineer bounded tool-using systems with explicit workflows state protocols evaluation observability security and human control.

27 concepts~29h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.