# Architecture & Design (Extended)

**blender-ai-mcp** enables precise, deterministic control of Blender by AI (LLM/MCP).
Instead of executing raw Python code generated by models (which is error-prone), the project provides a stable toolset via the Model Context Protocol.

This document contains detailed architectural decisions and the initial MVP specification.

---

## 📌 Introduction

**blender-ai-mcp** aims to solve the problem of "hallucinated code" when using LLMs with Blender. Instead of asking the AI to write `bpy` scripts, we provide a safe, high-level API.

The system allows AI to create:
- Low-poly models
- Technical models (devices, gadgets)
- Medical visualization primitives
- Game assets and scenery

---

## 🎯 Project Goals

- **Stability:** Deterministic 3D modeling driven by AI.
- **Safety:** Predictable API without Blender context errors (incorrect context is handled internally).
- **Scalability:** "Tool per logical task" approach instead of "Tool per function".
- **Maintainability:** Clean Architecture allows easy extension.

---

## 🧱 System Architecture

```
+------------------+        +---------------------+         +---------------------+
|     AI Model     | -----> |     MCP Server      | <-----> |   Blender Add-on    |
| (ChatGPT / LLM)  |        | (Python Fast-MCP)   |   RPC   | (bpy + RPC wrapper) |
+------------------+        +---------------------+         +---------------------+

                            Clean Architecture Layers
                -------------------------------------------
                Domain | Application | Adapters | Infra
```

### Runtime Responsibility Split

Beyond the Clean Architecture layers, the runtime product is divided into four responsibility layers:

- **FastMCP platform layer**: public MCP surface, discovery, visibility, prompts, elicitation, background-task UX, and future 3.x client-surface shaping.
- **Semantic layer (LaBSE / vector retrieval)**: workflow matching, multilingual generalization, learned parameter reuse.
- **Router policy layer**: deterministic correction, guardrails, adaptation, override policy, and execution safety.
- **Inspection / assertion layer**: the source of truth for current Blender state and future correctness checks.

This split is intentional:

- FastMCP should not be the semantic engine.
- LaBSE should not be the truth engine.
- Router should not be the primary discovery/catalog-shaping engine.
- Inspection must remain the final authority on actual Blender state.

See [_docs/_ROUTER/RESPONSIBILITY_BOUNDARIES.md](_docs/_ROUTER/RESPONSIBILITY_BOUNDARIES.md).
See [_docs/_MCP_SERVER/TOOL_LAYERING_POLICY.md](_docs/_MCP_SERVER/TOOL_LAYERING_POLICY.md) for the canonical product policy on layered tools, small public surfaces, hidden atomic tools, and `set_goal`-first orchestration.

### 1. MCP Server (Client Side)
A Python application that exposes tools to the AI model and acts as a client for the Blender Addon.
- **Domain**: Defines interfaces (`IModelingTool`) and models (`RpcRequest`).
- **Application**: Implements tool logic (`ModelingToolHandler`) using dependency injection.
- **Adapters**: Implements `RpcClient` (sockets) and `FastMCP` endpoints.
- **Infrastructure**: DI Container and Configuration.

Current state:
- The runtime now boots through an explicit FastMCP 3.x factory path with reusable provider groups and a deterministic transform pipeline scaffold.

Strategic direction:
- Move toward FastMCP 3.x platform capabilities for discovery, visibility, versioned surfaces, prompts, and richer client interaction patterns.

### FastMCP 3.x Composition Model

The MCP platform layer now has four explicit composition seams:

- **Provider groups**: reusable `core_tools`, `router_tools`, `workflow_tools`, and `internal_tools` provider builders
- **Surface profiles**: `legacy-flat`, `llm-guided`, `internal-debug`, `code-mode-pilot`
- **Platform manifest**: one minimal capability manifest outside router metadata
- **Transform pipeline**: one ordered scaffold for versioning, naming, prompt bridging, visibility, and discovery

This is important because the repo is no longer just “one FastMCP singleton + decorators”.
It is now moving toward:

