FPL Assistant
# FPL Assistant
A personal Fantasy Premier League assistant that knows your actual team and
helps you pick a lineup and plan transfers using **live, up-to-date data**.
It is built to run inside [OpenCode](https://opencode.ai): open OpenCode in this
repo, pick the `fpl` agent, and just talk about your team. Under the hood a
small Python service exposes the data and analysis as MCP tools; the agent is
the part that reasons, explains and asks you the right questions.
> Not affiliated with the Premier League or Fantasy Premier League. It reads
> public endpoints and is for personal use.
## What it does
- **Your squad, live** - pulls your actual 15, plus bank, squad value and your
banked free transfers. Sign in once with `fpl login` and it reads the team you
have *saved for the next gameweek* (visible before the deadline), with your
real free transfers and chips; otherwise it uses your last completed gameweek
and estimates the free transfers from your history.
- **Best XI** - picks the highest-scoring valid formation, with bench order,
captain and vice.
- **Transfer ideas** - one-for-one swaps within your bank, ranked by projected
gain, with a clear "is this worth a -4 hit?" call and the reasoning (fixtures,
form, underlying numbers).
- **Fixtures, rated our own way** - the next N games per team with **our own
difficulty model** (results, recent form and xG, adjusted for venue), a
ticker across the whole league, and FPL's number alongside for comparison.
- **Scouting** - each player's status, news, FPL scout risk fields and scout
link, plus a page fetcher for scout articles and press conferences.
- **Team news & injuries** - the day's **per-club press conferences** (Fantasy
Football Scout's Team News round-up) and, with a free API-Football key, a
structured injury list (player, type, reason). Both carry a source link and a
fetched-at time so you know how fresh the news is.
- **A second opinion on the numbers** - Understat xG/xA/xGI per player and xG
for/against per team, alongside the FPL API's own expected stats.
- **FPL Draft** - a separate game on its own public API: your draft squad and
best XI, waiver/free-agency claims (who to add and who to drop), and realistic
**position-preserving trades** against each rival, each labelled with who wins
on the model. Read-only: it recommends, you act on the site.
## Data sources
1. **Official FPL API** (`fantasy.premierleague.com/api`) - the backbone:
players, prices, form, ICT, xG/xA, fixtures, ownership, your picks and history.
2. **football-data.co.uk** - a reliable second statistical source: one CSV per
season, aggregated into an independent team table of points, goals, xG for
and against, shots on target and recent form.
3. **Fantasy Football Scout** - its rolling **Team News** round-up, the
community-standard digest of every manager's pre-deadline press conference,
split into one block per club. Discovered via the site's RSS feed; no key.
4. **API-Football** (`api-sports.io`) - a **structured injury list** (player,
injury type, expected return) for the Premier League. Optional and keyed:
grab a free key and store it with `fpl api-key`. Skip it and everything else
still works.
5. **The open web** - the agent uses web search plus the `fetch_page` tool to
read scout reports and press conferences for late injury news. (Understat
xG/xA/xGI per player is wired in too, but it is a best-effort scrape that
some networks block; the tools simply return nothing when it fails.)
Everything is cached on disk with sensible TTLs and degrades to stale data
rather than failing, so a flaky upstream never derails a team-selection chat.
## Requirements
- Python 3.11+ and [uv](https://docs.astral.sh/uv/)
- [OpenCode](https://opencode.ai) V2 (for the agent/skill experience)
## Setup
```sh
git clone https://github.com/mpvii/fpl-assistant.git
cd fpl-assistant
uv sync
```
Versions are tagged; see [Releases](https://github.com/mpvii/fpl-assistant/releases).
To pin one, clone its tag:
```sh
git clone --branch v0.1.0 https://github.com/mpvii/fpl-assistant.git
```
### Find your FPL entry id
Your entry (team) id is the number in your team's URL:
```
https://fantasy.premierleague.com/entry/1234567/event/13
^^^^^^^
```
If you don't have it to hand, page through any mini-league you are in:
```sh
uv run scripts/find_entry.py --league <mini-league-id> --name "<your team name>"
```
### Point the tool at your team
Copy `config.example.toml` to `~/.config/fpl-assistant/config.toml` and set
`entry_id`, or set the environment variable:
```sh
export FPL_ENTRY_ID=1234567
```
The tools that need your team will otherwise ask you to set it.
### Free transfers and bank
When you are signed in (`fpl login`, below) the tools read your **real bank and
free transfers** straight from your live team. When you are not signed in, the
bank still comes from the public API but the free-transfer count is reconstructed
from your transfer history - treat that number as an estimate.
### See your live team before the deadline (sign in)
The public API cannot show your squad until a gameweek has kicked off, and it
never exposes banked free transfers. To see the team you have actually saved on
deadline day - with your real free transfers and chips - sign in once:
```sh
uv sync --extra login # adds Playwright
uv run playwright install chromium # fetches the browser
uv run fpl login # opens a browser; log in as usual
```
A browser window opens; log in to Fantasy Premier League normally (SSO, 2FA and
Cloudflare all work because it is a real browser). Once you are in, the window
closes and the tool stores a **refresh token** in the macOS **Keychain** (service
`fpl-assistant`; it falls back to `~/.config/fpl-assistant/tokens.json`, mode 600,
if the Keychain is unavailable). From then on it exchanges and rotates that token
automatically - you never copy a cookie.
You can also let `fpl login` fill the sign-in form for you. Store your password
in the Keychain once - it is read at runtime and never written to a file or
passed on a command line:
```sh
uv run fpl login --save-password --email you@example.com
```
That prompts once (hidden), saves the password to the Keychain, then signs you in
automatically on every later `fpl login`. `fpl logout --forget-password` removes
it again. Note the sign-in page carries an invisible reCAPTCHA, so the automated
step is best-effort: if it is challenged, the window stays open and you can
finish by hand.
From OpenCode you can also just ask the assistant to sign you in: the `login`
tool (surfaced as `fpl_login`) does the same thing - opens the browser, fills the
form from the Keychain, stores the token. To fill the **username** it needs your
FPL email; a successful login remembers it in the Keychain, and you can set it up
front with `email = "you@example.com"` in `~/.config/fpl-assistant/config.toml`
(or `FPL_EMAIL`). `fpl_logout` signs you out from chat too.
This works because FPL replaced the old `sessionid` cookie with **PingOne OIDC**:
the API now wants an `X-API-Authorization: Bearer <access_token>` header, and the
durable credential is the OIDC refresh token. `fpl auth-status` shows whether you
are signed in; `fpl logout` forgets the token.
Once signed in, `get_my_team` (and the squad tools) read the live team and label
the source `live`; the token is only ever sent to FPL, and never written to the
response cache. This is a **read-only** integration - nothing here changes your
team.
## Using it in OpenCode
Open OpenCode **inside this repo** and select the `fpl` agent (Tab to switch
agents, or set it as default). The project `opencode.json` connects to the MCP
server, and the agent has three skills: `fpl-team` (squad/lineup/transfers),
`fpl-scout` (reports, news and the second statistical source) and `fpl-draft`
(the draft XI, waivers and trades).
The MCP server runs **once** as a small local HTTP service
(`scripts/install_http_service.sh` installs it as a launchd agent on
`http://127.0.0.1:8765/mcp`) and OpenCode connects as a `remote` server. That is
deliberate: a `local` stdio server is spawned per session and OpenCode does not
reap them, so one process per session used to pile up. One shared HTTP process
serves every session instead.
Things you can say:
- "How's my team looking for the next gameweek?"
- "Should I move on any of my defenders?"
- "What's the best XI this week, and who should I captain?"
- "Is X worth a -4 to bring in Y?"
- "Any injury news on my flagged players?"
The agent always states the gameweek and deadline, shows its reasoning, and
recommends a primary option plus alternatives, not a single blind pick.
> Want it in **every** session? Run the installer - it syncs the venv, starts
> the shared HTTP service, and adds the MCP server, the agent and the skills to
> your global OpenCode config (backing that config up first):
>
> ```sh
> bash scripts/install_global.sh
> ```
>
> It is idempotent; re-run it after pulling changes (it restarts the service so
> new code takes effect). Remove the service again with
> `bash scripts/install_http_service.sh uninstall`. It never sets a global
> default agent, so `fpl` stays opt-in per session (select it with Tab, or
> `opencode run --agent fpl`).
## Using it from the shell
The same tools are available as a CLI, handy for a quick look:
```sh
uv run fpl status
uv run fpl digest # gameweek digest for every team you run
uv run fpl digest --format md # ...as a readable Markdown document
uv run fpl digest --out gw13.md # ...written to a file
uv run fpl squad
uv run fpl login # sign in via a browser (stores a refresh token)
uv run fpl login --save-password # ...and remember the password in the Keychain
uv run fpl auth-status # are you signed in?
uv run fpl my-team # live, authenticated squad (needs `fpl login`)
uv run fpl analyze
uv run fpl lineup
uv run fpl transfers --limit 5
uv run fpl players --position MID --sort xgi90 --limit 10
uv run fpl fixtures Arsenal --horizon 6
uv run fpl ticker --horizon 6 # every team's run, easiest first
uv run fpl ticker --horizon 6 --desc # hardest first
uv run fpl strength # our team ratings (results, form, xG)
uv run fpl table
uv run fpl form Arsenal
uv run fpl scout "Saka" "Palmer"
uv run fpl understat --sort xgi90
uv run fpl team-news # today's per-club press conferences (FFScout)
uv run fpl injuries --team Arsenal # structured injuries (needs `fpl api-key`)
uv run fpl api-key --save # store a free API-Football key in the Keychain
uv run fpl draft-status # your FPL Draft league at a glance
uv run fpl draft-squad # your draft XV and best XI
uv run fpl draft-lineup # your best draft XI for the next gameweek
uv run fpl draft-waivers # waiver/free-agency calls: who to claim and drop
uv run fpl draft-trades # position-legal trade proposals
uv run fpl draft-free-agents --position FWD
uv run fpl draft-rosters # every manager's draft squad
```
## MCP tools
| Tool | What it returns |
| --- | --- |
| `status` | Config, current/next gameweek and deadline |
| `auth_status` | Whether you are signed in to FPL and when the token expires |
| `login` | Sign you in: opens a browser, fills the form from the Keychain, stores the token |
| `logout` | Sign you out (optionally forget the saved password) |
| `list_players` | Filtered, sorted players with live stats |
| `get_player` | One player, recent history and upcoming fixtures |
| `fixture_difficulty` | A team's next N fixtures with **our own** difficulty |
| `fixture_ticker` | Every team's next N games, easiest run first |
| `league_strength` | Our team ratings: position, form, attack, defence, strength |
| `football_data_table` | Independent team table: points, xG, shots, form |
| `team_form` | One team's season form from football-data.co.uk |
| `get_entry` | Your manager summary, rank, bank, value, chips |
| `get_my_team` | Your live, authenticated squad (pre-deadline), real bank/FTs/chips |
| `get_squad` | Your current 15 with stats and captain/vice |
| `analyze_my_squad` | Headline view: best XI, flags, fixtures, notes |
| `optimize_lineup` | Best XI, bench order, captain and vice |
| `suggest_transfers` | Ranked one-for-one transfers within budget |
| `gameweek_digest` | One call across your teams: XI, flags, transfers/waivers/trades |
| `gameweek_digest_markdown` | The digest as a readable Markdown document (optionally saved to a file) |
| `league_table` | Mini-league standings |
| `scout_report` | Status, news, scout risks/link for players |
| `fetch_page` | Cleaned text from any scout/press web page |
| `understat_players` | Understat xG/xA/xGI per player |
| `understat_teams` | Understat xG for/against per team |
| `team_news` | Today's per-club presser summaries (FFScout Team News) |
| `api_football_injuries` | Structured injury list (API-Football, needs a key) |
| `draft_status` | Your draft league: format, standings, waiver order, deadline |
| `draft_my_squad` | Your draft XV with projections, best XI and bench |
| `draft_lineup` | Your best draft XI and bench order (no captain) |
| `draft_free_agents` | Best unowned players (filter by position/minutes) |
| `draft_waivers` | Same-position claims: who to add and who to drop |
| `draft_trades` | Position-legal swaps, each with the partner's projected delta |
| `draft_rosters` | Every manager's draft squad (who owns whom) |
## How the scoring works
```
score(player) = expected_points(player) * fixture_factor(team) + form_bonus(player)
```
- `expected_points` prefers FPL's own `ep_next`, then `ep_this`, then points-per-game.
- `fixture_factor` nudges players up on easy fixtures and down on hard ones,
using **our own difficulty** (below), not FPL's laggy FDR.
- `form_bonus` is a small additive term from recent form.
`fixture_factor` and `form_bonus` are intentionally simple and inspectable - the
idea is that the agent explains the reasoning and you argue with it, not that a
black box tells you what to do.
## Our own fixture difficulty
FPL's 1-5 fixture difficulty is slow: it tracks a team's reputation more than
this season's evidence, so it lags the table and ignores form. We build our own
rating (`strength.py`) from what teams have actually done:
- **results** - points per game this season, blended with form (points per game
over the last five);
- **attack** - goals for per game, blended with xG for per 90 from
football-data.co.uk;
- **defence** - goals against per game, blended with xG against per 90.
Each is normalised across the league, combined into a 0-1 **strength**, nudged
for venue (home sides are stronger) and mapped to a 1-5 **difficulty**. The
model also splits the number into an **attack** sub-rating (how hard the fixture
is for your forwards - the opponent's defence) and a **defence** sub-rating (for
your defenders - the opponent's attack), so the same fixture can read hard for a
striker and easy for a keeper.
`fixture_difficulty`, `fixture_ticker` and `league_strength` all report it, and
carry FPL's own `fpl_difficulty` alongside so you can see where the two
disagree. Everything is pure and unit-tested; the xG blend is best-effort and
degrades to goals-per-game when the second source is unavailable.
## FPL Draft
FPL Draft is a **separate game** with its own public API
(`draft.premierleague.com/api`). It needs no login: the league, who owns whom,
every waiver move and every trade are all readable. The differences that matter:
- **Unique ownership** - each player is held by one manager; everyone else is a
free agent (the waiver pool).
- **No prices, no captain** - a squad is a fixed **2 GKP / 5 DEF / 5 MID /
3 FWD**, an XI of 11 with 4 bench and autosubs.
- **Trades preserve positions** - a MID can only leave a squad if a MID arrives
(the squad must stay 2/5/5/3). With one objective projection, a same-position
swap is zero-sum on raw value, so the trades worth proposing are the ones where
the other manager is **deep where you are short** - the player you take is
spare for them.
Draft players are valued by the **same scorer** as the classic game (FPL expected
points x our own fixture difficulty + form). A draft element id is the draft
game's own, so it is joined to the *draft* bootstrap rather than the classic one
(the two id spaces differ for a minority of players).
Point it at your team in `config.toml`:
```toml
draft_league_id = 123456 # the number in .../league/<ID>/standings
draft_entry_id = 7654321 # the number in .../entry/<ID>/edit
draft_team = "Your Team Name" # optional fallback: find you by name
```
The draft tools are **read-only** - they recommend, you act on the site. Each
`draft_trades` proposal carries the partner's own projected change
(`their_xi_gain`) and a fairness label, so a trade that only helps you is
flagged as an ask rather than dressed up as a win-win.
## Limitations
- **Free transfers come from your live team.** When you are signed in the tools
read the real count; otherwise they reconstruct it from your history, so treat
the unsigned-in number as an estimate.
- **Sell prices are approximated** at current price (purchase prices aren't in
the public API).
- **Understat is a best-effort scrape.** Some networks block it; when that
happens the Understat tools return an empty result and everything else keeps
working. The FPL API's own expected stats and football-data.co.uk cover the
need.
- This is decision support. No tool knows what will happen on Saturday.
## Development
```sh
uv run pytest # unit tests (pure logic, no network)
uv run ruff check # lint
uv run ruff format # format
# sign-in needs the optional extra + a browser
uv sync --extra login
uv run playwright install chromium
# the MCP server: stdio by default, or HTTP for the shared service
uv run fpl-assistant-mcp
uv run fpl-assistant-mcp --transport streamable-http --port 8765
```
## Layout
```
src/fpl_assistant/
config.py entry id, optional token seed, cache location, season
auth.py PingOne OIDC: refresh-token exchange, rotation, Bearer header
keychain.py macOS Keychain access for the password + refresh token
login.py browser-driven sign-in (Playwright) for `fpl login`
http.py cached, polite HTTP
fpl.py official FPL API client + derived helpers
footballdata.py football-data.co.uk source (xG, shots, form)
strength.py our own fixture-difficulty model (results, form, xG)
understat.py Understat xG/xA/xGI source (best-effort)
scout.py scout fields + readable page text
teamnews.py team news (FFScout) + structured injuries (API-Football)
analyze.py lineup, squad and transfer logic
draft.py FPL Draft client (separate, public API) + derived helpers
draftstrategy.py draft lineup, waiver and trade logic (pure)
mcp_server.py the MCP tools
cli.py the human CLI
.opencode/
agents/fpl.md the OpenCode agent
skills/ fpl-team, fpl-scout and fpl-draft skills
scripts/find_entry.py
scripts/install_http_service.sh the shared HTTP MCP service (launchd)
scripts/install_global.sh global OpenCode install (service + config + agent)
tests/
```
## License
MIT - see [LICENSE](LICENSE).
TDQS
Scored across 33 tools
Most tools target clearly distinct resources (players, fixtures, draft, transfers, external stats). A few pairs overlap: status vs auth_status, get_my_team vs get_squad, and gameweek_digest vs gameweek_digest_markdown (same content, different format). Descriptions mostly disambiguate these, but an agent could still hesitate between get_my_team and get_squad.
The draft tools use a clean draft_* prefix and many tools follow verb_noun (get_player, list_players, suggest_transfers), but a large set are noun-only or noun_phrase (status, team_form, league_table, fixture_ticker, understat_players, football_data_table, scout_report). Mixed conventions remain readable but aren't predictable.
33 tools is heavy for the scope, spanning auth, classic team, draft, transfers, fixtures, players, leagues and multiple external data sources. Several tools (status/auth_status, get_my_team/get_squad/analyze_my_squad, the two digest variants) could be consolidated.
Coverage is broad: auth, classic squad analysis, lineup optimization, transfers, draft waivers/trades, fixtures, players, leagues, and multiple independent stats sources. It's a read-only analysis toolkit, so the absence of write/transfer-execution tools is by design; minor gaps like direct player comparison are workable via get_player.