# Main Tutor Loop Session Driven by the Learn Skill: 5-Phase Architecture

> Understand the 5-phase architecture of a main tutor loop session driven by the learn skill. Discover how Bayesian Knowledge Tracing and MCP integration ensure learner mastery in stateless LLM interactions.

- Repository: [Rohit Ghumare/ai-engineering-from-scratch](https://github.com/rohitg00/ai-engineering-from-scratch)
- Tags: architecture
- Published: 2026-09-02

---

**The main tutor loop session driven by the learn skill implements a reusable five-phase cycle—Initialize, Prepare Prompt, Interact, Update State, and Terminate—that leverages Bayesian Knowledge Tracing and Model-Context-Protocol (MCP) integration to maintain persistent learner mastery across stateless LLM interactions.**

The `rohitg00/ai-engineering-from-scratch` repository provides a modular framework for AI engineering education, with the **learn** skill serving as the core engine for interactive tutoring. This skill implements a structured main tutor loop session that orchestrates adaptive learning conversations through persistent state management and dynamic prompt engineering.

## Overview of the Main Tutor Loop Session

The architecture centers on [`skills/learn/SKILL.md`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn/SKILL.md), which defines the high-level orchestration logic for driving interactive sessions. Unlike simple chat loops, this implementation maintains a **LearnerState** object that tracks mastery vectors and interaction history across multiple turns.

## The Five Phases of the Learn Skill Tutor Loop

The main tutor loop session proceeds through five distinct phases, each implemented via specific modules in the skills directory.

### 1. Initialize Learner State

The loop begins by instantiating the `LearnerState` class from [`skills/learn/state.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn/state.py). This object initializes mastery vectors for tracked concepts and attempts to load prior context from the `learning-artifacts/` directory via the `load()` method. If previous session data exists, the skill restores the knowledge trace to enable continuous learning across interrupted sessions.

### 2. Prepare System Prompt

During the preparation phase, the system assembles a context-rich prompt using `build_prompt()` from [`skills/learn_mcp/prompts.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn_mcp/prompts.py). This function injects the current learner's mastery levels, historical performance, and the active learning objective into a skill-specific template. The resulting prompt instructs the LLM to act as a tutor while respecting the learner's current competency profile.

### 3. Interact via MCP Client

The interaction phase sends the prepared prompt to the LLM through the **Model-Context-Protocol (MCP)** client implemented in [`skills/learn-mcp/client.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn-mcp/client.py). The `mcp_chat()` function handles stateless LLM inference while preserving session context on the client side. The LLM returns a structured response that the system parses into discrete actions—such as asking questions, providing explanations, or suggesting exercises.

### 4. Update Knowledge State

Following user interaction, the loop parses the response using `parse_answer()` from [`skills/learn/parser.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn/parser.py) to extract answers and correctness indicators. The `LearnerState.update()` method then applies a **Bayesian Knowledge Tracing (BKT)** style update—adjusting `p_learn` probabilities per concept based on the interaction outcome. The modified mastery vectors are immediately persisted to disk via the `save()` method, ensuring durability of the knowledge trace.

### 5. Evaluate Termination Criteria

The final phase checks termination conditions defined in the session configuration. The loop exits when the learner achieves the mastery threshold (e.g., `p_learn > 0.8` for target concepts), reaches the maximum step limit, or explicitly requests exit. If termination criteria are not met, the cycle returns to the Prepare Prompt phase with updated state.

## Core Architectural Components

Three primary components enable the stateful behavior of the otherwise stateless LLM interactions.

### LearnerState and Bayesian Knowledge Tracing

The `LearnerState` class in [`skills/learn/state.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn/state.py) implements a lightweight BKT model that tracks mastery probability for each concept separately. This class manages persistence logic, saving session state and transcripts as JSON bundles in the `learning-artifacts/` directory.

### MCP Integration for Stateless LLM Calls

The **Model-Context-Protocol (MCP)** integration defined in [`skills/learn-mcp/SKILL.md`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn-mcp/SKILL.md) ensures the LLM remains stateless while the client maintains all conversational context. The `mcp_chat()` function in [`skills/learn-mcp/client.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn-mcp/client.py) standardizes communication patterns, allowing the tutor loop to swap between different language models without modifying core logic.

### Artifact Persistence Layer

Session continuity relies on the `learning-artifacts/` directory structure, which stores serialized `LearnerState` objects and interaction transcripts. The test suite in [`scripts/test_skill_artifact_bundles.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/scripts/test_skill_artifact_bundles.py) validates that the learn skill correctly serializes and deserializes these artifact bundles, ensuring learners can resume sessions accurately.

## Implementing the Tutor Loop in Python

The following implementation demonstrates the four core steps required to drive a single iteration of the main tutor loop session:

```python

# 1. Initialise learner state

from skills.learn.state import LearnerState

state = LearnerState(learner_id="demo")
state.load()                     # restores prior mastery if present

# 2. Build the system prompt (uses MCP-aware template)

from skills.learn_mcp.prompts import build_prompt

system_prompt = build_prompt(state, objective="Linear Regression")

# 3. Send to LLM via MCP client

from skills.learn_mcp.client import mcp_chat

response = mcp_chat(system_prompt)

# 4. Parse response & update mastery

from skills.learn.parser import parse_answer

answer, correct = parse_answer(response)
state.update(concept="linear_regression", correct=correct)
state.save()                     # persists updated mastery

```

For complete session management, the test harness in [`skills/learn/tests/test_main.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn/tests/test_main.py) demonstrates the full loop execution:

```python

# skills/learn/tests/test_main.py (excerpt)

def test_full_session():
    session = TutorSession(state=LearnerState("test"))
    for _ in range(5):               # loop until termination

        if session.run_step() is False:
            break
    assert session.state.mastery["linear_regression"] > 0.8

```

## Summary

- The **main tutor loop session** follows a strict five-phase cycle: Initialize, Prepare Prompt, Interact, Update State, and Terminate.
- **LearnerState** in [`skills/learn/state.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn/state.py) maintains Bayesian Knowledge Tracing models that persist to the `learning-artifacts/` directory.
- **MCP integration** via [`skills/learn-mcp/client.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn-mcp/client.py) enables stateless LLM usage while preserving conversational context on the client side.
- Termination logic checks mastery thresholds, step limits, or user exit commands before concluding sessions.

## Frequently Asked Questions

### What is the role of the LearnerState class in the tutor loop?

The `LearnerState` class defined in [`skills/learn/state.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn/state.py) serves as the central data structure for tracking learner mastery. It implements Bayesian Knowledge Tracing to maintain `p_learn` probabilities for each concept, handles serialization to the `learning-artifacts/` directory via `save()` and `load()` methods, and provides the `update()` interface for modifying mastery based on interaction outcomes.

### How does the learn skill use the Model Context Protocol?

The learn skill uses the Model Context Protocol (MCP) to decouple LLM state management from the tutoring logic. As implemented in [`skills/learn-mcp/client.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/skills/learn-mcp/client.py), the `mcp_chat()` function sends constructed prompts to the LLM while the client side—specifically the `LearnerState`—retains all session context. This architecture allows the system to work with stateless language models while maintaining continuity across multi-turn tutoring conversations.

### Where are session artifacts and learner progress stored?

Session artifacts, including serialized `LearnerState` objects and interaction transcripts, are stored as JSON files in the `learning-artifacts/` directory at the repository root. The persistence mechanism is validated by [`scripts/test_skill_artifact_bundles.py`](https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/scripts/test_skill_artifact_bundles.py), which ensures that mastery vectors and conversation history correctly save and reload between sessions.

### How does the tutor loop determine when to end a session?

The loop evaluates termination criteria at the end of each cycle, checking whether the learner has achieved the target mastery threshold (typically `p_learn > 0.8` for relevant concepts), exceeded the maximum allowed interaction steps, or explicitly requested to exit. If any condition is met, the session concludes with a progress summary; otherwise, the cycle returns to the Prepare Prompt phase.