- one composition root
- multiple public surfaces
- future version coexistence
- future search- and visibility-driven shaping

Area modules now expose plain tool callables plus explicit `register_*_tools(...)`
seams. Runtime composition happens through provider builders, not through
module-import side effects.

See [_docs/_MCP_SERVER/fastmcp_3x_composition.md](_docs/_MCP_SERVER/fastmcp_3x_composition.md).

### 2. Blender Addon (Server Side)
A plugin running inside Blender's Python environment (`bpy`).
- **Infrastructure**: Threaded TCP Server (`rpc_server.py`) that safely schedules tasks on the main thread.
- **Application**: Handlers (`SceneHandler`, `ModelingHandler`) that execute actual `bpy` operations.

---

## 🔄 Data Flow

```
AI -> MCP Server (Adapter) -> Application Handler -> RPC Client (Adapter)
      -> JSON-RPC over TCP ->
Blender Addon (Infrastructure) -> Application Handler -> bpy API -> Result
```

**Example Request:**
```json
{
  "tool": "create_primitive",
  "args": { "primitive_type": "Cube", "size": 2.0 }
}
```

---

## 🧠 "Stable Blender Tools" Design Philosophy

### ❌ Bad Practice: 1 Tool = 1 Blender API Function
Blender has over 1200 operators. Exposing them directly confuses the AI and leads to context errors.

### ✔ Good Practice: 1 Tool = 1 Logical Modeling Task
We group operations into high-level, robust tools.

**Examples:**
- **Bad:** `mesh.primitive_cube_add`, `transform.translate`
- **Good:** `create_primitive(type="Cube")`, `transform_object(name="Cube")`

**Every Tool Must:**
- Manage mode (Object/Edit) automatically.
- Manage selection state.
- Validate arguments.
- Return descriptive JSON/Text results.
- Handle Blender context exceptions gracefully.

---

## 🧩 Tool Categories

### 1) Scene Tools
- `list_objects`: Get scene content.
- `delete_object`: Remove specific items.
- `clean_scene`: Factory reset the scene.

### 2) Modeling Tools
- `create_primitive`: Cube, Sphere, Cylinder, etc.
- `transform_object`: Move, Rotate, Scale.
- `add_modifier`: Subsurf, Bevel, Boolean.

### 3) Mesh Editing Tools (Planned)
- `mesh.enter_edit`, `mesh.exit_edit`
- `mesh.extrude`, `mesh.inset`, `mesh.bevel`
- `mesh.clean_topology`

### 4) UV Tools (Planned)
- `uv.smart_unwrap`, `uv.project_from_view`

### 5) Materials (Planned)
- `material.create`, `material.assign`

### 6) Export Tools (Planned)
- `export.glb`, `export.fbx`

---

## 🏗 Best Practices & Standards

- **Clean Architecture**: Strict separation of concerns. Domain never depends on Frameworks.
- **Dependency Injection**: All dependencies are injected via providers (`di.py`).
- **Thread Safety**: The Addon uses `bpy.app.timers` to ensure thread safety when handling RPC requests.
- **No "Raw Code"**: The AI calls tools, it never executes arbitrary Python scripts.
- **Semantic vs Truth Separation**: Semantic retrieval helps decide likely intent; inspection tools determine actual scene truth.
- **Deterministic Safety First**: Router corrections should prefer deterministic fixes and explicit policy over speculative behavior.

---

## 📡 RPC Protocol

**Request:**
```json
{
  "request_id": "uuid-v4",
  "cmd": "modeling.create_primitive",
  "args": { "primitive_type": "Cube" }
}
```

**Response:**
```json
{
  "request_id": "uuid-v4",
  "status": "ok",
  "result": { "name": "Cube", "type": "MESH" }
}
```

---

# 🗺 Roadmap

- [x] Core RPC
- [x] Scene Tools
- [x] Modeling Tools (Primitives, Transforms)
- [ ] Mesh Editing (Edit Mode)
- [ ] Materials
- [ ] Import/Export
- [ ] Auto-follow-up tool fixes
