Skip to main content
Glama
README.md
# openfantasy

Vendor-neutral fantasy sports platform. Connect Yahoo (ESPN and Sleeper are
registered scaffolds), normalise everything to the **OpenBook Fantasy** profile,
keep a local SQLite database, and expose it over an HTTP API and an MCP server.

The core has **zero runtime dependencies** (stdlib only). FastAPI and MCP are
optional extras that are already installed in this environment.

- Spec / models: [`openbook-fantasy`](https://github.com/openbook-data-standards/openbook-fantasy)
- Full plan: [`PLAN.md`](PLAN.md)

## Status

| Piece                                                                               | State                                           |
| ----------------------------------------------------------------------------------- | ----------------------------------------------- |
| OpenBook core + Fantasy profile conformance                                         | done (`../openbook-fantasy/conformance`)        |
| Yahoo OAuth 2.0 (auth-code, auto-refresh)                                           | done — needs your app credentials + one login   |
| Yahoo leagues / settings / teams / roster / scoreboard / transactions / free agents | done, tolerant parser pending live verification |
| Local SQLite store                                                                  | done                                            |
| Reports: roster health, trade, waivers, weekly                                      | done                                            |
| HTTP API + MCP server                                                               | done                                            |
| Sleeper / ESPN adapters                                                             | scaffolds                                       |
| OpenProb projections                                                                | seam only (raises clearly)                      |

## Quick start

```bash
cd openfantasy
cp .env.example .env          # optional; 'auth yahoo' can prompt instead
python3 -m openfantasy doctor
python3 -m openfantasy auth yahoo
python3 -m openfantasy sync
python3 -m openfantasy report weekly
```

No install step is required. Optionally, `pip install -e '.[api,mcp,dev]'` gives
you the `openfantasy` console script.

## Yahoo app setup (one time)

1. <https://developer.yahoo.com/apps/create/>
    - **Application Name:** `openfantasy`
    - **Application Type:** **Installed Application** if offered (this is the
      browser-less case; Yahoo then expects the callback `oob`). If the form only
      offers _Web Application_, register the callback domain `localhost` and set
      `YAHOO_REDIRECT_URI=https://localhost` — after approving you will land on a
      URL that fails to load, and you paste that whole URL back (the tool pulls
      `code=` out of it).
    - **API Permissions:** Fantasy Sports → **Read** (`fspt-r`)
2. Capture the **Client ID** and **Client Secret**. You do not have to hand-edit
   anything: `auth yahoo` asks for them once and writes `.env` (mode `0600`).
   Non-interactively, set them yourself:

    ```dotenv
    YAHOO_CLIENT_ID=...
    YAHOO_CLIENT_SECRET=...
    YAHOO_REDIRECT_URI=oob
    YAHOO_SCOPE=fspt-r
    ```

3. `python3 -m openfantasy auth yahoo`

    It prompts for the app values (first run only — Client ID, Client Secret,
    callback; press Enter for `oob`, or pass `--redirect <url>`), opens/prints an
    authorization URL, then you paste either the code (`oob`) or the full
    `?code=...` callback URL. On success it lists your leagues and syncs the
    first one (with raw payloads captured). Tokens are written to
    `$OPENFANTASY_HOME/tokens/yahoo.json` with `0600`.

Non-interactive: `python3 -m openfantasy auth yahoo --code '<code>' --sync`.

Yahoo's Fantasy API guide (<https://developer.yahoo.com/fantasysports/guide/>)
now describes an application-review step. If the create form still lists
_Fantasy Sports_ permissions, approval is immediate and you can proceed.

`fspt-w` (read/write) is only needed for setting lineups, waiver claims or
trades later. Start with `fspt-r`.

### `403 This application is not authorized to perform this action`

The token is valid and Yahoo accepts the login, but the **app** is not entitled
to the Fantasy API. In order:

1. <https://developer.yahoo.com/apps/> → open the app → confirm **API
   Permissions** lists `Fantasy Sports` (Read) and save if it was missing.
2. Re-authorize (`auth yahoo`) after changing permissions — the granted scope is
   fixed at consent time, so an old token stays unentitled.
3. If the permission is already listed and re-consent still 403s, the app needs
   approval through Yahoo's Fantasy API application review
   (<https://developer.yahoo.com/fantasysports/guide/>). Nothing client-side
   fixes that.

A `401` instead of `403` means the token itself is bad — re-run `auth yahoo`.

## Commands

```bash
python3 -m openfantasy doctor                      # config, token, sync status
python3 -m openfantasy auth yahoo                  # OAuth login (prompts once)
python3 -m openfantasy leagues                     # live leagues on the account
python3 -m openfantasy leagues --saved --json      # leagues already synced
python3 -m openfantasy sync                        # auto-detect the only league
python3 -m openfantasy sync --league 449.l.12345 --team 449.l.12345.t.3
python3 -m openfantasy sync --league 449.l.12345 --raw   # + dump raw payloads
python3 -m openfantasy teams --league 449.l.12345

python3 -m openfantasy report health               # empty slots, injuries, swaps
python3 -m openfantasy report waivers --limit 15
python3 -m openfantasy report weekly               # the full brief
python3 -m openfantasy report trade --give "Bijan Robinson" --get "Josh Jacobs"

python3 -m openfantasy sql "SELECT * FROM roster_entries WHERE week=5"
python3 -m openfantasy serve --port 8765           # HTTP API
python3 -m openfantasy mcp                         # MCP server (stdio)
```

Add `--provider yahoo|espn|sleeper` to `leagues`/`sync`. ESPN and Sleeper
currently return a clear "scaffold" error.

## HTTP API

`python3 -m openfantasy serve` then:

```
GET  /health
GET  /providers
GET  /leagues
GET  /leagues/{league_key}
GET  /leagues/{league_key}/teams
GET  /leagues/{league_key}/standings            # record, PF/PA, rank
GET  /leagues/{league_key}/scoreboard?week=5
GET  /leagues/{league_key}/waivers?position=RB&limit=25
GET  /teams/{team_key}/roster?week=5
GET  /teams/{team_key}/health
GET  /teams/{team_key}/context                  # luck-vs-talent read
GET  /reports/trade?give=Bijan&get=Jacobs&league_key=449.l.1
GET  /reports/waivers?team_key=449.l.1.t.3
GET  /reports/weekly?team_key=449.l.1.t.3
GET  /reports/recent?kind=weekly
POST /sync?league_key=449.l.1&team_key=449.l.1.t.3
GET  /sql?q=SELECT%20*%20FROM%20leagues     # SELECT/WITH only
```

## MCP

```json
{
    "mcpServers": {
        "openfantasy": {
            "command": "python3",
            "args": ["-m", "openfantasy.mcp.server"],
            "cwd": "/Users/dan/code/KazFlock/openfantasy"
        }
    }
}
```

Tools: `fantasy_providers`, `fantasy_list_leagues`, `fantasy_league_settings`,
`fantasy_list_teams`, `fantasy_my_team`, `fantasy_team_roster`,
`fantasy_scoreboard`, `fantasy_roster_health`, `fantasy_trade_compare`,
`fantasy_waiver_targets`, `fantasy_weekly_report`, `fantasy_sql`,
`fantasy_sync`.

## Where state lives

| Path                                                  | Contents                         |
| ----------------------------------------------------- | -------------------------------- |
| `$OPENFANTASY_HOME` (default `~/.config/openfantasy`) | state dir                        |
| `.../tokens/yahoo.json`                               | OAuth tokens, `0600`             |
| `.../data/openfantasy.db`                             | the local database (SQLite, WAL) |

Override with `OPENFANTASY_HOME` or `OPENFANTASY_DB`.

## Reports are data-derived

Points in reports are **recorded actual points** from the last sync, or a
labelled baseline. Nothing is presented as a projection until an OpenProb
projector is wired (`openfantasy/projections.py`). Trade verdicts compare
recorded points only; they are not rest-of-season forecasts.

## License and credentials

Apache-2.0 — see [`LICENSE`](LICENSE).

The client secret is **not** distributed with this repository. Each user
registers their own Yahoo app and authorises their own account; that is why
`auth yahoo` prompts for a Client ID and Secret on first run and writes them to
`.env` (mode `0600`). Tokens live under `$OPENFANTASY_HOME/tokens` and never
leave the machine.

Access is read-only (`fspt-r`): leagues, settings, teams, standings, rosters,
scoreboards, transactions and free agents. Nothing here sets lineups, bids on
waivers or proposes trades.

Requests are issued serially (no parallelism) and retried with linear backoff
on 5xx responses. The only outbound calls are the ones `sync` makes to Yahoo.

## Tests

```bash
python3 -m pytest          # 25 tests, no network
```