agentleFS
garavitgabrielgaravitgabriel/espn-fantasy-claude-openclaw/CLAUDE.md

espn-fantasy-claude-openclaw

CLAUDE.md3 starsChanged 6 years agoMITView on GitHub

This is a fork of cwendt94/espn-api extended with an MCP server, CLI, and Claude Code plugin for ESPN Fantasy Baseball. The league is "El Rey" (league ID 612122596), an H2H Categories format. Works with Claude Code, Claude Desktop, Claude Cowork, and OpenClaw.

  • Reads credentials

The file

We split this CLAUDE.md into the rules it gives an agent

11 rules. About 0 are common, 4 are distinctive, and 7 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 7

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    config.py owns the League instance: Always use get_league() and get_my_team() — never instantiate League directly in tools or CLI.

    line 50
  2. Distinctive:

    MCP tools and CLI commands are 1:1: Every MCP tool has a matching CLI subcommand.

    line 51
  3. Very specific:

    Create skills/<skill-name>/SKILL.md with frontmatter (name, description) and step-by-step instructions referencing MCP tool names.

    line 98
  4. Distinctive:

    Update the skill mapping table above.

    line 101
  5. Very specific:

    Write tools live in mcp_server/writes/{roster,lineup,trades}.py and share the safety flow in mcp_server/writes/_base.py.

    line 170
  6. Very specific:

    Every mutation is a single POST to ESPN's lm-api-writes /transactions/ endpoint (see docs/writes/00-BRIEF.md for the verified payloads and …

    line 176
  7. Very specific:

    Add formatter function in formatters.py if new output formatting is needed.

    line 190
  8. Very specific:

    Add MCP tool in tools.py inside register_tools().

    line 191
  9. Very specific:

    Add @app.command() in cli/__init__.py.

    line 192
  10. Distinctive:

    Update the tool mapping table above and in README.md.

    line 193
  11. Distinctive:

    When the user asks about their fantasy baseball league, use the MCP tools in this order:

    line 197

≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

Project Overview

This is a fork of cwendt94/espn-api extended with an MCP server, CLI, and Claude Code plugin for ESPN Fantasy Baseball. The league is "El Rey" (league ID 612122596), an H2H Categories format.

Works with Claude Code, Claude Desktop, Claude Cowork, and OpenClaw.

Quick Reference

uv sync                              # Install dependencies
uv run espn auth login               # Browser login (captures cookies)
uv run espn auth token <S2> <SWID>   # Manual credential entry
uv run espn standings                # CLI command
uv run espn-mcp                      # Start MCP server (stdio)
uv run pytest                        # Run tests

Architecture

espn-api/
├── .claude-plugin/plugin.json   # Plugin manifest (auto-discovered)
├── .mcp.json                    # MCP registration (uv run espn-mcp)
├── settings.json                # Default agent: fantasy-advisor
├── skills/                      # 8 agent-invoked skills
├── commands/                    # 5 user-invoked slash commands
├── agents/                      # fantasy-advisor agent
├── memory/                      # SQLite memory MCP server (separate package)
├── espn_api/                    # Upstream library (don't modify)
├── mcp_server/                  # MCP server + CLI (main package)
│   ├── server.py                # FastMCP: 20 tools + 5 resources
│   ├── tools.py                 # Tool definitions → register_tools(mcp)
│   ├── resources.py             # Resource definitions → register_resources(mcp)
│   ├── formatters.py            # 14 fmt_* functions (shared by tools + CLI)
│   ├── config.py                # League singleton, credential loading
│   ├── auth.py                  # ConfigManager + EspnConfig (Pydantic)
│   └── cli/                     # Typer CLI
│       ├── __init__.py          # 20 league commands + main()
│       ├── auth.py              # token, status, logout
│       └── build_plugin.py      # Plugin bundle builder
├── pyproject.toml               # uv/hatchling config, entry points
└── Dockerfile                   # Production container

Key Patterns

  • Formatters are the single source of truth for output. Both tools.py and cli/ call functions in formatters.py. Never duplicate formatting logic.
  • config.py owns the League instance. Always use get_league() and get_my_team() — never instantiate League directly in tools or CLI.
  • MCP tools and CLI commands are 1:1. Every MCP tool has a matching CLI subcommand. When adding a new capability, add it to both.
  • Credentials: env vars > config file > defaults. ConfigManager loads from ~/.espn-fantasy/config.json, then applies env var overrides. Users can set credentials via espn auth login (browser), espn auth token (manual), or .env.
  • The plugin wraps the MCP, never replaces it. Skills orchestrate MCP tools via markdown instructions. The standalone MCP stays stateless.
  • Memory is optional and plugin-only. The SQLite memory server runs locally via stdio. It does NOT affect the standalone MCP. Skills degrade gracefully without memory.

