Generated by /repo-architecture skill v2.0.0

Transcript Correction MCP Architecture

Accent-aware post-correction server for Whisper ASR transcripts. Combines a phonetic knowledge base of known accent mishearings, TF-IDF / Qdrant RAG retrieval of previously verified corrections, and a multi-LLM fallback chain (6 providers) to fix systematic misrecognitions in accented English speech. Initially built for Chilean and Indian English accents.

Exposes corrections as both a REST API (/api/*) and an MCP tool server over Streamable HTTP (/mcp), allowing Claude Code and other MCP clients to correct transcripts inline during conversations.

Workflow: Raw Whisper transcript → Phonetic KB deterministic fixes → RAG few-shot example retrieval → LLM correction with accent context → Markdown diff output → Human review → Accept pairs into RAG store (feedback loop).
MCP Tools
6
REST Endpoints
6
LLM Providers
6
Python Modules
7
Port
8000
Runtime
Python 3.12

2. Runtime Architecture

Diagram A: Runtime Architecture

MCP / stdio HTTP pipeline lookup retrieve persist generate fallback Claude Code MCP client / Streamable HTTP AI-powered correction REST Client curl / n8n / Browser API integration FastAPI + FastMCP Server Python / uvicorn / :8000 6 MCP tools + 6 REST endpoints CorrectionEngine KB lookup + RAG retrieval + LLM merge Chunk-based pipeline (15 segments/chunk) Phonetic KB JSON / per-speaker profiles Deterministic accent fixes RAG Store JSON + TF-IDF / Qdrant Few-shot correction pairs File System /data volume transcripts / corrected / reviewed Agent CLI Proxies Qwen / Claude / Codex / Gemini REST /chat (ports 3300-3303) Ollama GPU rod-ml RTX 4090 / :11434 qwen2.5:7b Ollama CPU rod-server GTX 1650 / :11434 llama3.2:3b fallback Legend Primary path Direct call Fallback

Request Flow

  1. Client sends text or file path via MCP tool call (/mcp) or REST POST (/api/correct)
  2. Parser extracts timestamped segments from Whisper output format ([00:15.32 --> 00:15.38] text)
  3. Phonetic KB applies deterministic fixes for known accent mishearings (single-candidate substitutions)
  4. RAG Store retrieves the 3 most similar previously-verified correction pairs via TF-IDF cosine similarity
  5. LLM Chain sends the segments + speaker profile + RAG examples to the first available provider (6-provider fallback)
  6. Engine merges LLM output with KB fixes (KB is authoritative), flags uncertain corrections
  7. Output is a markdown diff table with columns: Timestamp, Original, Corrected, Flag
  8. Accept flow: human reviews diff, calls transcript_accept to extract verified pairs back into the RAG store

3. Correction Pipeline

Diagram B: Per-Segment Correction Flow

flowchart TD A[Input Segment] --> B{Hallucination?} B -- Yes --> C["[UNINTELLIGIBLE]"] B -- No --> D[Phonetic KB Lookup] D --> E{Single candidate?} E -- Yes --> F[Apply deterministic fix] E -- No / None --> G[Keep original] F --> H[Collect for LLM batch] G --> H H --> I[TF-IDF RAG Retrieval] I --> J[Build prompt with speaker profile + RAG examples] J --> K[LLM Chain Generate] K --> L{LLM succeeded?} L -- Yes --> M[Merge LLM output with KB fixes] L -- No --> N["Flag: llm_unavailable"] M --> O{Contains UNCERTAIN?} O -- Yes --> P["Flag: uncertain"] O -- No --> Q[Final corrected text] P --> Q N --> Q C --> Q

Correction Priority

PrioritySourceBehavior
1 (highest)Hallucination detectionKnown hallucination markers immediately produce [UNINTELLIGIBLE]
2Phonetic KBDeterministic single-candidate substitutions are applied first and preserved through LLM merge
3LLM correctionContext-aware correction using speaker profile, domain vocabulary, and RAG examples
4 (lowest)Original textIf no correction is confident, the original ASR text is preserved

5. Public Interfaces

MCP Tools (Streamable HTTP at /mcp)

ToolParametersRead-OnlyDescription
transcript_correct text, file_path, speaker, model No Correct accent-related ASR errors in a transcript. Provide raw text or a file path relative to transcripts/. Writes corrected output to corrected/ when using file mode.
transcript_correct_batch speaker, model No Batch-correct all uncorrected transcript files in the transcripts/ directory. Returns list of corrected and failed files.
transcript_accept file_path No Accept a reviewed correction file: extract correction pairs into the RAG store and move file to reviewed/.
transcript_stats (none) Yes Return statistics about the correction store (total pairs, breakdown by speaker).
transcript_list_uncorrected (none) Yes List transcript files that have not yet been corrected.
transcript_health (none) Yes Check server health: per-provider LLM chain status and store size.

REST API Endpoints

MethodPathDescription
GET/healthServer health check (LLM chain status, store pair count)
POST/api/correctCorrect a single transcript segment. Body: {"text", "speaker", "model"}
POST/api/correct-batchBatch-correct all uncorrected files. Body: {"speaker", "model"}
POST/api/acceptAccept a corrected file into the RAG store. Body: {"file_path"}
GET/api/statsCorrection store statistics
GET/api/uncorrectedList pending uncorrected transcript files

MCP Client Configuration

{
  "transcript-correction": {
    "type": "streamable-http",
    "url": "http://transcript-correction.home/mcp"
  }
}

6. Repository Structure

_transcript-correction-mcp/
  server.py                          # FastAPI + FastMCP dual-mode entry point (uvicorn)
  requirements.txt                   # Python dependencies (7 packages)
  Dockerfile                         # Python 3.12-slim, port 8000
  docker-compose.yml                 # Single service on hosting_web network
  README.md                          # Usage docs and troubleshooting
  correction/                        # Core correction pipeline package
    __init__.py                      # Package marker
    engine.py                        # CorrectionEngine: orchestrates KB + RAG + LLM
    llm_chain.py                     # LLMChain: 6-provider fallback (proxies + Ollama)
    rag_store.py                     # CorrectionStore: TF-IDF + Qdrant RAG retrieval
    parser.py                        # Whisper transcript segment parser
    phonetic_kb.py                   # PhoneticKB: speaker profiles + accent substitutions
    ollama_client.py                 # Legacy Ollama client (superseded by llm_chain.py)
    phonetic_kb.json                 # Knowledge base data (speakers, substitutions)
    correction_store.json            # Correction pair storage (grows via accept flow)
    prompts/
      correction.txt                 # LLM system prompt template
  defaults/                          # First-run seed data (copied to /data if missing)
    correction/
      phonetic_kb.json
      correction_store.json
      prompts/
        correction.txt
  docs/
    ARCHITECTURE.html                # Previous architecture document

Component Classification

ComponentClassificationRole
server.pyPrimaryApplication entry point, MCP tool definitions, REST endpoints, app factory
correction/engine.pyPrimaryCore pipeline orchestrator: chunk-based correction with KB/RAG/LLM merge
correction/llm_chain.pyPrimaryMulti-LLM fallback chain with AgentProxy and Ollama providers
correction/rag_store.pySecondaryTF-IDF retrieval of correction pairs with optional Qdrant vector fallback
correction/phonetic_kb.pySecondarySpeaker-specific accent profile and deterministic substitution rules
correction/parser.pyAuxiliaryWhisper timestamp format parser ([start --> end] text)
correction/ollama_client.pyLegacySuperseded by OllamaProvider in llm_chain.py

7. Deployment & Operations

Docker Container

PropertyValue
ImageCustom build from python:3.12-slim
Container Nametranscript-correction-mcp
Port8000 (internal only, no host mapping)
Networkhosting_web (shared Docker bridge)
Restart Policyunless-stopped
Volumetranscript_correction_data:/data
Traefik Labelstraefik.enable=false (routed via dynamic.yml file provider)
HealthcheckGET http://localhost:8000/health every 30s, 15s timeout, 3 retries

Environment Variables

VariableDefaultDescription
DATA_DIR/dataPersistent data directory (transcripts, corrections, KB)
DEFAULTS_DIR/app/defaultsSeed data for first-run initialization
DEFAULT_MODELqwen2.5:7bDefault LLM model name
DEFAULT_SPEAKERrod_chileanDefault speaker accent profile
LLM_CHAINqwen,claude,codex,gemini,ollama_gpu,ollamaComma-separated provider fallback order
QWEN_PROXY_URLhttp://172.17.0.1:3301Qwen CLI proxy endpoint
CLAUDE_PROXY_URLhttp://172.17.0.1:3300Claude CLI proxy endpoint
CODEX_PROXY_URLhttp://172.17.0.1:3303Codex CLI proxy endpoint
GEMINI_PROXY_URLhttp://172.17.0.1:3302Gemini CLI proxy endpoint
OLLAMA_GPU_URLhttp://10.0.1.3:11434Ollama with RTX 4090 on rod-ml
OLLAMA_URLhttp://ollama:11434Ollama CPU fallback (GTX 1650 on rod-server)
OLLAMA_FALLBACK_MODELllama3.2:3bSmall model for CPU Ollama fallback
QDRANT_URLhttp://qdrant:6333Qdrant vector DB for RAG (optional)

Operations Commands

# Deploy / rebuild
cd /home/rod/_rod/_transcript-correction-mcp
docker compose up -d --build

# View logs
docker compose logs -f transcript-correction-mcp

# Health check
curl -s http://localhost:8000/health | python3 -m json.tool

# Stop
docker compose down

Data Directory Layout (/data volume)

/data/
  transcripts/          # Input: raw Whisper transcript files
  corrected/            # Output: markdown diff tables (pending review)
  reviewed/             # Archive: accepted corrections (moved from corrected/)
  correction/
    phonetic_kb.json    # Speaker profiles and accent substitution rules
    correction_store.json  # RAG store: verified correction pairs (grows over time)
    prompts/
      correction.txt    # LLM system prompt template

8. Dependencies

Python Packages (requirements.txt)

PackageVersionPurpose
fastapi>=0.110.0REST API framework and ASGI application
uvicorn[standard]>=0.27.0ASGI server (production runner)
mcp[cli]>=1.0.0MCP SDK with FastMCP for Streamable HTTP transport
requests>=2.31.0HTTP client for LLM provider calls
scikit-learn>=1.3.0TF-IDF vectorizer and cosine similarity for RAG retrieval
pydantic>=2.0.0Request/response validation models
qdrant-client>=1.7.0Optional Qdrant vector DB client for enhanced RAG

External Services

ServiceLocationRequiredRole
Qwen CLI Proxy172.17.0.1:3301OptionalPrimary LLM provider (agent proxy pattern)
Claude CLI Proxy172.17.0.1:3300OptionalSecond LLM fallback
Codex CLI Proxy172.17.0.1:3303OptionalThird LLM fallback
Gemini CLI Proxy172.17.0.1:3302OptionalFourth LLM fallback
Ollama GPU (rod-ml)10.0.1.3:11434OptionalFifth fallback (RTX 4090, qwen2.5:7b)
Ollama CPU (rod-server)ollama:11434OptionalLast-resort fallback (GTX 1650, llama3.2:3b)
Qdrantqdrant:6333OptionalVector DB for enhanced RAG (falls back to TF-IDF)
Traefik10.0.1.6:443RequiredReverse proxy and TLS termination
Degradation model: The server starts and serves requests even when all LLM providers are down. Phonetic KB corrections still apply deterministically. RAG retrieval still works via TF-IDF. Only the LLM-enhanced correction step is skipped (flagged as llm_unavailable). At least one LLM provider must be reachable for full correction quality.

9. Constraints & Risks

CategoryItemSeverityDetails
Availability LLM provider dependency Medium All 6 LLM providers are external (CLI proxies on host, Ollama on rod-ml and rod-server). If all are down, corrections are KB-only (reduced quality). Agent CLI proxies require WSL to be running on rod-ml.
Performance TF-IDF recomputation Medium TF-IDF matrix is recomputed on every retrieval call (no caching). Will degrade as the correction store grows past thousands of pairs.
Storage JSON persistence Low Correction store and phonetic KB are stored as flat JSON files. Adequate for current scale but not suitable for concurrent writes or very large stores.
Scope Two speaker profiles Low Currently supports rod_chilean and nikhil_indian speaker profiles. Adding new accents requires manual KB entries.
Legacy ollama_client.py Low Legacy Ollama client module exists alongside llm_chain.py. Not imported by any current code but should be removed.