← Back to Guides
GuideFor: AI Engineers, ML Engineers, Platform Engineers, AI Systems Architects

Deterministic Constraint Systems: Building Tool Registries That Keep Agents in Scope

The model will try to use tools it doesn't have, with parameters that don't exist. A closed, fail-closed registry is how you make every one of those calls fail in code instead of in production.

Updated
#harness-engineering#tool-registry#action-manifest#constraint-systems#llm-agents#production-ai-systems

The Tool That Didn't Exist

An agent was tasked with triaging customer support tickets and routing them to the appropriate team. It had four tools: get_ticket, assign_ticket, add_comment, and close_ticket.

Three days in, a ticket arrived that the agent decided was a billing issue. The agent called escalate_to_billing. This tool did not exist. The function call returned a tool-not-found error.

The agent tried again. Same error. It tried a variation: route_to_billing_team. Same error. It tried billing_escalation. Same error.

After six failed attempts, the agent added a comment to the ticket saying "Escalated to billing team" and closed it. The ticket was never escalated. The comment was false. The customer waited three days for a response from a team that never received the ticket.

The agent invented a tool that didn't exist, failed to call it, declared success anyway, and produced a false audit trail.

This is not a hallucination problem. The model didn't make up facts - it made up capabilities. And it had no way to know that escalate_to_billing didn't exist, because nobody had told it precisely which tools did exist and what they could do.

d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
call: "escalate_to_billing x6\nroute_to_billing_team, billing_escalation" {class: yellow}
err: "tool-not-found, six times" {class: red}
fake: "add_comment(\"Escalated to billing team\")\nclose_ticket()" {class: red}
out: "Ticket closed, never escalated\nfalse audit trail" {class: red}
call -> err -> fake -> out

The failure that mattered is the third box. The tool errors were correct, and what made the outcome worse was the agent's next move, which every one of its real tools allowed.

This is Part 8 of the Harness Engineering series - the final layer of the seven-layer Harness Architecture. Part 1 introduced the architecture. This article covers Layer 3 - the Constraint Layer - building tool registries and action manifests that reject every hallucinated tool call in code.

This series grew into a book: Harness Engineering for Production AI Systems. Chapter 10, "Deterministic Constraint Systems," covers this layer.

17 November 2026: fixed a scoping bug that exposed every tool when a context had no scope, replaced type coercion with rejection, made the action manifest actually enforced, and made the code runnable. Added provider strict tool schemas, tool search, and MCP tools, and gave every section its own diagram.


The Model's Imagination Is Not Your Action Space

This is the core problem the constraint layer solves.

The model has a training-time conception of what tools an agent might have. It knows about REST APIs. It knows about databases. It knows about email. It knows about file systems. All of this knowledge informs what tool calls it might attempt.

Your agent has a runtime action space: exactly the tools you've wired up, with exactly the parameters they accept, operating on exactly the resources they're permitted to access.

The gap between the model's imagination and your runtime action space is your Injection Surface for capability hallucination. The model will reach into that gap and call tools that don't exist, pass parameters that aren't valid, and attempt actions on resources it isn't permitted to touch.

The constraint system closes that gap in code.

Not by making the model smarter. Not by better prompting. By building a tool registry where every callable action is explicitly defined, every parameter is typed and validated, the model is shown only what's in scope, and anything outside that is rejected before it runs. The model can still propose a tool that doesn't exist; what changes is that the proposal fails at the registry instead of in production. Provider strict mode (Anthropic's strict: true on a tool, OpenAI's strict function calling) adds a second guarantee at decode time: calls come back well-formed. Well-formed is not the same as safe, though. A typed parameter still leaves the model choosing its value, which is where tool signature narrowing goes further.

d2
grid-rows: 1
grid-gap: 16
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
imagined: "What the model imagines" {
  label.near: top-center
  grid-columns: 1
  grid-gap: 8
  a: "escalate_to_billing" {class: yellow}
  b: "delete_all_tickets" {class: yellow}
  c: "assign_ticket(priority=...)" {class: yellow}
}
real: "What the registry admits" {
  label.near: top-center
  grid-columns: 1
  grid-gap: 8
  d: "get_ticket(ticket_id)" {class: green}
  e: "assign_ticket(ticket_id, team)" {class: green}
  f: "add_comment, close_ticket" {class: green}
}

The left column is unbounded and the right one is a list you wrote. The constraint layer's job is to make sure only the right column ever executes.


What a Tool Registry Actually Is

Most agent frameworks expose tools as a list of function signatures passed to the model. This is a start and a poor substitute for a constraint system.

A tool registry is a runtime data structure that:

  1. Defines every available action with complete, typed parameter specifications
  2. Validates every tool call before execution against those specifications
  3. Enforces scope rules that restrict which tools are available in which contexts
  4. Logs every tool call with full input/output for audit
python
from dataclasses import dataclass, fieldfrom typing import Any, Callableclass ToolCallError(Exception):    """Base class: every refusal carries what the model needs to self-correct."""class ToolNotFound(ToolCallError):    def __init__(self, tool_name: str, available_tools: list[str]):        super().__init__(f"Tool '{tool_name}' does not exist.")        self.available_tools = available_tools  # in-scope names onlyclass ToolOutOfScope(ToolCallError):    def __init__(self, tool_name: str, current_scope: list[str]):        super().__init__(f"Tool '{tool_name}' is not available in this context.")        self.current_scope = current_scopeclass ParameterError(ToolCallError):    def __init__(self, message: str, tool: "ToolDefinition"):        super().__init__(message)        self.tool = tool@dataclassclass ToolParameter:    name: str    type: type    required: bool    description: str    enum_values: list | None = None    min_value: float | None = None    max_value: float | None = None@dataclassclass ToolDefinition:    name: str    description: str    parameters: list[ToolParameter]    handler: Callable    scope_tags: list[str] = field(default_factory=list)  # e.g. ["ticket_read"]    def to_llm_schema(self) -> dict:        """Anthropic tool format, strict mode on: calls must match the schema."""        properties, required = {}, []        for param in self.parameters:            prop = {"type": _JSON_TYPES.get(param.type, "string"),                    "description": param.description}            if param.enum_values:                prop["enum"] = param.enum_values            properties[param.name] = prop            if param.required:                required.append(param.name)        return {            "name": self.name,            "description": self.description,            "strict": True,            "input_schema": {                "type": "object",                "properties": properties,                "required": required,                "additionalProperties": False,            },        }_JSON_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean"}class ToolRegistry:    def __init__(self):        self._tools: dict[str, ToolDefinition] = {}    def register(self, tool: ToolDefinition):        self._tools[tool.name] = tool    def get_tools_for_scope(self, scope_tags: list[str]) -> list[ToolDefinition]:        """Only tools whose scope_tags intersect the scope. No scope, no tools."""        return [t for t in self._tools.values()                if any(tag in scope_tags for tag in t.scope_tags)]    def to_llm_schemas(self, scope_tags: list[str]) -> list[dict]:        return [t.to_llm_schema() for t in self.get_tools_for_scope(scope_tags)]    def validate_and_execute(self, tool_name: str, tool_input: dict,                             scope_tags: list[str]) -> Any:        in_scope = [t.name for t in self.get_tools_for_scope(scope_tags)]        if tool_name not in self._tools:            raise ToolNotFound(tool_name, in_scope)        if tool_name not in in_scope:            raise ToolOutOfScope(tool_name, scope_tags)        tool = self._tools[tool_name]        self._validate_parameters(tool, tool_input)        return tool.handler(**tool_input)    def _validate_parameters(self, tool: ToolDefinition, inputs: dict):        known = {p.name for p in tool.parameters}        unknown = set(inputs) - known        if unknown:            raise ParameterError(f"Unknown parameters: {sorted(unknown)}", tool)        for param in tool.parameters:            if param.name not in inputs:                if param.required:                    raise ParameterError(                        f"Required parameter '{param.name}' missing", tool)                continue            value = inputs[param.name]            # Reject, don't coerce: bool("false") is True and int(2.7) is 2            if type(value) is not param.type:                raise ParameterError(                    f"Parameter '{param.name}' must be {param.type.__name__}, "                    f"got {type(value).__name__}: {value!r}", tool)            if param.enum_values and value not in param.enum_values:                raise ParameterError(                    f"Parameter '{param.name}' must be one of {param.enum_values}", tool)            if param.min_value is not None and value < param.min_value:                raise ParameterError(                    f"Parameter '{param.name}' must be >= {param.min_value}", tool)            if param.max_value is not None and value > param.max_value:                raise ParameterError(                    f"Parameter '{param.name}' must be <= {param.max_value}", tool)

The key behaviors:

ToolNotFound raises immediately with the list of tools available in this scope, never the whole registry. This error feeds back to the model on the next turn, allowing it to correct its tool selection. No silent failure, no agent pretending it escalated something it didn't.

No scope means no tools. An earlier version of this registry returned every tool when the scope list was empty, so a context nobody had configured got the widest possible access. A constraint system has to fail closed, the same way Part 4's policy engine denies by default.

Scope enforcement is runtime, not prompt-based. The scope restriction is enforced in code, not in the system prompt. Telling the model "you can only use read tools in this context" is a prompt-level hint. The registry enforcing scope in validate_and_execute is a hard constraint that cannot be overridden by the model's reasoning.

Reject, don't coerce. An earlier version tried param.type(value) on a mismatch. But bool("false") is True and int(2.7) is 2, so coercion quietly turns a wrong call into a different call. The registry now rejects unknown parameters and wrong types outright, and strict mode keeps most of them from arriving in the first place.

Registered with the four ticket tools plus a refund tool scoped to billing, and run in a triage scope, the registry answers:

text
not found; offered: ['get_ticket', 'assign_ticket', 'add_comment', 'close_ticket']unknown resource type -> []ToolOutOfScope: Tool 'refund' is not available in this context.ParameterError: Unknown parameters: ['priority']ParameterError: Parameter 'text' must be str, got bool: True
d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
call: "Proposed call" {class: yellow}
checks: "" {
  grid-rows: 1
  grid-gap: 10
  exists: "1. exists?" {class: violet}
  scope: "2. in scope?" {class: violet}
  params: "3. known params,\nexact types, ranges?" {class: violet}
}
fail: "Any no: structured error back to the model" {class: red}
run: "All yes: run the handler" {class: green}
call -> checks
checks -> fail
checks -> run

The three checks run in order of cost, and none of them asks the model anything. Every refusal is decided by data you wrote down, which is what makes the refusals predictable.


The Action Manifest

The action manifest is a higher-level concept that sits above the tool registry. Where the registry defines what tools exist and how to call them, the manifest defines what the agent is authorized to do in a specific task context.

python
class ManifestViolation(ToolCallError):    pass@dataclassclass ActionManifest:    task_id: str    task_type: str    allowed_scope_tags: list[str]    allowed_ticket_ids: list[str]    max_tool_calls: int    requires_human_approval_for: list[str]  # tool names handed to the gate    calls_made: int = 0    def admit(self, tool_name: str, tool_input: dict) -> bool:        """Raise if the call breaks the manifest; return True if it needs approval."""        if self.calls_made >= self.max_tool_calls:            raise ManifestViolation(f"Tool-call budget of {self.max_tool_calls} used up")        ticket = tool_input.get("ticket_id")        if ticket is not None and ticket not in self.allowed_ticket_ids:            raise ManifestViolation(f"Ticket {ticket!r} is outside this task")        self.calls_made += 1        return tool_name in self.requires_human_approval_fordef execute_under_manifest(registry: ToolRegistry, manifest: ActionManifest,                           tool_name: str, tool_input: dict, approval_gate) -> Any:    if manifest.admit(tool_name, tool_input) and not approval_gate(tool_name, tool_input):        raise ManifestViolation(f"'{tool_name}' was not approved")    return registry.validate_and_execute(tool_name, tool_input,                                         manifest.allowed_scope_tags)

For the ticket triage agent, the manifest would look like:

python
triage_manifest = ActionManifest(    task_id="triage-session-abc123",    task_type="ticket_triage",    allowed_scope_tags=["ticket_read", "ticket_write", "comment"],    allowed_ticket_ids=["T-1001", "T-1002", "T-1003"],    max_tool_calls=50,    requires_human_approval_for=["close_ticket"],)

The manifest would have shown the model exactly four tools: get_ticket, assign_ticket, add_comment, close_ticket. escalate_to_billing would not appear, and if the model proposed it anyway, the registry would reject it. What the model can't see, it rarely proposes. What it proposes anyway, the registry refuses.

A manifest is only a constraint if something enforces it. The earlier version of this class declared ticket ids, a call budget and approval requirements, and nothing read them. execute_under_manifest is the piece that does. It checks the call budget and the resource ids, then hands any approval-gated tool to the gate from Part 4 before the registry runs. With a two-call budget and a gate that refuses close_ticket:

text
T-1001->billingManifestViolation: Ticket 'T-9999' is outside this taskManifestViolation: 'close_ticket' was not approvedManifestViolation: Tool-call budget of 2 used up
d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
call: "Proposed call" {class: yellow}
manifest: "Manifest: budget left?\nticket in this task?" {class: violet}
gate: "Gate (Part 4): approval if listed" {class: blue}
registry: "Registry: exists, in scope, valid" {class: green}
call -> manifest -> gate -> registry

Each box answers a different question about the same call. The manifest asks whether it belongs to this task, the gate asks whether anyone must approve it, and the registry asks whether it's a well-formed call to a tool that exists.

This is the fundamental constraint design principle: the model's action space is what you show it, not what it imagines.


Dynamic Tool Scoping

Static tool registries give every agent the same tools in every context. Dynamic scoping restricts available tools based on the task phase, the agent's current position in a workflow, or the resource being operated on.

