AdarshRajDS Cursor commited on
Commit
e418df7
·
1 Parent(s): c649336

Add thesis system design and MCP architecture document.

Browse files

Documents the project's evolution from initial RAG to the final dual-mode architecture with true MCP stdio integration and Mermaid diagrams for thesis figures.

Co-authored-by: Cursor <cursoragent@cursor.com>

Files changed (1) hide show
  1. docs/THESIS_SYSTEM_DESIGN_AND_MCP.md +756 -0
docs/THESIS_SYSTEM_DESIGN_AND_MCP.md ADDED
@@ -0,0 +1,756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HFU Multimodal Anatomy Chatbot — System Design, Evolution, and MCP Architecture
2
+
3
+ **Document type:** Thesis technical design record
4
+ **Scope:** Planning rationale, failed/iterative approaches, final architecture, and Model Context Protocol (MCP) integration
5
+ **Repository:** `ThesisBackend` (FastAPI + Next.js + `anatomy_mcp/`)
6
+
7
+ ---
8
+
9
+ ## 1. Executive summary
10
+
11
+ This project delivers a **multimodal anatomy learning assistant** with two deliberately separated capabilities:
12
+
13
+ | Mode | User intent | Knowledge source | Output |
14
+ |------|-------------|------------------|--------|
15
+ | **RAG Chatbot** | Answer textbook questions from uploaded PDFs | Chroma + BM25 + optional CLIP figure index | Grounded text, ≤3 citations, optional figures |
16
+ | **MCP 3D Anatomy** | Export and inspect a named body structure | Z-Anatomy `Startup.blend` + geometry-proven catalog | GLB + annotation JSON + Three.js viewer |
17
+
18
+ The thesis contribution is not “one model that does everything,” but a **dual-pipeline architecture** where document grounding and 3D geometry export remain **evaluated independently**. The final 3D path implements the **official Model Context Protocol** (`stdio` transport, `ClientSession.call_tool`, FastMCP tool server) rather than ad-hoc Python function calls or prompt-only LLM hallucination.
19
+
20
+ ---
21
+
22
+ ## 2. Original research goals
23
+
24
+ When the project started, the goals were:
25
+
26
+ 1. **Grounded Q&A** — Students ask anatomy questions; answers must cite uploaded course PDFs, not unconstrained LLM knowledge.
27
+ 2. **Multimodal support** — Textbook figures (diagrams, histology, radiology stills) should appear when relevant, not only text chunks.
28
+ 3. **3D visualization** — When a structure is named, the system should produce inspectable 3D geometry with labels, not a static screenshot alone.
29
+ 4. **Reproducible evaluation** — RAG quality (citation accuracy, abstention) and 3D export success (GLB URL, viewer load) must be measurable separately.
30
+ 5. **Local-first deployment** — Run on a Windows developer machine: LM Studio, Blender 5.x, Z-Anatomy, optional MinIO.
31
+
32
+ These goals drove every architectural decision below.
33
+
34
+ ---
35
+
36
+ ## 3. Initial approach (v0) and its flaws
37
+
38
+ ### 3.1 What we built first
39
+
40
+ The first iteration was a **monolithic FastAPI + single LLM** stack:
41
+
42
+ ```
43
+ User question → Chroma similarity search → top-k chunks → LLM prompt → answer
44
+ ```
45
+
46
+ Supporting pieces:
47
+
48
+ - PDF upload → text chunking → MiniLM embeddings → Chroma persist directory
49
+ - Optional local `/outputs` folder for extracted images
50
+ - A separate experimental path: **prompt Blender to procedurally generate geometry** (`src/mcp/blender_generator.py`, `BlenderMCP.generate_3d_brain`)
51
+
52
+ ### 3.2 Flaws discovered in practice
53
+
54
+ | Flaw | Symptom | Root cause |
55
+ |------|---------|------------|
56
+ | **Weak retrieval** | Correct answer in PDF but wrong passage retrieved | Dense-only search; no BM25 for exact terms (e.g. “mitral valve”, “NMJ”) |
57
+ | **Citation sprawl** | 10+ reference cards; duplicates from same page | No deduplication, no max-source cap, no evidence grading |
58
+ | **Ungrounded synthesis** | Plausible anatomy not in corpus | LLM answered from parametric knowledge when retrieval was empty |
59
+ | **Figure blindness** | Questions about labeled diagrams missed images | Text-only index; figures stored but not retrieved cross-modally |
60
+ | **Fragile image URLs** | Broken images after restart or HF deploy | Local paths only; no object storage abstraction |
61
+ | **Fake 3D success** | UI showed “Exported liver” with no GLB | LLM text claimed export; no tool verification |
62
+ | **Wrong 3D source** | Procedural “brain” mesh unrelated to Z-Anatomy | `blender_generator.py` creates synthetic geometry, not curriculum-accurate labels |
63
+ | **Name-only matching** | “kidney” export failed or picked wrong collection | Raw label index lists scene names, not exportable geometry |
64
+ | **Parallel Blender corruption** | Random export failures on Windows | Multiple Blender subprocesses writing concurrently |
65
+ | **Coupled evaluation** | Could not tell if RAG or 3D failed | Single chat endpoint mixed document answers and export URLs |
66
+
67
+ These flaws motivated the phased redesign documented in Sections 4–7.
68
+
69
+ ---
70
+
71
+ ## 4. Approaches we tried (chronological evolution)
72
+
73
+ ### 4.1 Overview timeline
74
+
75
+ ```mermaid
76
+ timeline
77
+ title Architecture evolution
78
+ section Retrieval
79
+ v0 Dense Chroma only : Weak on exact terms
80
+ v1 Hybrid BM25 + dense + RRF : Better keyword + semantic balance
81
+ v2 Evidence grading + max 3 sources : Thesis-grade grounding
82
+ section Multimodal
83
+ v0 Text chunks only : Missed figures
84
+ v1 CLIP multimodal Chroma : Figure retrieval added
85
+ v2 PDF pipeline + MinIO/Supabase : Durable public image URLs
86
+ section 3D visualization
87
+ v0 Procedural Blender script : Not Z-Anatomy accurate
88
+ v1 Remote render worker (asset PNG) : RAG sidebar preview only
89
+ v2 Direct Python anatomy calls : Worked but not MCP-standard
90
+ v3 True MCP stdio + catalog fast path : Final production design
91
+ section LLM
92
+ v0 Single local model : LM Studio only
93
+ v1 Split providers : Groq for RAG speed, LM Studio as MCP tool host
94
+ ```
95
+
96
+ ---
97
+
98
+ ### 4.2 Approach A — Dense vector RAG only
99
+
100
+ **Design:** `VectorStoreFactory` + `similarity_search(k=...)`.
101
+
102
+ **Why we tried it:** Fastest path to a demo; LangChain/Chroma defaults.
103
+
104
+ **Result:** Failed on anatomy terminology where embedding similarity diverges from exact nomenclature (Latin names, hyphenation, “left vs right”).
105
+
106
+ **Replacement:** `HybridRetriever` in `src/retrieval/hybrid_retriever.py` — BM25 + dense + phrase matching fused with **Reciprocal Rank Fusion (RRF)**.
107
+
108
+ ---
109
+
110
+ ### 4.3 Approach B — Multimodal RAG (CLIP + text)
111
+
112
+ **Design:** `MultimodalRAG` combines:
113
+
114
+ - Text corpus (MiniLM Chroma, same as ingestion)
115
+ - Multimodal retriever (`MultimodalRetriever` + `CLIPEmbedding`)
116
+ - Up to 3 unique text passages (`_MAX_UNIQUE_TEXT_PASSAGES = 3`)
117
+
118
+ **Why we tried it:** Anatomy learning is inherently visual; students ask about figures explicitly.
119
+
120
+ **Improvements over A:**
121
+
122
+ - Retrieves figure metadata and serves images from `/outputs` or presigned storage
123
+ - Dedupes by PDF stem + page + text fingerprint
124
+
125
+ **Remaining gap:** Still no 3D export; images are 2D textbook figures only.
126
+
127
+ ---
128
+
129
+ ### 4.4 Approach C — Strict grounding & thesis evaluation pipeline
130
+
131
+ **Design:** `src/multimodal/thesis_rag_eval.py` — parallel experiment track:
132
+
133
+ - **Baseline** — LLM without retrieval (measures hallucination rate)
134
+ - **Strict RAG** — answer only from numbered passages
135
+ - **Coherent synthesis** — stricter prompt with citation IDs
136
+ - **Blind judge** — compares baseline vs strict
137
+
138
+ **Why we tried it:** Quantify *how much* retrieval helps for thesis evaluation (`POST /rag/experiment/ask`).
139
+
140
+ **Lesson:** Production `POST /rag/ask` and experiment pipeline stay separate so tuning does not break live UI.
141
+
142
+ ---
143
+
144
+ ### 4.5 Approach D — Procedural Blender generation (`BlenderMCP`)
145
+
146
+ **Design:** `src/mcp/blender_mcp.py` + `blender_generator.py`
147
+
148
+ ```
149
+ LLM prompt → blender --background --python blender_generator.py → synthetic GLB
150
+ ```
151
+
152
+ **Why we tried it:** Quick 3D “something” without licensing a full anatomy asset library.
153
+
154
+ **Flaws:**
155
+
156
+ - Geometry is **not** Z-Anatomy; labels do not match course material
157
+ - No annotation JSON sidecar
158
+ - `POST /blender/generate-brain-3d` is a research stub, not curriculum export
159
+
160
+ **Status:** Kept for optional brain demo; **not** the MCP catalog path.
161
+
162
+ ---
163
+
164
+ ### 4.6 Approach E — Remote Blender render worker (RAG adjunct)
165
+
166
+ **Design:** `app/services/blender_service.py` → `render_related_anatomy()`
167
+
168
+ ```
169
+ POST /rag/ask → detect keyword (brain, heart, spine…) → POST {BLENDER_SERVER_URL}/render-asset → PNG URL
170
+ ```
171
+
172
+ **Why we tried it:** Attach a **related 3D preview** to RAG answers without blocking on full GLB export latency.
173
+
174
+ **Characteristics:**
175
+
176
+ - Fixed asset map (`ASSET_MAPPING`: brain, heart, hand, lung, spine)
177
+ - Worker uploads to object storage; backend stores **no local render files**
178
+ - Returns `render_3d_url` in RAG response (optional, best-effort)
179
+
180
+ **Flaws:**
181
+
182
+ - Only ~5 pre-authored assets; no arbitrary “left femur” from user query
183
+ - Docker `blender` service in `docker-compose.yml` is a **different** worker from Z-Anatomy MCP export
184
+ - Must not be confused with MCP panel exports in evaluation
185
+
186
+ **Status:** Optional RAG enhancement; orthogonal to MCP.
187
+
188
+ ---
189
+
190
+ ### 4.7 Approach F — Label index without exportable catalog
191
+
192
+ **Design:** Scan Z-Anatomy once → `z_anatomy_index.json` (all collection/object names in scene).
193
+
194
+ **Why we tried it:** First automated bridge from natural language to Blender object names.
195
+
196
+ **Flaws:**
197
+
198
+ - Index proves **name exists**, not that mesh is exportable
199
+ - Broad queries (`kidney`, `iris`) hit ambiguous or empty collections
200
+ - Exports sometimes succeeded with **huge** selections (entire limb regions)
201
+
202
+ **Replacement:** `build_exportable_catalog.py` → `exportable_catalog.json` — entries validated by geometry probe in Blender.
203
+
204
+ ---
205
+
206
+ ### 4.8 Approach G — Direct in-process Python calls (pre-MCP)
207
+
208
+ **Design:** Import `anatomy_mcp/server.py` functions directly from FastAPI handlers.
209
+
210
+ **Why we tried it:** Fastest integration before MCP SDK maturity on Windows.
211
+
212
+ **Flaws:**
213
+
214
+ - Not interoperable with LM Studio, Claude Desktop, or MCP Inspector
215
+ - No standard tool discovery / schema contract
216
+ - LLM could not participate in multi-step tool loops using a portable protocol
217
+ - Harder to sandbox Blender side effects
218
+
219
+ **Replacement:** True MCP stdio server + `MCPBridge` client (Approach H).
220
+
221
+ ---
222
+
223
+ ### 4.9 Approach H — True MCP with dual execution paths (FINAL)
224
+
225
+ **Design:** See Section 6–7. This is the production 3D architecture.
226
+
227
+ ---
228
+
229
+ ### 4.10 Storage approaches tried
230
+
231
+ | Approach | Mechanism | When used | Flaw / fix |
232
+ |----------|-----------|-----------|------------|
233
+ | Local `outputs/` | FastAPI static mount | Earliest dev | URLs break on multi-replica / HF Spaces |
234
+ | MinIO | S3-compatible Docker (`docker-compose.yml`) | Local full stack | Requires Docker; good for dev |
235
+ | Supabase Storage | `STORAGE_PROVIDER=supabase` | Production / HF | Needs service role key; auto-selected when env set |
236
+
237
+ Image pipeline steps are observable via `GET /debug/storage` and upload response `pipeline` array.
238
+
239
+ ---
240
+
241
+ ### 4.11 LLM provider approaches
242
+
243
+ | Role | Initial | Final |
244
+ |------|---------|-------|
245
+ | RAG synthesis | LM Studio local | **Groq** (`llama-3.1-8b-instant`) for latency |
246
+ | MCP tool host | N/A | **LM Studio** OpenAI-compatible API at `:1234/v1` |
247
+ | Evidence grading / judge | Groq | Groq (thesis eval) |
248
+
249
+ **Rationale for split:** RAG needs fast repeated calls; MCP tool loop needs a model with reliable **function calling** locally without cloud cost for Blender waits.
250
+
251
+ ---
252
+
253
+ ## 5. Final architecture (what we reached)
254
+
255
+ ### 5.1 System context
256
+
257
+ ```mermaid
258
+ flowchart TB
259
+ subgraph User["User / Evaluator"]
260
+ U1[Browser]
261
+ end
262
+
263
+ subgraph Frontend["Next.js Frontend :3000"]
264
+ Chat[Main Chat UI]
265
+ Upload[Upload Panel]
266
+ MCPPanel[MCP 3D Panel + iframe viewer]
267
+ end
268
+
269
+ subgraph Backend["FastAPI Backend :8000"]
270
+ RAGRoute["/rag/ask"]
271
+ UploadRoute["/upload-pdf/"]
272
+ MCPRoute["/anatomy/ask"]
273
+ RAGSvc[rag_service]
274
+ RAGEngine[MultimodalRAG]
275
+ MCPChat[anatomy_mcp_chat]
276
+ MCPBridge[MCPBridge stdio client]
277
+ end
278
+
279
+ subgraph RAGData["Document knowledge"]
280
+ Chroma[(Chroma text index)]
281
+ BM25[(BM25 pickle)]
282
+ MMChroma[(Multimodal Chroma)]
283
+ MinIO[(MinIO / Supabase / local outputs)]
284
+ end
285
+
286
+ subgraph MCPData["3D anatomy knowledge"]
287
+ Catalog[(exportable_catalog.json)]
288
+ Blend[Z-Anatomy Startup.blend]
289
+ Exports[/anatomy-exports GLB + JSON/]
290
+ Viewer[/anatomy-viewer Three.js/]
291
+ end
292
+
293
+ subgraph External["External runtimes"]
294
+ Groq[Groq API — RAG LLM]
295
+ LMStudio[LM Studio — MCP host LLM]
296
+ Blender[Blender 5.x headless]
297
+ end
298
+
299
+ subgraph MCPServer["anatomy_mcp/server.py — stdio MCP"]
300
+ SearchTool[search_anatomy_catalog]
301
+ ExportPart[export_anatomy_part]
302
+ ExportPkg[export_anatomy_package]
303
+ end
304
+
305
+ U1 --> Chat & Upload & MCPPanel
306
+ Chat -->|POST question| RAGRoute
307
+ Upload -->|POST PDF| UploadRoute
308
+ MCPPanel -->|POST message| MCPRoute
309
+
310
+ RAGRoute --> RAGSvc --> RAGEngine
311
+ RAGEngine --> Chroma & BM25 & MMChroma
312
+ RAGEngine --> Groq
313
+ UploadRoute --> Chroma & MMChroma & MinIO
314
+ RAGEngine --> MinIO
315
+ RAGSvc -->|optional| RenderWorker[Remote render worker]
316
+
317
+ MCPRoute --> MCPChat --> MCPBridge
318
+ MCPChat -->|fast path or tool loop| LMStudio
319
+ MCPBridge <-->|stdio JSON-RPC| MCPServer
320
+ SearchTool --> Catalog
321
+ ExportPart & ExportPkg --> Blender
322
+ Blender --> Blend
323
+ ExportPart & ExportPkg --> Exports
324
+ MCPPanel -->|iframe src=viewer_url| Viewer
325
+ Viewer --> Exports
326
+ ```
327
+
328
+ ### 5.2 Separation of concerns (evaluation rule)
329
+
330
+ ```mermaid
331
+ flowchart LR
332
+ subgraph RAGPath["Mode A — RAG Chat"]
333
+ Q1[Textbook question]
334
+ A1[Grounded answer + PDF citations]
335
+ end
336
+
337
+ subgraph MCPPath["Mode B — MCP 3D"]
338
+ Q2[Structure name e.g. left femur]
339
+ A2[GLB + annotations + viewer]
340
+ end
341
+
342
+ Q1 -.->|must NOT| A2
343
+ Q2 -.->|must NOT| A1
344
+
345
+ style RAGPath fill:#e8f4fc,stroke:#2563eb
346
+ style MCPPath fill:#ecfdf5,stroke:#059669
347
+ ```
348
+
349
+ **Thesis rule:** Never score a RAG answer on GLB export success; never score an MCP export on PDF citation quality.
350
+
351
+ ---
352
+
353
+ ## 6. MCP deep dive — protocol, components, and guarantees
354
+
355
+ ### 6.1 What “proper MCP” means in this project
356
+
357
+ The implementation satisfies the MCP contract at three layers:
358
+
359
+ | Layer | Component | Responsibility |
360
+ |-------|-----------|----------------|
361
+ | **Tool server** | `anatomy_mcp/server.py` | FastMCP registers tools; runs Blender; returns structured JSON |
362
+ | **Transport** | `stdio` via `mcp.client.stdio` | Parent process spawns server; no HTTP port on MCP server |
363
+ | **Host orchestration** | `app/services/anatomy_mcp_chat.py` | LM Studio chooses tools; backend executes via `ClientSession.call_tool` |
364
+
365
+ **Non-MCP patterns explicitly rejected:**
366
+
367
+ - LLM printing `http://.../anatomy.glb` without calling a tool
368
+ - Direct Python import of export functions from FastAPI routes
369
+ - Hard-coded export in frontend
370
+
371
+ ### 6.2 MCP layer diagram
372
+
373
+ ```mermaid
374
+ flowchart TB
375
+ subgraph Presentation["Presentation layer"]
376
+ UI[AnatomyMcpPanel.js]
377
+ Viewer[Three.js viewer iframe]
378
+ end
379
+
380
+ subgraph API["FastAPI REST layer"]
381
+ Ask["POST /anatomy/ask"]
382
+ Health["GET /anatomy/health"]
383
+ Static["/anatomy-exports /anatomy-viewer"]
384
+ end
385
+
386
+ subgraph Orchestration["MCP host orchestration"]
387
+ Agent[run_lmstudio_mcp_agent]
388
+ FastPath[_try_catalog_fast_path]
389
+ ToolLoop[LM Studio tool loop max 6 rounds]
390
+ end
391
+
392
+ subgraph Client["MCP client — MCPBridge"]
393
+ Session[ClientSession]
394
+ ListTools[list_tools → OpenAI schema]
395
+ CallTool[call_tool]
396
+ StdioTransport[stdio_client]
397
+ end
398
+
399
+ subgraph Server["MCP server — FastMCP"]
400
+ T1[search_anatomy_catalog]
401
+ T2[export_anatomy_part]
402
+ T3[export_anatomy_package]
403
+ Lock[_BLENDER_EXPORT_LOCK]
404
+ Resolver[exportable_catalog resolver]
405
+ end
406
+
407
+ subgraph Execution["Execution layer"]
408
+ BlenderCLI[Blender subprocess]
409
+ ZAnatomy[Startup.blend]
410
+ Cache[exports/cache v4 schema]
411
+ end
412
+
413
+ UI --> Ask
414
+ Ask --> Agent
415
+ Agent --> FastPath
416
+ Agent --> ToolLoop
417
+ FastPath --> CallTool
418
+ ToolLoop --> ListTools
419
+ ToolLoop --> CallTool
420
+ CallTool --> StdioTransport --> Session
421
+ Session --> T1 & T2 & T3
422
+ T2 & T3 --> Lock --> BlenderCLI --> ZAnatomy
423
+ T2 & T3 --> Cache
424
+ Static --> Viewer
425
+ UI --> Viewer
426
+ ```
427
+
428
+ ### 6.3 MCP tool catalog
429
+
430
+ | Tool | Input | Output | When used |
431
+ |------|-------|--------|-----------|
432
+ | `search_anatomy_catalog` | `query`, `limit` | Ranked catalog entries, suggestions, ambiguity errors | Every export path starts here or equivalent resolution |
433
+ | `export_anatomy_part` | `part_query`, `include_preview` | `model_url`, `annotations_url`, `viewer_url`, metadata | Single structure (e.g. `Femur.l`, `Liver`) |
434
+ | `export_anatomy_package` | `part_query`, options | Study package with subparts for large regions | Brain, thalamus; fallback after part export timeout |
435
+
436
+ **Safety boundaries** (from `anatomy_mcp/README.md`):
437
+
438
+ - No arbitrary `.blend` paths from user input
439
+ - No arbitrary Python injection
440
+ - No full-scene export by default
441
+ - Serialized Blender lock — one export at a time on Windows
442
+
443
+ ### 6.4 Catalog resolution pipeline
444
+
445
+ ```mermaid
446
+ flowchart TD
447
+ Input[User message e.g. left femur]
448
+ Validate{Query valid?}
449
+ Vague{Vague query?}
450
+ Normalize[catalog_query_from_user_message]
451
+ Search[search_anatomy_catalog]
452
+ Match{Exact exportable match?}
453
+ Ambiguous{Multiple matches?}
454
+ Export[export_anatomy_part]
455
+ Package[export_anatomy_package]
456
+ Success[anatomy_export status ok]
457
+ Clarify[Clarification message]
458
+ Suggest[Return suggestion labels]
459
+
460
+ Input --> Validate
461
+ Validate -->|invalid chars / too long| Clarify
462
+ Validate --> Vague
463
+ Vague -->|show me the organ| Clarify
464
+ Vague --> Normalize --> Search
465
+ Search --> Match
466
+ Match -->|yes Femur.l| Export
467
+ Match -->|no| Ambiguous
468
+ Ambiguous -->|kidney| Suggest
469
+ Export -->|timeout| Package
470
+ Export --> Success
471
+ Package --> Success
472
+ ```
473
+
474
+ **Key data artifact:** `exportable_catalog.json` — only entries with proven mesh geometry. This replaced naive `z_anatomy_index.json` matching.
475
+
476
+ ### 6.5 MCP sequence — fast path (plain queries)
477
+
478
+ Used when input matches `looks_like_plain_anatomy_query` (≤80 chars, alphanumeric + space/dot/dash).
479
+
480
+ ```mermaid
481
+ sequenceDiagram
482
+ autonumber
483
+ actor User
484
+ participant UI as AnatomyMcpPanel
485
+ participant API as POST /anatomy/ask
486
+ participant Chat as anatomy_mcp_chat
487
+ participant Bridge as MCPBridge
488
+ participant Srv as anatomy_mcp/server.py
489
+ participant Cat as exportable_catalog.json
490
+ participant B as Blender
491
+ participant V as anatomy-viewer iframe
492
+
493
+ User->>UI: "left femur"
494
+ UI->>API: { message, language }
495
+ API->>Chat: run_lmstudio_mcp_agent()
496
+
497
+ Note over Chat: Fast path — no LM Studio round-trip
498
+
499
+ Chat->>Bridge: call_tool search_anatomy_catalog
500
+ Bridge->>Srv: MCP CallTool
501
+ Srv->>Cat: token + lateral resolution
502
+ Srv-->>Chat: Femur.l match
503
+
504
+ Chat->>Bridge: call_tool export_anatomy_part
505
+ Bridge->>Srv: MCP CallTool
506
+ Srv->>B: subprocess export_part.py
507
+ B-->>Srv: anatomy.glb + annotations.json
508
+ Srv-->>Chat: model_url, viewer_url
509
+
510
+ Chat->>Chat: structured_to_anatomy_export
511
+ Note over Chat: Fail if model_url missing — no fake success
512
+
513
+ Chat-->>API: answer + anatomy_export + mcp_tools_used
514
+ API-->>UI: JSON 200
515
+ UI->>V: iframe src = viewer_url
516
+ V-->>User: labeled 3D mesh
517
+ ```
518
+
519
+ **Why fast path exists:** Blender exports take 30–120s. Skipping LLM orchestration for `"Femur.l"`-style queries reduces failure modes and token cost.
520
+
521
+ ### 6.6 MCP sequence — LLM tool loop (complex queries)
522
+
523
+ ```mermaid
524
+ sequenceDiagram
525
+ autonumber
526
+ participant Chat as anatomy_mcp_chat
527
+ participant LM as LM Studio LLM
528
+ participant Bridge as MCPBridge
529
+ participant Srv as MCP server
530
+
531
+ Chat->>Bridge: get_openai_tools()
532
+ Bridge->>Srv: list_tools
533
+ Srv-->>Bridge: tool schemas
534
+ Bridge-->>Chat: OpenAI function definitions
535
+
536
+ loop Up to MAX_TOOL_ROUNDS = 6
537
+ Chat->>LM: messages + tools + tool_choice auto
538
+ LM-->>Chat: assistant message + tool_calls
539
+ alt tool_calls present
540
+ Chat->>Bridge: call_tool(name, args)
541
+ Bridge->>Srv: MCP CallTool
542
+ Srv-->>Bridge: structured JSON result
543
+ Bridge-->>Chat: compact_tool_result_for_llm
544
+ Chat->>Chat: append tool result to messages
545
+ else no tool_calls
546
+ Chat->>Chat: verify export or require tools
547
+ end
548
+ end
549
+
550
+ Chat->>Chat: structured_to_anatomy_export
551
+ alt model_url present
552
+ Chat-->>Chat: status ok + mcp_tools_used logged
553
+ else export error
554
+ Chat-->>Chat: status error — UI shows failure, no empty iframe
555
+ end
556
+ ```
557
+
558
+ **Host prompt constraints** (`build_mcp_system_prompt` in `app/i18n/locale.py`):
559
+
560
+ - Must call `export_anatomy_part` or `export_anatomy_package` before claiming success
561
+ - Must not echo raw package manifest URLs to user
562
+ - Must ask clarification on vague queries
563
+ - Retry package export after part export timeout
564
+
565
+ ### 6.7 How the final approach **ensures** MCP integrity
566
+
567
+ | Guarantee | Mechanism | Code reference |
568
+ |-----------|-----------|----------------|
569
+ | **Real tool discovery** | `session.list_tools()` → OpenAI schemas | `MCPBridge.get_openai_tools()` |
570
+ | **Real tool execution** | `session.call_tool(name, arguments)` | `MCPBridge.call_tool()` |
571
+ | **Stdio isolation** | Separate Python process for `server.py` | `StdioServerParameters` |
572
+ | **Structured tool results** | `structuredContent` + text fallback parsing | `extract_structured_from_tool_payload()` |
573
+ | **No hallucinated exports** | `structured_to_anatomy_export` returns `null` without `model_url` | `anatomy_mcp_client.py` |
574
+ | **UI honesty** | Frontend checks `anatomy_export.status === "ok"` before iframe | `AnatomyMcpPanel.js` |
575
+ | **Audit trail** | Response includes `mcp_tools_used`, `mcp_tool_steps` | `_agent_result()` |
576
+ | **URL rewriting** | Dev server `:8123` → public API base | `rewrite_local_urls()` |
577
+ | **Concurrency safety** | `threading.RLock` around Blender | `anatomy_mcp/server.py` |
578
+ | **Health probe** | `GET /anatomy/health` checks Blender, catalog, MCP import | `anatomy_mcp_health()` |
579
+
580
+ ```mermaid
581
+ flowchart TD
582
+ Claim[LLM says Exported liver]
583
+ Tools{mcp_tools_used includes export tool?}
584
+ URL{model_url HTTP 200?}
585
+ OK[Show viewer + GLB links]
586
+ Fail[Show error panel]
587
+
588
+ Claim --> Tools
589
+ Tools -->|no| Fail
590
+ Tools -->|yes| URL
591
+ URL -->|no| Fail
592
+ URL -->|yes| OK
593
+ ```
594
+
595
+ ---
596
+
597
+ ## 7. Final approach — what we implemented in the last iteration
598
+
599
+ ### 7.1 Backend wiring (`app/main.py`)
600
+
601
+ Routers and static mounts required for MCP UI:
602
+
603
+ - `app.include_router(anatomy_mcp.router)` → `/anatomy/*`
604
+ - `app.mount("/anatomy-exports", ...)` → GLB, packages, annotations
605
+ - `app.mount("/anatomy-viewer", ...)` → Three.js viewer assets
606
+
607
+ ### 7.2 Settings contract (`src/config/settings.py`)
608
+
609
+ Environment-driven configuration for MCP:
610
+
611
+ - `PUBLIC_API_BASE` — URL prefix for exported assets
612
+ - `BLENDER_BIN`, `Z_ANATOMY_BLEND` — passed into MCP server env
613
+ - `LLM_API_BASE` — LM Studio for tool host
614
+ - `ANATOMY_MCP_ENABLED` — feature gate
615
+
616
+ ### 7.3 Frontend MCP panel
617
+
618
+ `frontend/app/components/AnatomyMcpPanel.js`:
619
+
620
+ - Calls `POST /anatomy/ask` (not `/rag/ask`)
621
+ - Renders `AnatomyExportPanel` with viewer link, GLB download
622
+ - Salvage path parses URLs from verbose LLM dumps (legacy compatibility)
623
+ - i18n EN/DE strings for errors including “restart backend if 404”
624
+
625
+ ### 7.4 Caching & performance
626
+
627
+ - Export cache schema **v4** under `anatomy_mcp/exports/cache/`
628
+ - Repeated `Femur.l` queries hit cache → near-instant URLs
629
+ - Package exports for large structures avoid timeout on single-part mesh
630
+
631
+ ### 7.5 RAG path (unchanged responsibility)
632
+
633
+ `POST /rag/ask` still uses `MultimodalRAG` + optional `render_3d_url` from remote worker — **does not** invoke MCP tools by default. This preserves evaluation separation.
634
+
635
+ ---
636
+
637
+ ## 8. RAG pipeline reference (Mode A detail)
638
+
639
+ ```mermaid
640
+ sequenceDiagram
641
+ autonumber
642
+ actor User
643
+ participant UI as Next.js Chat
644
+ participant API as POST /rag/ask
645
+ participant RAG as MultimodalRAG
646
+ participant IDX as Chroma + BM25 + Hybrid
647
+ participant LLM as Groq
648
+
649
+ User->>UI: Question + optional PDF context
650
+ UI->>API: { question, allow_world_knowledge, language }
651
+ API->>RAG: ask()
652
+
653
+ RAG->>RAG: classify + typo correct + rewrite
654
+ RAG->>IDX: hybrid retrieve
655
+ RAG->>RAG: rerank + dedupe passages
656
+ RAG->>LLM: evidence grading A/B/C
657
+ RAG->>LLM: grounded synthesis
658
+ RAG->>RAG: normalize citations, max 3 sources
659
+ RAG-->>API: answer, sources, images, grounding
660
+ API-->>UI: AskResponse
661
+ ```
662
+
663
+ ---
664
+
665
+ ## 9. Comparison matrix (for thesis discussion section)
666
+
667
+ | Dimension | Initial v0 | Final system |
668
+ |-----------|------------|--------------|
669
+ | Retrieval | Dense only | Hybrid BM25 + dense + RRF + phrases |
670
+ | Grounding | Prompt-only | Evidence grading + abstention + max 3 sources |
671
+ | Figures | Ignored | CLIP multimodal index + storage URLs |
672
+ | 3D source | Procedural script | Z-Anatomy catalog + Blender export |
673
+ | 3D protocol | Direct Python / fake LLM text | MCP stdio + tool audit trail |
674
+ | LLM | Single local | Groq (RAG) + LM Studio (MCP host) |
675
+ | Storage | Local folder | MinIO / Supabase abstraction |
676
+ | Evaluation | Mixed | Separated RAG vs MCP metrics |
677
+ | Export correctness | Name in index | Geometry-proven catalog |
678
+ | Parallelism | Unsafe | Blender export lock |
679
+
680
+ ---
681
+
682
+ ## 10. Known limitations & future work
683
+
684
+ 1. **LM Studio dependency for complex MCP queries** — Fast path avoids it; natural-language disambiguation still needs tool-capable local model.
685
+ 2. **Windows-only Blender path** — Linux/Mac require different Blender binary paths.
686
+ 3. **Export latency** — Large packages (brain) may exceed user patience; cache mitigates repeat queries.
687
+ 4. **RAG render worker** — Only five asset keys; not a general anatomy renderer.
688
+ 5. **MCP + RAG fusion** — Deliberately not merged; future work could *link* citation text to MCP viewer via shared entity IDs without mixing retrieval corpora.
689
+
690
+ ---
691
+
692
+ ## 11. Verification checklist
693
+
694
+ ### RAG (Mode A)
695
+
696
+ ```powershell
697
+ curl -X POST http://127.0.0.1:8000/rag/ask `
698
+ -H "Content-Type: application/json" `
699
+ -d '{"question":"What is the function of the mitral valve?","allow_world_knowledge":false,"language":"en"}'
700
+ ```
701
+
702
+ Pass: answer cites PDF sources; no GLB URLs.
703
+
704
+ ### MCP (Mode B)
705
+
706
+ ```powershell
707
+ curl -X POST http://127.0.0.1:8000/anatomy/ask `
708
+ -H "Content-Type: application/json" `
709
+ -d '{"message":"left femur","language":"en"}'
710
+ ```
711
+
712
+ Pass: `anatomy_export.status == "ok"`, `mcp_tools_used` includes `export_anatomy_part`, viewer URL loads.
713
+
714
+ ### MCP health
715
+
716
+ ```powershell
717
+ Invoke-RestMethod http://127.0.0.1:8000/anatomy/health
718
+ ```
719
+
720
+ Pass: `ready: true`, `mcp_stdio_ok: true`, `blender_exists: true`, `exportable_catalog_exists: true`.
721
+
722
+ ---
723
+
724
+ ## 12. Key file index
725
+
726
+ | Path | Role |
727
+ |------|------|
728
+ | `app/main.py` | FastAPI entry, routers, static mounts |
729
+ | `app/services/rag_service.py` | RAG + optional render worker |
730
+ | `app/services/anatomy_mcp_chat.py` | MCP host agent (fast path + tool loop) |
731
+ | `app/services/anatomy_mcp_client.py` | MCPBridge stdio client |
732
+ | `app/services/anatomy_mcp_service.py` | Health checks, env configuration |
733
+ | `anatomy_mcp/server.py` | FastMCP tool server |
734
+ | `anatomy_mcp/label_index/exportable_catalog.json` | Geometry-validated catalog |
735
+ | `anatomy_mcp/viewer/` | Three.js annotation viewer |
736
+ | `src/multimodal/multimodal_rag_chain.py` | MultimodalRAG core |
737
+ | `src/retrieval/hybrid_retriever.py` | BM25 + dense hybrid |
738
+ | `frontend/app/components/AnatomyMcpPanel.js` | MCP UI |
739
+ | `docs/ARCHITECTURE_FOR_DIAGRAMS.md` | Diagram source pack |
740
+
741
+ ---
742
+
743
+ ## 13. Conclusion
744
+
745
+ The project evolved from a **single-path RAG demo** into a **dual-mode architecture** grounded in evaluation needs:
746
+
747
+ - **Documents** are handled by retrieval-augmented generation with strict citation limits.
748
+ - **Geometry** is handled by a **standards-based MCP toolchain** connecting an LLM host, a stdio tool server, Blender, and a web viewer.
749
+
750
+ The final MCP design is not “MCP-themed naming” — it implements discoverable tools, stdio transport, structured tool results, and verifiable export URLs. The **fast path** optimizes common classroom queries without bypassing MCP (`call_tool` is still used); the **LLM tool loop** handles ambiguous natural language while respecting the same server contract.
751
+
752
+ This document should be cited alongside `docs/ARCHITECTURE_FOR_DIAGRAMS.md` when generating thesis figures: use **blue** styling for RAG paths and **green** styling for MCP paths in all diagrams.
753
+
754
+ ---
755
+
756
+ *Generated from repository state and architecture records. Update when new approaches are tried or MCP tools change.*