Development

uv sync --group dev     # Install with dev deps
uv run pytest           # Run tests
uv run espn --help      # CLI help
uv run espn-mcp         # Start MCP server (stdio)

Plugin Development

# Test the plugin locally (auto-discovered from repo root)
claude

# Available slash commands
/espn-fantasy:standings
/espn-fantasy:roster [team_name]
/espn-fantasy:matchup [week]
/espn-fantasy:scout [position]
/espn-fantasy:refresh

Plugin ↔ Skill ↔ MCP Tool Mapping

Plugin SkillTypeMCP Tools Used
matchup-scoutAgent-invokedget_standings, get_matchup, get_team_roster, get_my_roster + memory
free-agent-finderAgent-invokedget_scoring_categories, get_my_roster, get_roster_needs, get_free_agents, get_player_info + memory
trade-analyzerAgent-invokedget_scoring_categories, analyze_trade, get_player_info, get_my_roster + memory
draft-assistantAgent-invokedget_scoring_categories, get_roster_slots, get_draft_board, get_roster_needs, get_free_agents, get_player_info + memory
weekly-prepAgent-invokedget_standings, get_matchup, get_my_roster, get_team_roster, get_free_agents + memory
category-strategistAgent-invokedget_standings, get_my_roster, get_scoring_categories, get_league_rosters + memory
waiver-wire-scoutAgent-invokedget_recent_activity, get_my_roster, get_scoring_categories, get_player_info + memory
season-outlookAgent-invokedget_standings, get_my_roster, get_scoring_categories, get_box_scores + memory

Memory MCP Server

The memory server (memory/) is a local SQLite-backed MCP server with 14 tools across 6 tables: matchup_history, roster_moves, watchlist, category_trends, draft_picks, preferences. DB stored at ~/.espn-fantasy/memory.db.

Adding a New Skill

  1. Create skills/<skill-name>/SKILL.md with frontmatter (name, description) and step-by-step instructions referencing MCP tool names.
  2. Skills reference ESPN tools as get_* and memory tools as save_*/get_* from the memory server.
  3. Include conditional memory steps: "If memory tools are available, call X."
  4. Update the skill mapping table above.

Environment Variables

Set via espn auth login (browser), espn auth token (manual), or .env (gitignored). Stored in ~/.espn-fantasy/config.json. Env vars always override the config file.

VariablePurpose
ESPN_S2ESPN auth cookie
ESPN_SWIDESPN auth SWID
ESPN_LEAGUE_IDLeague ID (default: 612122596)
ESPN_YEARSeason year (default: 2026)
ESPN_TEAM_NAMEPartial match for your team name (default: Gabriel)
ESPN_WRITE_ENABLEDEnable mutating tools (add/drop/waiver/lineup/trade). Default false (read-only). Set true/1/yes/on to allow writes.

MCP Resources

URIDescription
espn://workflow/season-managementWeekly season management playbook
espn://workflow/draft-dayAuction draft day playbook
espn://info/league-settingsH2H Categories format, scoring, roster config
espn://skill/matchup-scoutMatchup analysis workflow
espn://skill/free-agent-finderFree agent search workflow

Tool ↔ CLI ↔ Formatter Mapping

MCP ToolCLI CommandFormatter
get_my_rosterrosterfmt_roster
get_team_rosterroster --team Xfmt_roster
get_matchupmatchupfmt_box_score
get_standingsstandingsfmt_standings
get_free_agentsfree-agentsfmt_free_agents
get_recent_activityactivityfmt_activity
get_box_scoresbox-scoresfmt_box_score
get_player_infoplayerfmt_player_detail
compare_playerscomparefmt_compare
get_league_rostersrostersfmt_league_rosters
analyze_tradetradefmt_trade_analysis
get_scoring_categoriesscoringfmt_scoring_categories
get_roster_slotsslotsfmt_roster_slots
get_draft_boarddraftfmt_draft_board + fmt_roster_needs
get_roster_needsneedsfmt_roster_needs
get_scheduleschedulefmt_schedule
get_league_settingssettingsfmt_league_settings
search_playersearchfmt_player_search
get_scoreboardscoreboard(none)
refresh_datarefresh(none — returns status string)
get_probable_pitchersprobable-pitchersfmt_probable_pitchers
get_sp_schedulesp-schedulefmt_sp_schedule
get_weekly_movesweekly-movesfmt_weekly_moves
get_batter_vs_team (accepts opponent_team)vs-team --opponentfmt_batter_vs_team
get_recent_activity (accepts team_name, scoring_period)activity --team --periodfmt_activity

Write Tools (gated by ESPN_WRITE_ENABLED)

