---
title: "Put middleware in front of the session"
lesson_id: "02"
---

# Put middleware in front of the session

- **Lesson ID:** 02
- **Goal:** Introduce PromptGate around respond and Tool.call.
- **Human lesson:** [02-middleware-layer.html](02-middleware-layer.html)

## Prerequisites

Lesson 01.

## Inputs, outputs, and artifacts

- **Inputs:** Raw strings from UI and tools.
- **Outputs:** A single prepareForModel path.
- **Artifacts:** PromptGate and TextSource sketches.

## Agent build steps

1. Require every respond call to go through the gate.
2. Check tool output before it returns to the session.
3. Keep Guardrails.default on the session.
4. Link [Run tools in a safe box](../on-device-sandboxed-tools/), [Talk to tools with MCP](../on-device-mcp-server-client/), and [Make several agents agree first](../on-device-multi-agent-consensus/).

## Constraints

iOS 27 or later, or macOS 27 or later, and Xcode 27. Plain spoken English. No metaphor, quizzes, Mermaid, or em dashes. Apple's Guardrails.default is a safety filter, not PII redaction or injection detection. Do not invent a built-in injection API.

## Key concepts

- One gate owns the injection checker and the PII redactor.
- Prepare text for the model, then wrap `session.respond`.
- Use the same prepare path on tool arguments and tool results.
- Keep `guardrails: .default` on the session.

## Takeaways

- One door into the model: UI and tools go through middleware.
- Any raw paste straight to `session.respond` means middleware is not in production.
- Your gate covers injection and PII. Apple's default stays as a second layer.

## Acceptance checks

- UI and tools share the same gate.
- Sibling links, progressive .flow diagrams, and the Agent brief link are present.
- [ ] Proceed to [lesson brief](03-injection-checks.llms.md).
