New Article

Every Tool Call Needs a Gatekeeper

By Mahmoud Zalt

We’re examining how Microsoft Semantic Kernel governs AI tool calls. Semantic Kernel is an orchestration framework that connects application code, plugins, and AI services; its kernel.py file provides the public Kernel facade that coordinates those pieces. That facade matters because a model can produce plausible function names and arguments without having authority over either. I’m Mahmoud Zalt, an AI solutions architect, and we’ll follow this boundary from tool selection through execution, history, and streaming to learn the central lesson: an AI runtime must treat every tool call as untrusted input and enforce policy at one observable gate.

The Kernel as a Policy Boundary

Kernel is a facade: one interface in front of specialized subsystems. Its extensions separate function lookup, service lookup, filters, and reliability concerns, so callers do not rebuild orchestration for every invocation. But its value is not merely convenience. It is the place where the system can make consistent decisions before model output reaches application capabilities.

Application or agent
        |
        v
      Kernel
   /      |       \
plugins  filters  AI services
   \      |       /
        function
           |
           v
 FunctionResult / ChatHistory

Model tool call
  -> resolve and validate
  -> run filter stack
  -> invoke function
  -> convert result
  -> append to history
The kernel coordinates policy and routing while plugins and providers implement the underlying work.

This placement is crucial. A tool call crosses from probabilistic output into deterministic authority: plugin code, service clients, mutable conversation state, and possibly external side effects. A facade should hide coordination, not hide policy. Callers need clear guarantees about validation, failure handling, mutation, and resource use.

That leads to the first job of the gatekeeper: distinguish the functions and arguments a model can describe from the actions and context the host controls.

Validate What the Model May Say

invoke_function_call applies that distinction before execution. A configured function-choice filter can constrain selection, and argument validation separates required parameters from parameters the model may supply. A host-only parameter may carry a tenant identifier, authorization scope, or internal setting; its presence in a Python signature must not grant the model permission to set it.

required_param_names = {
    p.name for p in function_to_call.parameters
    if p.name is not None and p.is_required
}
model_param_names = {
    p.name for p in function_to_call.parameters
    if p.include_in_function_choices
}
received_param_names = set(parsed_args or {})

missing_params = required_param_names - received_param_names
unexpected_params = received_param_names - model_param_names

The set differences make the policy explicit: required names describe what must arrive, model-visible names describe what may arrive, and received names describe what did arrive. Missing arguments and attempts to set hidden arguments become corrective tool feedback in ChatHistory, rather than necessarily ending the conversation. For malformed model output, recovery is often the right behavior.

BoundaryKernel behaviorWhy it matters
Function selectionChecks configured function-choice filtersConstrains tools to the advertised set
Required argumentsReports missing namesMakes schema mismatches recoverable
Hidden argumentsRejects parameters excluded from function choicesPreserves host control of sensitive context
Execution policyRuns auto-invocation filtersApplies cross-cutting policy consistently
Recorded resultsDeep-copies values before history serializationPrevents later mutation from changing the record

We should not mistake this for complete authorization. When function_behavior is absent, the method proceeds without allowlist validation; even with an allowlist, the host must decide whether the current user or tenant may perform the underlying action. Tool visibility and authorization are separate decisions.

Keep the Gate Testable

Centralizing policy does not justify centralizing every branch. invoke_function_call has 116 source lines, cyclomatic complexity 16, and cognitive complexity 24. It resolves a function, applies an allowlist, parses and validates arguments, constructs recovery messages, creates invocation context, runs filters, snapshots results, updates history, and decides whether execution terminates.

Each step belongs near the boundary; their concentration raises regression risk. A change to validation can accidentally change whether a tool executes, whether history receives a message, or whether the loop continues. Cognitive complexity does not prove code is wrong, but here it identifies a method that is difficult to reason about and test as one unit.

Extract three policy-shaped operations: resolve and validate function membership; parse and validate model arguments; and convert every outcome into exactly one history message. Those seams support direct contracts: a rejected tool never runs, hidden parameters never enter KernelArguments, and a recoverable failure produces neither zero nor duplicate history messages.

The extraction must preserve the AUTO_FUNCTION_INVOCATION filter stack around execution. That interceptor pipeline is the right place for cross-cutting concerns such as telemetry, approval, and termination; helpers should clarify orchestration, not bypass it. The same ownership discipline appears in clone: configuration collections can diverge, while service clients and callable identities remain shared because they may contain non-serializable asynchronous resources.

Bound the Cost of Convenience

A gatekeeper also owns resource boundaries. Streaming illustrates why asynchronous code is not automatically bounded. invoke_stream can relay messages as they arrive, but with return_function_results enabled it retains streamed messages and reconstructs final choices. Its local time and space become O(m + c), where m is message count and c is the total number of streamed choices.

That is reasonable for short responses and risky for long-running agent streams. The same aggregation appears in invoke_stream and invoke_prompt_stream, so a fix to choice-index handling or memory policy must be made twice. Centralizing aggregation would not eliminate buffering, but it would give buffering policy one home for limits, incremental accumulation, and parity tests.

Embedding ingestion exposes a related edge. add_embedding_to_object batches extracted text into one provider request, efficient until the batch approaches provider limits. It also inspects inputs[0] to identify dictionary-like list records, making an empty list an avoidable IndexError. A defined empty-input contract—a no-op or documented ValueError—is another small but important boundary.

Build a Production Gatekeeper

The primary lesson is simple: every AI tool call needs a gatekeeper because model output is a request for authority, not authority itself. Semantic Kernel’s Kernel shows the right shape: validate selectable functions and model-supplied arguments, run calls through filters, preserve host-only context, turn recoverable schema failures into feedback, and record stable results. Its branch-heavy invocation method and unbounded aggregation paths show where that boundary needs further hardening.

Those controls turn a facade into a reliable control point. As agents gain access to more capabilities, the next improvement is not broader tool exposure; it is sharper, measurable boundaries around every capability they can request.


View Permalink