These mutate the real league. Each is two-step: call without confirm_token for a preview + token, then re-call echoing the token to execute. See "Writes & Safety" below.

MCP ToolCLI CommandLibrary method (espn_api/baseball/league.py)Formatter
add_playeradd <player> [--drop X] [--confirm-token T]add_drop_playerfmt_txn_preview / fmt_txn_result
drop_playerdrop <player> [--confirm-token T]add_drop_player (drop-only)fmt_txn_preview / fmt_txn_result
waiver_claimwaiver <player> [--drop X] [--confirm-token T]waiver_claimfmt_txn_preview / fmt_txn_result
set_lineuplineup <player> <to_slot> [--swap-with X] [--confirm-token T]set_lineup_movesfmt_txn_preview / fmt_txn_result
propose_tradepropose-trade --to T --give "A,B" --receive "C" [--comment ...] [--confirm-token T]propose_tradefmt_txn_preview / fmt_txn_result
cancel_tradecancel-trade <transaction_id> [--confirm-token T]cancel_tradefmt_txn_preview / fmt_txn_result

Write tools live in mcp_server/writes/{roster,lineup,trades}.py and share the safety flow in mcp_server/writes/_base.py. The library methods accept dry_run=True (return the exact payload without POSTing) so the preview is byte-for-byte what executes.

Writes & Safety

Every mutation is a single POST to ESPN's lm-api-writes /transactions/ endpoint (see docs/writes/00-BRIEF.md for the verified payloads and docs/WRITES.md for the owner live-verification procedure). Two layers protect the live league:

  1. Env kill-switch — writes are refused unless ESPN_WRITE_ENABLED=true. With it off, the tools still appear (and explain how to enable) but never execute.
  2. Payload-bound confirm token — the first call returns a preview rendering the literal JSON body plus an 8-hex token derived from that body. Execution happens only when the caller echoes the exact token. If anything changes between preview and execute (player resolves differently, scoring period rolls over), the token no longer matches and a fresh preview is forced. Cache is invalidated after a successful write.

Adding a New Tool

  1. Add formatter function in formatters.py if new output formatting is needed.
  2. Add MCP tool in tools.py inside register_tools().
  3. Add @app.command() in cli/__init__.py.
  4. Update the tool mapping table above and in README.md.

Agent Workflows

When the user asks about their fantasy baseball league, use the MCP tools in this order:

  1. Situational awareness first — Start with get_standings and get_my_roster to understand the current state before making recommendations.
  2. Scouting — Use get_free_agents (filter by position if the user has a gap) and get_league_rosters to find trade targets.
  3. Evaluation — Use compare_players for head-to-head comparisons and analyze_trade before recommending any moves.
  4. Live games — Use get_matchup during the season to check the current week's H2H category breakdown. Use get_box_scores for a league-wide view.
  5. Refresh — Call refresh_data if the user says scores seem stale or asks for the latest.

The league uses H2H Categories (not points). Advice should focus on winning individual stat categories, not total points. When analyzing trades, consider category impact — not just point differential.

Draft Day Workflow

The league uses AUCTION draft ($280 budget per team). When assisting during draft:

  1. Start with context — Call get_scoring_categories + get_roster_slots to understand what categories matter and what positions need filling.
  2. Track the draft — Call refresh_data then get_draft_board to see picks so far, prices paid, and remaining budgets per team. Spot teams running low on cash.
  3. Know what you need — Call get_roster_needs to see which positions are still empty. Prioritize scarce positions (C, SS have only 1 slot each).
  4. Scout picks — Use get_free_agents filtered by needed positions and get_player_info / compare_players to evaluate targets.
  5. Value by category — Don't just rank by total points. The 14 categories are: AVG, HR, OPS, R, RBI, SB, B_SO (lower wins) | WHIP (lower wins), ERA (lower wins), K, W, L (lower wins), SV, HLD. Target players who help in categories you're weakest in.
  6. Budget strategy — With $280 and ~20 active slots, average cost is ~$14/player. Stars go for $40-60+. Track opponent budgets to know when you can win players cheaply late.

Building Plugin Bundles

# For Claude Cowork (requires deployed SSE URL)
uv run espn build-plugin build --target claude --url https://your-app.up.railway.app/sse

# For OpenClaw (local)
uv run espn build-plugin build --target openclaw

# Without memory server
uv run espn build-plugin build --target openclaw --no-memory

Gotchas

  • The espn_api baseball module uses H2H Categories scoring. Box scores have home_stats/away_stats dicts with per-category breakdowns — not simple point totals.
  • league.player_info() can return a single Player or a list. Always handle both cases.
  • league.free_agents() accepts position as a string (e.g., "SS"), not the numeric ESPN position ID.
  • The .mcp.json uses uv run — requires uv to be installed.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.