python
class DynamicToolScope:    def __init__(self, registry: ToolRegistry):        self.registry = registry    def tools_for_phase(self, phase: str) -> list[dict]:        phase_scopes = {            "planning": ["read"],            "execution": ["read", "write"],            "verification": ["read"],            "cleanup": ["read", "write", "delete"],        }        scope_tags = phase_scopes.get(phase, ["read"])        return self.registry.to_llm_schemas(scope_tags)    def tools_for_resource_type(self, resource_type: str) -> list[dict]:        resource_scopes = {            "ticket": ["ticket_read", "ticket_write", "comment"],            "user": ["user_read"],            # No write scope for billing: billing writes require separate approval        "billing": ["billing_read"],        }        # An unknown resource type gets no tools: the registry fails closed        scope_tags = resource_scopes.get(resource_type, [])        return self.registry.to_llm_schemas(scope_tags)

The evidence points the same way. Vercel reported that cutting its internal data agent from 17 tools to 2 raised success on its benchmark from 4 of 5 queries to 5 of 5. That's a small benchmark, and Vercel credits a well-documented semantic layer for much of the gain, but the direction is clear. Anthropic's tool-use docs say selection accuracy "degrades once you exceed 30–50 available tools", and OpenAI's function-calling guide suggests aiming for fewer than 20 functions at the start of a turn. More tools means more ways to get it wrong. Fewer, well-scoped tools means fewer failure modes and more reliable task completion.

Tool search is not scoping. For agents that genuinely need many tools, providers now offer deferred loading: Anthropic's tool search tool and defer_loading, OpenAI's tool_search. These keep most definitions out of the context window until the model searches for them. That's a context optimisation, not a constraint: a deferred tool is still registered and still callable. Scope first, then defer within the scope, and never let a search widen what the manifest allows.

d2
grid-rows: 1
grid-gap: 12
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
all: "Registry\nevery tool" {class: grey}
scoped: "Scope for this phase\nand resource\n(constraint)" {class: violet}
loaded: "Loaded into context\nnow; the rest deferred\n(optimisation)" {class: green}
all -> scoped -> loaded

The middle box is the constraint, and it's enforced in code. The right box only decides what the model reads first, so it must always sit inside the middle one.

Never give an agent more tools than it needs for the current phase of the current task.


Error Feedback to the Agent

When a tool call fails validation, the error message the model receives is a critical part of the constraint system. A good error message enables self-correction. A bad one produces retry loops.

python
def build_tool_error_feedback(error: ToolCallError, tool_name: str,                              tool_input: dict) -> str:    if isinstance(error, ToolNotFound):        return (            f"Tool '{tool_name}' does not exist.\n"            f"Available tools: {error.available_tools}\n"            "Please use one of the available tools or adjust your approach."        )    if isinstance(error, ToolOutOfScope):        return (            f"Tool '{tool_name}' is not available in the current task context.\n"            f"Current context allows: {error.current_scope}"        )    if isinstance(error, ParameterError):        required = [p.name for p in error.tool.parameters if p.required]        return (            f"Tool call failed: {error}\n"            f"Required parameters for '{tool_name}': {required}\n"            f"You provided: {list(tool_input.keys())}"        )    return f"Tool call refused: {error}"

The ToolNotFound error lists available tools. This is what enables the model to self-correct: it knows escalate_to_billing doesn't exist and can choose assign_ticket instead. Without this feedback, the model either loops or, worse, pretends it succeeded.

d2
grid-rows: 1
grid-gap: 16
classes: {
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
bad: "A bare error" {
  label.near: top-center
  grid-columns: 1
  grid-gap: 8
  a: "\"tool not found\"" {class: red}
  b: "model guesses another name" {class: red}
  c: "six tries, then fakes success" {class: red}
}
good: "A structured error" {
  label.near: top-center
  grid-columns: 1
  grid-gap: 8
  d: "\"not found; available: ...\"" {class: green}
  e: "model picks assign_ticket" {class: green}
  f: "one retry, real outcome" {class: green}
}

The only difference between the columns is the first box. An error that names the valid options turns a guessing loop into a single correction.


The Named Pattern: Closed Action Vocabulary

I call the combination of registry + manifest + dynamic scoping the Closed Action Vocabulary: the complete, exhaustive, and non-extensible set of actions the agent is permitted to take in a given context.

"Closed" is the operative word. The vocabulary has no open-ended extension mechanism at runtime. The model cannot add new tools by describing them. It cannot call undeclared functions. It cannot reach outside the boundary of what the registry exposes.

Every production agentic system should operate within a Closed Action Vocabulary. The vocabulary may be large. It may vary by context. But it is always defined, always enforced, and never improvised by the model - though a vocabulary only bounds which actions exist, never when each one is legal.

The model's imagination is unbounded. Its action space must not be.

MCP tools join the vocabulary by name, not by arriving. An MCP server can offer new tools at runtime, and its tools/list can change. The vocabulary stays closed only if each MCP tool you use is re-declared in your registry, allowlisted by name, with its schema pinned and its scope assigned by you. Don't derive scope or approval requirements from the server's own tool annotations. The MCP specification says "clients MUST consider tool annotations to be untrusted unless they come from trusted servers", and Part 4 treats them as hints for the same reason.

d2
direction: down
classes: {
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
mcp: "MCP server: tools/list\n(may change; annotations untrusted)" {class: grey}
allow: "Your allowlist: name, pinned schema,\nscope and approval set by you" {class: violet}
vocab: "Closed Action Vocabulary" {class: green}
mcp -> allow: "only listed tools pass"
allow -> vocab

The grey box can change whenever the server's owner wants. The violet box changes only when you do, and the vocabulary is built from it alone.


The Full Constraint System Flow

The registry, manifest, dynamic scoping, and error feedback don't operate independently - every tool call passes through all of them in sequence before a single external action executes.

d2
grid-rows: 6
grid-columns: 2
vertical-gap: 30
horizontal-gap: 130
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
a: "1. Model proposes a tool call\n(strict schema: well-formed)" {class: yellow}
y0: "" {style.opacity: 0}
m: "2. Manifest: budget, resource ids" {class: violet}
em: "ManifestViolation" {class: red}
r: "3. Registry: exists, in scope,\nknown params, exact types" {class: violet}
er: "Structured error:\nin-scope tools, required params" {class: red}
g: "4. Gated Execution (Part 4)" {class: green}
y3: "" {style.opacity: 0}
x: "5. Execute, write the audit log" {class: blue}
y4: "" {style.opacity: 0}
o: "6. Result back to the model" {class: yellow}
y5: "" {style.opacity: 0}
a -> m
m -> em: "no"
m -> r: "ok"
r -> er: "no"
r -> g: "ok"
g -> x -> o

Four things this diagram makes explicit. First, every refusal is structured: the model gets back the in-scope tools or the parameters it got wrong, which is what lets it correct itself rather than loop. Second, there is no coercion path. A call with the wrong type or an unknown parameter is refused, not rewritten into a different call. Third, the manifest runs before the registry, so a call to the wrong ticket is refused even if it's a perfectly valid call. Fourth, the flow runs on every tool call the model makes, not once per task.


What Observability Looks Like for This Layer

ToolNotFound rate by tool name - which non-existent tools does the model attempt most often? This tells you where your manifest is incomplete. If the model frequently attempts escalate_to_billing, you either need to add that tool or make the routing instruction clearer.

Parameter validation failure rate by tool and parameter - which parameters does the model get wrong most often? A high failure rate on a specific parameter signals a prompt-level description issue - the model doesn't understand what format that parameter expects.

Scope violation attempts - how often does the model attempt to call an out-of-scope tool? A non-zero rate means either your scope boundaries are misconfigured or the model is attempting to exceed its authorization. Both require investigation.

Tool call distribution - what fraction of calls go to each tool? An uneven distribution (90% of calls to one tool) may indicate the manifest is missing tools the agent needs, forcing it to use suboptimal substitutes.

d2
grid-rows: 2
grid-columns: 4
grid-gap: 12
classes: {
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
a: "Registry lookup" {class: violet}
b: "Parameters" {class: violet}
c: "Scope" {class: violet}
d: "Execution" {class: violet}
m1: "ToolNotFound by name" {class: grey}
m2: "Failures by tool\nand parameter" {class: grey}
m3: "Scope violation attempts" {class: grey}
m4: "Call distribution" {class: grey}

The left metric names the tools the model keeps wishing for, and that's the input for deciding whether to add one or fix a description.


What to Build First

First: Explicit tool schema definitions, in strict mode. Stop passing raw function signatures to the model. Define every tool with name, description, typed parameters, and required vs. optional fields, with additionalProperties: false. Turn on the provider's strict mode (strict: true on Anthropic tools, strict function calling on OpenAI) so calls arrive well-formed. Keep range checks in your own code: Anthropic's strict mode doesn't support minimum or maximum in the schema at all.

Second: Registry with ToolNotFound handling. Wrap every tool call in a registry check. If the model calls a tool that doesn't exist, return a structured error with the list of available tools. Never silently fail or let the model declare success on a failed tool call.

Third: Scope restriction. Identify which tools should be available in which contexts. Start with read/write/delete as your basic scope tags. Apply scope restrictions to agent tasks that don't need write access.

Fourth: Action manifest per task type. Define a manifest for each task type your agent performs. What tools, what scopes, what resource constraints, what approval requirements.

Fifth: Parameter validation that rejects. Refuse unknown parameters and wrong types instead of coercing them, and return an explicit error the model can act on. The error feedback the model receives on validation failure is as important as the validation itself.

Sixth: Tool call audit logging. Log every tool call: tool name, inputs, outputs, validation outcome, execution time. This is your agent's audit trail. You will need it.

d2
grid-columns: 1
grid-gap: 8
classes: {
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
}
s1: "1. Strict tool schemas" {class: green}
s2: "2. Registry with ToolNotFound" {class: green}
s3: "3. Scope restriction, failing closed" {class: violet}
s4: "4. Enforced manifest per task type" {class: violet}
s5: "5. Validation that rejects" {class: blue}
s6: "6. Audit log" {class: blue}

The first two would have stopped the opening incident on their own. The rest decide how much an agent may do once its calls are real.


Closing the Series: The Complete Harness Architecture

This is the final layer. With all seven in place, here is what the complete Harness Architecture looks like:

d2
grid-rows: 8
grid-columns: 2
vertical-gap: 30
horizontal-gap: 120
classes: {
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
req: "User request" {class: blue}
x0: "" {style.opacity: 0}
l1: "Layer 1: Normalization (Part 2)" {class: violet}
x1: "" {style.opacity: 0}
l2: "Layer 2: Context Orchestration (Part 3)" {class: violet}
x2: "" {style.opacity: 0}
llm: "LLM reasoning" {class: yellow}
l6: "Layer 6: retry, breaker, fallback\n(Part 6)" {class: red}
l3: "Layer 3: Constraint System (Part 8)" {class: green}
x4: "" {style.opacity: 0}
l5: "Layer 5: Validation (Part 5)" {class: green}
x5: "" {style.opacity: 0}
l4: "Layer 4: Gated Execution (Part 4)" {class: green}
x6: "" {style.opacity: 0}
act: "Action execution" {class: blue}
l7: "Layer 7: State Management\n(Part 7)" {class: teal}
req -> l1 -> l2 -> llm
llm -> l6: "provider failure"
llm -> l3 -> l5 -> l4 -> act
act -> l7: "long-running"

Seven layers. Each one a specific failure mode absorbed before it propagates. Together, they are the infrastructure that separates a demo from a production system.

The model is the least reliable component in your stack. The harness is how you ship it anyway.


The Complete Series

Going deeper: Chapter 10 of the book

This is Part 8 of the Harness Engineering series, which grew into Harness Engineering for Production AI Systems. This layer became Chapter 10, "Deterministic Constraint Systems," which builds the full tool-safety matrix as a TOML file with a loader that refuses unsafe rows, wires admission and the policy gate into a LangGraph graph in that order, and shows how to test the matrix as a file.

The code for that chapter is the ch10-deterministic-constraints tag of the companion repository. Its tests need no model and no API key.

For a chapter-length treatment on this blog, including where it departs from the book, see Strict Tool Schemas Aren't Enough: Narrow LLM Tool Calls, Part 10 of the chapter-by-chapter guide to the book.


References

  1. Yao, S., Zhao, J., Yu, D., et al. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. ICLR 2023. https://arxiv.org/abs/2210.03629

  2. Shinn, N., Cassano, F., Berman, E., Gopinath, A., Narasimhan, K., & Yao, S. (2023). Reflexion: Language Agents with Verbal Reinforcement Learning. arXiv:2303.11366. https://arxiv.org/abs/2303.11366

  3. Anthropic. Tool use overview and tool search tool. https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview and https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool

  4. OpenAI. Function calling. https://developers.openai.com/api/docs/guides/function-calling

  5. Schick, T., Dwivedi-Yu, J., Dessì, R., et al. (2023). Toolformer: Language Models Can Teach Themselves to Use Tools. NeurIPS 2023. https://arxiv.org/abs/2302.04761

  6. Greshake, K., Abdelnabi, S., Mishra, S., et al. (2023). Not What You've Signed Up For: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection. arXiv:2302.12173. https://arxiv.org/abs/2302.12173

  7. Chase, H. (2022). LangChain: Building applications with LLMs through composability. https://github.com/langchain-ai/langchain

  8. Kumar, R. (2026). Harness Engineering for Production AI Systems. Chapter 10, "Deterministic Constraint Systems." https://harness.ranjankumar.in/

  9. Vercel. We removed 80% of our agent's tools. https://vercel.com/blog/we-removed-80-percent-of-our-agents-tools

  10. Model Context Protocol. Specification 2026-07-28: Tools. https://modelcontextprotocol.io/specification/2026-07-28/server/tools

References 1, 2, 5, 6 and 7 are background reading on tool-using agents; they are not cited for specific claims above.


AI Security

Systems Design

Follow for more technical deep dives on AI/ML systems, production engineering, and building real-world applications:


Books by Ranjan Kumar

Federated AI Agents cover

Federated AI Agents

Right-Sized AI cover

Right-Sized AI

Harness Engineering for Production AI Systems cover

Harness Engineering

The 7 GenAI Architectures cover

The 7 GenAI Architectures

Building Real-World Agentic AI Systems with LangGraph cover

Building Real-World Agentic AI Systems

The ChatML Handbook cover

The ChatML Handbook

The Chat Templates Handbook cover

The Chat Templates Handbook

Comments