Table of Contents


Course capstone for 105532-AI day 5: a microservice application combining MCP, RAG, LLM, LangChain, and a Streamlit dashboard, deployable with Docker Compose and plain Kubernetes manifests. Primary deliverable is documentation + runnable skeleton — students (with AI agents) fill in the logic.

Working directory: /home/cfreire/Documents/2026/105532-AI/PREP/day5/final_project (currently contains only url.md).

Confirmed decisions

DecisionChoice
DeliverableDocs + skeleton (runnable stubs with # TODO(student) markers; students fill logic)
LLMOllama container in the cluster, no API keys (day2/day4 consistency)
RAG corpusINE accidents indicator data turned into text chunks at ingestion (data-grounded, no static corpus)
MCPFastMCP with streamable-http transport + in-memory TTL cache (evolution of day5/ipma/ipma_mcp.py)
Services3 app services + Ollama: dashboard, ipma-mcp, accidents-rag-api, ollama (INE proxy merged into rag-api)
Deploymentdocker compose up primary path + plain K8s YAML for k3s/minikube (no Helm)
DashboardSingle Streamlit page with tabs: Acidentes / Meteorologia / RAG Chat
Vector storeChromaDB (persistent volume) + Ollama embeddings (nomic-embed-text)
ScaffoldingTODO stubs + numbered lab guide with acceptance checks per step
Doc languageEnglish (matches day5 docs); Portuguese data labels kept as-is from upstream

Verified data sources (live-tested 2026-11-12)

  1. INE accidents https://www.ine.pt/ine/json_indicador/pindica.jsp?op=2&varcd=0012774&lang=PT
    • Returns [ { IndicadorCod, IndicadorDsg, UltimoPref: "2024", DataUltimoAtualizacao, Dados: { "<year>": [ { geocod, geodsg, dim_3, dim_3_t, dim_4, dim_4_t, ind_string, valor } ] } } ]
    • dim_3_t = accident type (mortais / não mortais); dim_4_t = road type (Autoestradas, Vias nacionais…). Geography covers municipalities (geodsg = concelho name) and NUTS aggregates — both appear in the same response.
    • Payload ≈ 1 MB for the latest year → must TTL-cache; update cadence is annual.
  2. IPMA precipitation CSV https://api.ipma.pt/open-data/observation/climate/precipitation/prec-p1d-continental-obssup-idw-concelhos-20d.csv
    • Columns: time, zname, zid, mean_maxprate, std_maxprate, min_maxprate, max_maxprate, percentile_*_maxprate, mean_tp, std_tp, min_tp, max_tp, percentile_*_tp. One row per concelho per day, last 20 days. tp = daily precipitation total.
  3. IPMA stations/observations (already implemented in day5/ipma/ipma_mcp.py):
    • .../stations/stations.json and .../stations/observations.json (dict keyed by ISO timestamp → {station_id: measurements}), -99.0 = nodata.

Data caveat (must be stated in docs): INE accidents are annual aggregates; IPMA precipitation covers only the last 20 days. A rain-vs-accidents time correlation is impossible with these endpoints. The optional stretch goal is instead a name-join map: choropleth of 2024 accidents per concelho overlaid/matched with current 20-day precipitation by geodsg ≈ zname (normalizing accents/case).

Architecture

                ┌─────────────────────────────┐
 Browser ──────►│  dashboard (Streamlit) :8501│
                └──────┬──────────────┬───────┘
             HTTP/JSON │              │ MCP client (fastmcp.Client)
                       ▼              ▼
   ┌───────────────────────────┐  ┌──────────────────────┐
   │ accidents-rag-api :8000   │  │ ipma-mcp :8001/mcp   │
   │ FastAPI                   │  │ FastMCP http + TTL   │
   │  • INE proxy + TTL cache  │  │  • stations/obs tools│
   │  • ingest → ChromaDB (PVC)│  │  • precipitation tool│
   │  • LangChain RAG /ask     │  └──────────┬───────────┘
   └──────┬─────────────┬──────┘             │ httpx
          │             │                    ▼
          │             ▼             api.ipma.pt (CSV + GeoJSON/JSON)
          │      ollama :11434
          │      • qwen chat model
          │      • nomic-embed-text
          ▼
   dados.gov.pt / INE pindica API
  • Ports: dashboard 8501, accidents-rag-api 8000, ipma-mcp 8001 (streamable-http at /mcp), ollama 11434.
  • Dashboard is an MCP client (fastmcp Client("http://ipma-mcp:8001/mcp")) and a REST client of accidents-rag-api.
  • ChromaDB persists in a named volume inside accidents-rag-api; Ollama models in another volume.

Repository layout (to create)

final_project/
├── README.md                  # project brief, architecture diagram, quickstart, grading checklist
├── AGENTS.md                  # how AI agents should implement/extend this project
├── url.md                     # (exists) data sources
├── .env.example               # all env vars documented
├── docker-compose.yml
├── docs/
│   ├── architecture.md        # services, data flow, ports, env vars, failure modes
│   ├── concepts.md            # MCP / RAG / LangChain / FastMCP recap, links to day1–5 notes
│   ├── lab_guide.md           # numbered steps with TODO markers + acceptance checks
│   └── kubernetes.md          # k3s/minikube deployment walkthrough
├── ipma-mcp/
│   ├── Dockerfile, pyproject.toml, README.md
│   └── app/server.py          # adapted from day5/ipma/ipma_mcp.py; TODO: http transport, precipitation tool
├── accidents-rag-api/
│   ├── Dockerfile, pyproject.toml, README.md
│   └── app/
│       ├── main.py            # FastAPI routes (stubs)
│       ├── ine_client.py      # TODO: fetch + TTL cache + normalize INE JSON
│       ├── ingest.py          # TODO: chunking + ChromaDB upsert (LangChain)
│       └── rag.py             # TODO: retriever + Ollama chain (LangChain)
├── dashboard/
│   ├── Dockerfile, pyproject.toml, README.md
│   └── app/
│       ├── Home.py            # st.tabs: Acidentes | Meteorologia | RAG Chat
│       ├── tab_accidents.py   # TODO: charts from accidents-rag-api
│       ├── tab_weather.py     # TODO: fastmcp Client → ipma-mcp tools
│       └── tab_chat.py        # TODO: st.chat_input → POST /ask
└── k8s/
    ├── namespace.yaml, configmap.yaml
    ├── ollama.yaml            # Deployment + Service + PVC
    ├── ipma-mcp.yaml, accidents-rag-api.yaml (incl. Chroma PVC), dashboard.yaml

API / tool contracts (skeleton stubs must document these)

ipma-mcp tools (reuse day5 list_stations, get_latest_observations, get_station_observations as working code; new tool is the TODO):

  • get_precipitation_last_days(concelho: str | None = None, days: int = 7) -> dict — from TTL-cached CSV (TTL 3600 s; dataset refreshes daily), filtered by zname with accent/case-insensitive match.

accidents-rag-api (FastAPI):

  • GET /health → {"status": "ok"}
  • GET /accidents?year=&geodsg=&dim3=&dim4= → normalized records from TTL-cached INE JSON (TTL 86400 s; data is annual)
  • GET /accidents/summary → totals by year, top-N concelhos, latest metadata (UltimoPref, DataUltimoAtualizacao)
  • POST /ingest → builds text chunks from cached INE data, embeds via Ollama, upserts into ChromaDB; returns document count. One chunk per (year, geodsg): PT text like “Em 2024, em Guimarães (Braga): 32 acidentes com vítimas não mortais em Autoestradas; …”. Metadata: {year, geocod, geodsg, dim3, dim4}.
  • POST /ask {"question": ...} → LangChain retriever (ChromaDB) + langchain-ollama chat model; returns {answer, sources: [chunk metadata]}.

Dashboard tabs:

  • Acidentes: KPIs (total latest year, vs previous), bar chart top concelhos, filter by dim3/dim4 — all via accidents-rag-api.
  • Meteorologia: station picker → latest observations; concelho picker → precipitation last N days — via MCP client.
  • RAG Chat: st.chat_input, POST /ask, render answer + sources.

Env vars (all in .env.example): OLLAMA_BASE_URL, OLLAMA_MODEL (default qwen3.5:4b, matching day4 benchmark models), OLLAMA_EMBED_MODEL (default nomic-embed-text), INE_ACCIDENTS_URL, IPMA_PRECIP_URL, IPMA_OBS_URL, IPMA_STATIONS_URL, OBS_CACHE_TTL=300, PRECIP_CACHE_TTL=3600, INE_CACHE_TTL=86400, CHROMA_DIR=/data/chroma, ACCIDENTS_API_URL=http://accidents-rag-api:8000, IPMA_MCP_URL=http://ipma-mcp:8001/mcp.

Implementation task list (ordered)

  1. Docs first: README.md (brief + architecture + quickstart), docs/architecture.md, AGENTS.md (project rules: uv for venvs, keep upstream PT labels, comment style, no secrets, verify by running services). Include the annual-vs-20-days data caveat and the MCP client/HTTP service distinction.
  2. Skeleton + packaging: directory tree above; each pyproject.toml pinned (fastmcp>=2,<3, fastapi, uvicorn, httpx, langchain, langchain-ollama, chromadb, streamlit, pandas, requests); one Dockerfile per service (python:3.12-slim, non-root, uv or pip install).
  3. ipma-mcp: copy day5 ipma_mcp.py as the base (stations/observations tools work as-is), switch entrypoint to mcp.run(transport="http", host="0.0.0.0", port=8001), add get_precipitation_last_days as TODO stub (CSV parse helper may be provided working; the tool wiring is the TODO).
  4. accidents-rag-api stubs: ine_client.py (TODO: fetch + cache + normalize), ingest.py (TODO: chunk builder + Chroma upsert), rag.py (TODO: retriever + chain), main.py with FastAPI routes raising NotImplementedError in TODO bodies but /health working.
  5. dashboard stubs: Home.py with working st.tabs shell; each tab file renders a placeholder and has TODO bodies; provide working ask() / fetch_json() helpers as examples.
  6. docker-compose.yml + .env.example: 4 services, volumes (chroma-data, ollama-models), healthchecks (ollama via /api/tags), internal network, only dashboard published.
  7. k8s/ manifests + docs/kubernetes.md: namespace road-safety, ConfigMap for env, Deployments (1 replica each), ClusterIP Services, PVCs for chroma + ollama models, dashboard exposed via NodePort 30501; walkthrough for k3s and minikube.
  8. docs/lab_guide.md: numbered student steps (see below), each with TODO pointer + acceptance check.
  9. Validation (see below) and fix anything broken.

Lab guide steps (student journey, one acceptance check each)

  1. Compose up the skeleton — all containers healthy, curl /health works, Streamlit shell loads.
  2. Pull models — docker compose exec ollama ollama pull qwen3.5:4b nomic-embed-text succeeds.
  3. Implement INE client — GET /accidents?geodsg=Guimarães returns normalized records; second call served from cache (log line).
  4. Implement ingest — POST /ingest reports e.g. ~1k+ documents; chroma volume non-empty.
  5. Implement RAG — POST /ask {"question":"Quantos acidentes com vítimas em Guimarães em 2024?"} returns grounded answer + sources (32, per live check).
  6. Add MCP precipitation tool — fastmcp inspector or MCP client lists the new tool; call returns Águeda rows.
  7. Dashboard tabs — charts render from the API; weather tab shows MCP tool output; chat tab answers with sources.
  8. Kubernetes stage — kubectl apply -f k8s/ on k3s/minikube; dashboard reachable on NodePort; pod restart keeps Chroma data (PVC).

Risks & gotchas (document in AGENTS.md / lab guide)

  • INE payload ≈ 1 MB, annual cadence — cache aggressively; do not refetch per request; parse defensively (valor is a string).
  • FastMCP http transport — pin fastmcp>=2,<3; endpoint is http://host:8001/mcp; dashboard must run the async MCP client inside Streamlit’s event loop (provide helper using asyncio.run).
  • Ollama first boot — model pull is slow/large; PVC mandatory; set OLLAMA_KEEP_ALIVE to avoid reload latency in demos.
  • langchain-ollama, not langchain-openai, for ChatOllama/OllamaEmbeddings.
  • Chroma persistence — without the volume, /ingest work is lost on restart (compose + PVC in k8s).
  • Name-join stretch: geodsg vs zname differ in accents/case; normalize before matching; label the map clearly (different time scales).
  • No secrets — all upstream APIs are open; do not introduce keys.

Validation plan (implementer must run)

  1. docker compose build && docker compose up -d — all healthy.
  2. curl localhost:8000/health; curl "localhost:8000/accidents?year=2024&geodsg=Porto" (after step-3 implementation).
  3. MCP: npx @modelcontextprotocol/inspector against http://localhost:8001/mcp or a small fastmcp.Client script — list tools, call precipitation tool.
  4. POST /ingest then POST /ask with the Guimarães question — expect grounded answer citing the chunk.
  5. Streamlit at localhost:8501 — all three tabs render with data.
  6. Kubernetes (if available): kubectl apply -f k8s/ && kubectl get pods -n road-safety — all Running; restart a pod, confirm Chroma data persists.

Out of scope

  • Helm/kustomize packaging, CI/CD, authentication, horizontal scaling, Redis/pgvector alternatives, rain-vs-accidents statistical correlation, non-INE accident micro-data.