Skip to main content
Glama
README.md
# pyviaggiatreno

Monorepo Python (workspace `uv`) basato sulle API non ufficiali di
[ViaggiaTreno](http://www.viaggiatreno.it) (treni in Italia): libreria client,
server MCP e crawler che salva dati storici in SQLite.

## ๐Ÿ“ฆ Packages

| Package | Ruolo | PyPI |
|---------|-------|------|
| [`viaggiatreno`](./packages/viaggiatreno) | Libreria client HTTP async (core, nessuna dipendenza MCP) | `viaggiatreno` |
| [`viaggiatreno-mcp`](./packages/viaggiatreno_mcp) | Server MCP per agenti AI (Claude, Kiro, Cursor, โ€ฆ) | `viaggiatreno-mcp` |
| [`viaggiatreno-crawler`](./packages/viaggiatreno_crawler) | Poller che interroga le API nel tempo e salva in SQLite | `viaggiatreno-crawler` |

> Non esiste un pacchetto CLI generico separato: gli unici comandi da riga di
> comando sono gli entry point `viaggiatreno-mcp` (server MCP) e
> `viaggiatreno-crawler` (crawler).

### `viaggiatreno` - Core Library โญ

Pure Python client library for ViaggiaTreno APIs. No MCP dependencies.

```bash
pip install viaggiatreno
```

**Usage**:
```python
from viaggiatreno import ViaggiaTrenoClient
import asyncio


async def main():
    client = ViaggiaTrenoClient()

    # Get station suggestions
    stations = await client.autocompleta_stazione("milano")
    print(stations)

    # Get departures
    departures = await client.partenze("S01700", datetime.now())
    for train in departures:
        print(f"{train.compNumeroTreno} โ†’ {train.destinazione} ({train.ritardo} min delay)")


asyncio.run(main())
```

### `viaggiatreno-mcp` - MCP Server

Model Context Protocol server for Claude, pi, and other AI agents.

```bash
pip install viaggiatreno-mcp
```

**Start server**:
```bash
viaggiatreno-mcp
```

Configure in Claude, pi, or other AI tools to use these tools:
- `autocompleta_stazione` - Station autocomplete
- `cerca_stazione` - Search stations
- `dettaglio_stazione` - Station details
- `partenze` - Departures board
- `arrivi` - Arrivals board
- `stato_treno` - Train status & full route
- E altri...

### `viaggiatreno-crawler` - Crawler โ†’ SQLite

Poller che usa la libreria core per raccogliere nel tempo dati storici sui
treni (numeri, ritardi, binari, fermate) in un database SQLite locale โ€” utile
per KPI che le API ViaggiaTreno non espongono (sono solo "stato attuale", non
storiche).

```bash
pip install viaggiatreno-crawler
```

**Avvio**:
```bash
viaggiatreno-crawler eventi --regione 1 --db-path data/eventi.db
```

Flusso: stazioni (`elencoStazioni` e quelle scoperte da tabelloni e itinerari) โ†’
tabelloni di partenze/arrivi dei capolinea โ†’ `andamento_treno` una volta alla partenza e
una dopo l'arrivo previsto โ†’ upsert in SQLite, con una coda di lavori a scadenza.
Dettagli in
[packages/viaggiatreno_crawler/README.md](./packages/viaggiatreno_crawler/README.md);
tabelle, schema ed esempi di dati in [README-DB.md](./README-DB.md).

---

## โœจ Features

### Core Library
- ๐Ÿš„ Async/await HTTP client with `httpx`
- ๐Ÿ“Š Strongly-typed Pydantic models
- ๐Ÿ”„ Intelligent parsing (JSON, plain text, HTML fragments)
- โšก Handles ViaggiaTreno quirks (204 No Content, JS date formats, etc.)
- ๐Ÿ‡ฎ๐Ÿ‡น Full coverage of Italian railways

### MCP Server
- ๐Ÿค– AI-ready tool registration
- ๐Ÿ”— Automatic parameter resolution (derive trip details from train number)
- ๐Ÿ“ฑ Works with Claude, pi, and other MCP clients
- ๐Ÿงต Async concurrent tool execution

---

## ๐Ÿ“š Documentation

See main documentation files:
- [VIAGGIATRENO.md](./VIAGGIATRENO.md) - API reference (20+ endpoints)
- [TRENORD.md](./TRENORD.md) - GTFS Trenord structure
- [ENTITA.md](./ENTITA.md) - Data model & schema
- [GLOSSARIO.md](./GLOSSARIO.md) - Railway terminology
- [COPERTURA_GEOGRAFICA.md](./COPERTURA_GEOGRAFICA.md) - Geographic coverage

---

## ๐Ÿš€ Quick Start

### Installation

```bash
# Core library only
pip install viaggiatreno

# With MCP server
pip install viaggiatreno-mcp

# With crawler (SQLite poller)
pip install viaggiatreno-crawler
```

### Using the Library

```python
from viaggiatreno import ViaggiaTrenoClient
from datetime import datetime

client = ViaggiaTrenoClient()

# Get train departures from Milano Centrale
trains = await client.partenze("S01700", datetime.now())

for train in trains:
    print(
        f"{train.numeroTreno}: {train.destinazione} at {train.compOrarioPartenza} (delay: {train.ritardo}m)"
    )
```

### Using MCP Server

Il modo consigliato รจ `uvx` (richiede [uv](https://docs.astral.sh/uv/)), che
esegue il server in un ambiente isolato senza installarlo a mano.

**Claude Desktop** (`~/Library/Application Support/Claude/claude_desktop_config.json`
su macOS, `%APPDATA%\Claude\claude_desktop_config.json` su Windows):

```json
{
  "mcpServers": {
    "viaggiatreno": {
      "command": "uvx",
      "args": ["viaggiatreno-mcp"]
    }
  }
}
```

**Kiro** (`~/.kiro/settings/mcp.json`) e altri client con lo stesso formato
(Cursor, Windsurf, VS Code MCP):

```json
{
  "mcpServers": {
    "viaggiatreno": {
      "command": "uvx",
      "args": ["viaggiatreno-mcp"],
      "disabled": false,
      "autoApprove": []
    }
  }
}
```

In alternativa, se hai giร  fatto `pip install viaggiatreno-mcp`, usa
`"command": "viaggiatreno-mcp"` (o `"command": "python", "args": ["-m", "viaggiatreno_mcp"]`).
Riavvia il client dopo aver salvato la configurazione.

Dettagli completi in [packages/viaggiatreno_mcp/README.md](./packages/viaggiatreno_mcp/README.md).

---

## ๐Ÿ› ๏ธ Development

Il repo รจ un workspace `uv` con 3 pacchetti sotto `packages/`.

```bash
# Clone repo
git clone https://github.com/matteoredaelli/pyviaggiatreno.git
cd pyviaggiatreno

# Install workspace + dev deps (editable)
uv sync

# Lint + type check + format check
make lint          # ruff format --check + ruff check + pyright

# Run tests
make pytest        # oppure: uv run pytest

# Run MCP server
make run           # oppure: uv run viaggiatreno-mcp

# Run crawler
make crawler-eventi

# Build all packages
make build         # oppure: uv build
```

---

## ๐Ÿ“„ License

[GNU General Public License v3.0 o successiva](./LICENSE) (`GPL-3.0-or-later`).
Ogni file sorgente riporta l'intestazione `SPDX-License-Identifier: GPL-3.0-or-later`.

---

## ๐Ÿค Contributing

Contributions welcome! Please:
1. Fork the repo
2. Create a feature branch
3. Submit a PR

---

## ๐Ÿ“ž Support

- ๐Ÿ› [Bug reports](https://github.com/matteoredaelli/pyviaggiatreno/issues)
- ๐Ÿ’ฌ [Discussions](https://github.com/matteoredaelli/pyviaggiatreno/discussions)
- ๐Ÿ“ง Email: matteo.redaelli@gmail.com

---

## ๐Ÿ”„ GitHub Actions Workflow

La repo ha 3 workflow automatici:

### 1. **Tests & Linting** (`tests.yml`)
- โœ… Ruff linting
- โœ… Pyright type checking  
- โœ… Pytest unit tests
- ๐Ÿ”„ Trigger: Ogni commit su `main`/`dev` e PR
- ๐ŸŽฏ Purpose: Verifica codice quality

### 2. **Test Build** (`test-build.yml`)
- โœ… Build entrambi i pacchetti
- โœ… Testa installazione wheel
- ๐Ÿ”„ Trigger: Commit su `packages/` o workflow_dispatch
- ๐ŸŽฏ Purpose: Verifica che la build funzioni (senza pubblicare)

### 3. **Publish to PyPI** (`publish-pypi.yml`)
- โœ… Build entrambi i pacchetti
- โœ… Pubblica su PyPI
- โœ… Crea GitHub Release con artifacts
- ๐Ÿ”„ Trigger: Tag push (e.g. `git push origin v0.1.0`)
- ๐ŸŽฏ Purpose: Pubblica su PyPI (una sola volta)

**Vedi [RELEASE.md](./RELEASE.md) per istruzioni dettagliate.**

---

## ๐Ÿ“ฆ Publishing to PyPI

### Prerequisites

Il publish usa **Trusted Publishing (OIDC)** โ€” nessun token da gestire. Configurazione una tantum:

1. PyPI account (https://pypi.org)
2. Per **ciascun** pacchetto (`viaggiatreno`, `viaggiatreno-mcp`), aggiungi un Trusted Publisher:
   owner `matteoredaelli`, repo `pyviaggiatreno`, workflow `publish-pypi.yml`, environment `pypi`
3. Crea l'environment `pypi` in GitHub (Settings โ†’ Environments)

### Release Process
```bash
# 1. Commit & push
git add .
git commit -m "feature: add X"
git push origin main

# 2. Create tag (triggers publish workflow)
git tag v0.2.0
git push origin v0.2.0

# 3. GitHub Actions automatically publishes both packages
```

Both `viaggiatreno` and `viaggiatreno-mcp` (e `viaggiatreno-crawler`) will be published to PyPI with the same version.

---

TDQS

B3.4/5.0

Scored across 23 tools

Disambiguation3/5

Most tools target distinct concerns (boards, status, routes, info-mobility), but a few pairs genuinely blur: cerca_stazione and autocompleta_stazione both do prefix matching on station names, and stato_treno vs profilo_treno vs itinerario_treno_canvas all return train progress with overlapping data. Descriptions are detailed and frequently disambiguate (note on NTS codes, note on direct-only routes), which pulls this up to a middling score.

Naming Consistency4/5

All names are consistently snake_case Italian, mostly noun-first with a qualifier (profilo_stazione, tabellone_partenze, treni_su_tratta), which is easy to read and predict. Minor deviations exist where verb-first forms appear (cerca_*, autocompleta_*) for tasks that are otherwise noun-named, but overall the set feels coherent.

Tool Count3/5

23 tools is in the heavy 16-25 band. For a rich real-time rail API this is defensible, but several slots are low-value or redundant (titoli_infomobilita overlaps notizie/ticker, cerca_stazione vs autocompleta_stazione, autocompleta_stazione_nts serves an edge case). Some consolidation would tighten the surface.

Completeness4/5

The read-only ViaggiaTreno domain is well covered: station lookup/details/region, live departures/arrivals, train status/route/canvas, network segments and trains-on-segment, info-mobility, weather, and stats. The main gap is journey planning beyond direct trains (no multi-leg/change routing), plus no historical data, but agents can work around these.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues