A FastMCP server that provides health monitoring, web content extraction, NFL news fetching, NFL teams information, and comprehensive fantasy league management through both REST and MCP protocols.
- Health Endpoint: Non-MCP REST endpoint at
/healthfor monitoring server status - URL Crawling Tool: MCP tool that crawls arbitrary URLs and extracts LLM-friendly text content
- NFL News Tool: MCP tool that fetches the latest NFL news from ESPN API
- NFL Teams Tools: Comprehensive MCP tools for NFL teams including:
- Team data fetching and database caching from ESPN API
- Depth chart retrieval for individual teams
- Fantasy Intelligence APIs: Advanced MCP tools for fantasy football decision making:
- Injury Reports: Real-time injury status for start/sit decisions
- Player Performance Stats: Team player statistics and fantasy relevance indicators
- NFL Standings: League standings with playoff implications and team motivation context
- Team Schedules: Matchup analysis with fantasy implications and strength of schedule
- CBS Fantasy Football Tools: MCP tools for fetching CBS Sports fantasy content:
- Player News: Latest fantasy football player news and updates
- Projections: Weekly player projections by position with customizable scoring formats
- Expert Picks: NFL expert picks against the spread for informed betting and fantasy decisions
- Athlete Tools: MCP tools for fetching, caching, and looking up NFL athletes from Sleeper API with SQLite persistence
- Sleeper API Tools: Comprehensive MCP tools for fantasy league management including:
- League information, rosters, users, matchups, playoff brackets
- Transactions, traded picks, NFL state, trending players
- Flexible Configuration: Environment variables and configuration files (YAML/JSON) with hot-reloading
- HTTP Transport: Runs on HTTP transport protocol (default port 9000)
- Containerized: Docker support for easy deployment
- Well Tested: Comprehensive unit tests for all functionality
- Python 3.9 or higher
- Docker (optional, for containerized deployment)
- Task (optional, for using Taskfile commands)
- Clone the repository:
git clone https://github.com/gtonic/nfl_mcp.git
cd nfl_mcp- Install dependencies:
pip install -r requirements.txt
pip install -e ".[dev]"python -m nfl_mcp.server# Build and run
docker build -t nfl-mcp-server .
docker run --rm -p 9000:9000 nfl-mcp-server# Install task: https://taskfile.dev/installation/
task run # Run locally
task run-docker # Run in Docker
task all # Complete pipelineThe NFL MCP Server supports flexible configuration through environment variables and configuration files.
# Set custom timeouts and limits
export NFL_MCP_TIMEOUT_TOTAL=45.0
export NFL_MCP_NFL_NEWS_MAX=75
export NFL_MCP_SERVER_VERSION="1.0.0"
# Advanced enrichment and prefetch (optional)
export NFL_MCP_ADVANCED_ENRICH=1 # Enable snap%, opponent, practice status, usage metrics
export NFL_MCP_PREFETCH=1 # Enable background data prefetch
export NFL_MCP_PREFETCH_INTERVAL=900 # Prefetch interval in seconds (default: 900 = 15 min)
export NFL_MCP_PREFETCH_SNAPS_TTL=1800 # Snap data TTL in seconds (default: 1800 = 30 min)
export NFL_MCP_PREFETCH_SCHEDULE_WEEKS=4 # Number of weeks to prefetch schedules for (default: 4)
# Logging configuration (optional)
export NFL_MCP_LOG_LEVEL=INFO # Log level: DEBUG, INFO, WARNING, ERROR, CRITICAL (default: INFO)
# Run the server
python -m nfl_mcp.serverNote: Logging is enabled at INFO level by default, providing comprehensive tracking of prefetch operations, enrichment activity, and API calls.
timeout:
total: 45.0
connect: 15.0
limits:
nfl_news_max: 75
athletes_search_max: 150
rate_limits:
default_requests_per_minute: 120
security:
max_string_length: 2000docker run --rm -p 9000:9000 \
-e NFL_MCP_TIMEOUT_TOTAL=45.0 \
-e NFL_MCP_RATE_LIMIT_DEFAULT=120 \
-e NFL_MCP_ADVANCED_ENRICH=1 \
-e NFL_MCP_PREFETCH=1 \
-e NFL_MCP_LOG_LEVEL=INFO \
nfl-mcp-server📋 AI/LLM Integration Guide - Comprehensive MCP tool reference and integration guide optimized for LLM understanding
The NFL MCP Server provides 30+ MCP tools organized into these categories:
get_nfl_news- Latest NFL news from ESPNget_teams- All NFL team informationfetch_teams- Cache teams in databaseget_depth_chart- Team roster/depth chartget_team_injuries- Injury reports by teamget_team_player_stats- Team player statisticsget_nfl_standings- Current NFL standingsget_team_schedule- Team schedules with fantasy contextget_league_leaders- NFL statistical leaders by category
get_cbs_player_news- Latest fantasy football player news from CBS Sportsget_cbs_projections- Fantasy projections by position and week from CBS Sportsget_cbs_expert_picks- NFL expert picks against the spread from CBS Sports
fetch_athletes- Import all NFL players (expensive, use sparingly)lookup_athlete- Find player by IDsearch_athletes- Search players by nameget_athletes_by_team- Get team roster
crawl_url- Extract text from any webpage
- Core League:
get_league,get_rosters,get_league_users - Match / Brackets:
get_matchups,get_playoff_bracket(now supports winners|losers via bracket_type) - Activity & Assets:
get_transactions(week required),get_traded_picks - Draft Data:
get_league_drafts,get_draft,get_draft_picks,get_draft_traded_picks - Global / Meta:
get_nfl_state,get_trending_players,fetch_all_players(large players map w/ caching)
- Matchup Analysis:
get_defense_rankings,get_matchup_difficulty,analyze_roster_matchups - Start/Sit Recommendations:
get_start_sit_recommendation,get_roster_recommendations,compare_players_for_slot,analyze_full_lineup - Vegas Lines:
get_vegas_lines,get_game_environment,analyze_roster_vegas,get_stack_opportunities
- GET
/health- Server status monitoring
For LLMs: The AI/LLM Integration Guide includes:
- 🎯 When to use each tool - Decision matrix for tool selection
- 📊 Parameter validation - Input constraints and validation rules
- 💡 Usage patterns - Common workflows and examples
- ⚡ Performance notes - Which tools are expensive vs. fast
- 🛡️ Error handling - Consistent error response patterns
from fastmcp import Client
async with Client("http://localhost:9000/mcp/") as client:
# Get latest NFL news
news = await client.call_tool("get_nfl_news", {"limit": 5})
# Search for a player
player = await client.call_tool("search_athletes", {"name": "Mahomes"})
# Get team depth chart
depth = await client.call_tool("get_depth_chart", {"team_id": "KC"})Recent upgrades to Sleeper tooling:
- Added losers bracket support:
get_playoff_bracket(league_id, bracket_type="losers") - Enforced explicit week for
get_transactions(or alias round) to match official API - Trending players now preserves Sleeper-provided
countand enriches with local athlete data underenriched - Added draft suite (
get_league_drafts,get_draft,get_draft_picks,get_draft_traded_picks) - Added full players dataset endpoint
fetch_all_playerswith 12h in-memory TTL (returns metadata, not massive map) - Added enrichment across core endpoints (rosters, matchups, transactions, traded picks, draft picks, trending)
- Automatic week inference for
get_transactions(addsauto_week_inferred) - Aggregator endpoint
get_fantasy_contextto batch league core data (optionalinclude) - Introduced central param validator utility (
param_validator.py) for future consolidation - Robustness layer (retry + snapshot fallback) for:
get_rosters,get_transactions,get_matchups - Snapshot metadata fields now returned:
retries_used: number of retry attempts consumedstale: indicates if served data came from a snapshot beyond freshness TTLfailure_reason: last encountered failure code/categorysnapshot_fetched_at,snapshot_age_seconds: present when snapshot used (or null on fresh)
New optional fields may appear within players_enriched, starters_enriched, and transaction add/drop enrichment objects:
| Field | Description | Source Values |
|---|---|---|
snap_pct |
Offensive snap percentage for the current week (float, one decimal) | Derived or cached |
snap_pct_source |
Provenance for snap_pct |
cached, estimated |
opponent |
Opponent team abbreviation (for DEF entries) | Schedule cache |
opponent_source |
Provenance for opponent |
cached, fetched |
Notes:
- Estimated snap% uses depth-chart heuristics (starter≈70, #2≈45, others≈15) when real stats absent.
- All fields are additive and may be absent without breaking existing consumers.
Additional practice status & usage metrics (requires NFL_MCP_ADVANCED_ENRICH=1):
| Field | Description | Values/Format |
|---|---|---|
practice_status |
Latest injury practice designation | DNP, LP, FP, Full |
practice_status_date |
Date of practice report | ISO date (YYYY-MM-DD) |
practice_status_age_hours |
Age of practice report in hours | Float (1 decimal) |
practice_status_stale |
Report older than 72h | Boolean |
usage_last_3_weeks |
Avg usage metrics (WR/RB/TE only) | Object (see below) |
usage_source |
Provenance for usage data | sleeper, estimated |
usage_trend |
Trend analysis per metric (WR/RB/TE) | Object (see below) |
usage_trend_overall |
Overall usage trend direction | up, down, flat |
Usage Object Fields:
targets_avg: Average targets per game (1 decimal)routes_avg: Average routes run per game (1 decimal)rz_touches_avg: Average red zone touches per game (1 decimal)snap_share_avg: Average snap share percentage (1 decimal)weeks_sample: Number of weeks in sample (1-3)
Usage Trend Object Fields:
targets: Trend for targets (up/down/flat)routes: Trend for routes run (up/down/flat)snap_share: Trend for snap percentage (up/down/flat)
Notes:
- Practice status helps identify injury risk (DNP = high risk, LP = moderate, FP/Full = low)
- Usage metrics provide true volume indicators beyond depth chart position
- Trend calculation compares most recent week vs prior weeks (15% threshold)
- Trend "up" (↑) = rising usage, "down" (↓) = declining usage, "flat" (→) = stable usage
- All fields are additive; absent fields mean data unavailable
Each robust endpoint attempts multiple fetches with backoff. If all fail, the server returns the most recent cached snapshot with success=false but still provides usable data so LLM workflows can continue gracefully. Always check:
For fresh successful responses the snapshot fields are present with null values (allowing uniform downstream parsing).
get_fantasy_context(league_id="12345", include="league,rosters,matchups")
If week omitted it will be inferred from NFL state. Response includes week and auto_week_inferred.
Calling get_transactions(league_id) without week now attempts inference; falls back to validation error only if NFL state unavailable.
Simplified Design (v2.0):
- ✅ Single Tool Registry - All tools defined in one place
- ✅ 92% Code Reduction - Server simplified from 766 to 59 lines
- ✅ Zero Duplication - Eliminated redundant tool definitions
- ✅ Clean Dependencies - Straightforward import structure
GET /health
Returns server health status.
Response:
{
"status": "healthy",
"service": "NFL MCP Server",
"version": "0.1.0"
}Tool Name: get_nfl_news
Fetches the latest NFL news from ESPN API and returns structured news data.
Parameters:
limit(integer, optional): Maximum number of news articles to retrieve (default: 50, max: 50)
Returns: Dictionary with the following fields:
articles: List of news articles with headlines, descriptions, published dates, etc.total_articles: Number of articles returnedsuccess: Whether the request was successfulerror: Error message (if any)
Example Usage with MCP Client:
from fastmcp import Client
async with Client("http://localhost:9000/mcp/") as client:
result = await client.call_tool("get_nfl_news", {"limit": 10})
if result.data["success"]:
print(f"Found {result.data['total_articles']} articles")
for article in result.data["articles"]:
print(f"- {article['headline']}")
print(f" Published: {article['published']}")
else:
print(f"Error: {result.data['error']}")Article Structure:
Each article in the articles list contains:
headline: Article headlinedescription: Brief description/summarypublished: Publication date/timetype: Article type (Story, News, etc.)story: Full story contentcategories: List of category descriptionslinks: Associated links (web, mobile, etc.)
Tools: get_teams, fetch_teams, get_depth_chart
These tools provide comprehensive NFL teams data management with database caching and depth chart access.
Fetches all NFL teams from ESPN API and returns structured team data.
Parameters: None
Returns: Dictionary with the following fields:
teams: List of teams with comprehensive team informationtotal_teams: Number of teams returnedsuccess: Whether the request was successfulerror: Error message (if any)
Fetches all NFL teams from ESPN API and stores them in the local database for caching.
Parameters: None
Returns: Dictionary with the following fields:
teams_count: Number of teams processed and storedlast_updated: Timestamp of the updatesuccess: Whether the fetch was successfulerror: Error message (if any)
Fetches the depth chart for a specific NFL team from ESPN.
Parameters:
team_id: Team abbreviation (e.g., 'KC', 'TB', 'NE')
Returns: Dictionary with the following fields:
team_id: The team identifier usedteam_name: The team's full namedepth_chart: List of positions with players in depth ordersuccess: Whether the request was successfulerror: Error message (if any)
Example Usage with MCP Client:
from fastmcp import Client
async with Client("http://localhost:9000/mcp/") as client:
# Get all teams
result = await client.call_tool("get_teams", {})
for team in result.data["teams"]:
print(f"- {team['displayName']} ({team['abbreviation']})")
# Fetch and cache teams data
result = await client.call_tool("fetch_teams", {})
print(f"Cached {result.data['teams_count']} teams")
# Get depth chart for Kansas City Chiefs
result = await client.call_tool("get_depth_chart", {"team_id": "KC"})
print(f"Depth chart for {result.data['team_name']}:")
for position in result.data['depth_chart']:
print(f" {position['position']}: {', '.join(position['players'])}")Team Structure:
Each team in the teams list contains:
id: Unique team identifiername: Team name
Tools: get_team_injuries, get_team_player_stats, get_nfl_standings, get_team_schedule
These advanced tools provide critical fantasy football intelligence for making informed decisions about lineups, waiver wire pickups, and long-term strategy.
Fetches real-time injury reports for a specific NFL team from ESPN's Core API.
Parameters:
team_id: Team abbreviation (e.g., 'KC', 'TB', 'NE')limit: Maximum number of injuries to return (1-100, defaults to 50)
Returns: Dictionary with the following fields:
team_id: The team identifier usedteam_name: The team's full nameinjuries: List of injured players with status and fantasy severitycount: Number of injuries returnedsuccess: Whether the request was successfulerror: Error message (if any)
Injury Structure: Each injury contains:
player_name: Player's full nameposition: Player's position (QB, RB, WR, etc.)status: Injury status (Out, Questionable, Doubtful, etc.)severity: Fantasy impact level (High, Medium, Low)description: Injury descriptiontype: Type of injury
Fetches player statistics and fantasy relevance for a specific NFL team.
Parameters:
team_id: Team abbreviation (e.g., 'KC', 'TB', 'NE')season: Season year (defaults to 2025)season_type: 1=Pre, 2=Regular, 3=Post, 4=Off (defaults to 2)limit: Maximum number of players to return (1-100, defaults to 50)
Returns: Dictionary with the following fields:
team_id: The team identifier usedteam_name: The team's full nameseason: Season year requestedseason_type: Season type requestedplayer_stats: List of players with performance datacount: Number of players returnedsuccess: Whether the request was successfulerror: Error message (if any)
Player Stats Structure: Each player contains:
player_name: Player's full nameposition: Player's positionfantasy_relevant: Boolean indicating fantasy football relevancejersey: Jersey numberage: Player's ageexperience: Years of NFL experience
Fetches current NFL standings with fantasy context about team motivation and playoff implications.
Parameters:
season: Season year (defaults to 2025)season_type: 1=Pre, 2=Regular, 3=Post, 4=Off (defaults to 2)group: Conference group (1=AFC, 2=NFC, None=both, defaults to None)
Returns: Dictionary with the following fields:
standings: List of teams with records and fantasy contextseason: Season year requestedseason_type: Season type requestedgroup: Conference group requestedcount: Number of teams returnedsuccess: Whether the request was successfulerror: Error message (if any)
Standings Structure: Each team contains:
team_name: Team's full nameabbreviation: Team abbreviationwins: Number of winslosses: Number of lossesmotivation_level: Team motivation for fantasy purposes (High/Medium/Low)fantasy_context: Description of potential player usage implications
Fetches team schedule with matchup analysis and fantasy implications.
Parameters:
team_id: Team abbreviation (e.g., 'KC', 'TB', 'NE')season: Season year (defaults to 2025)
Returns: Dictionary with the following fields:
team_id: The team identifier usedteam_name: The team's full nameseason: Season year requestedschedule: List of games with matchup detailscount: Number of games returnedsuccess: Whether the request was successfulerror: Error message (if any)
Schedule Structure: Each game contains:
date: Game date and timeweek: Week numberseason_type: Season type (Regular Season, Playoffs, etc.)opponent: Opponent team informationis_home: Boolean indicating if it's a home gameresult: Game result (win/loss/scheduled)fantasy_implications: List of fantasy-relevant insights for the matchup
Tools: fetch_athletes, lookup_athlete, search_athletes, get_athletes_by_team
These tools provide comprehensive athlete data management with SQLite-based caching.
Fetches all NFL players from Sleeper API and stores them in the local SQLite database.
Parameters: None
Returns: Dictionary with athlete count, last updated timestamp, success status, and error (if any)
Look up an athlete by their unique ID.
Parameters:
athlete_id: The unique identifier for the athlete
Returns: Dictionary with athlete information, found status, and error (if any)
Search for athletes by name (supports partial matches).
Parameters:
name: Name or partial name to search forlimit: Maximum number of results (default: 10, max: 100)
Returns: Dictionary with matching athletes, count, search term, and error (if any)
Get all athletes for a specific team.
Parameters:
team_id: The team identifier (e.g., "SF", "KC", "NE")
Returns: Dictionary with team athletes, count, team ID, and error (if any)
Example Usage with MCP Client:
from fastmcp import Client
async with Client("http://localhost:9000/mcp/") as client:
# Fetch and cache all athletes
result = await client.call_tool("fetch_athletes", {})
print(f"Cached {result.data['athletes_count']} athletes")
# Look up specific athlete
result = await client.call_tool("lookup_athlete", {"athlete_id": "2307"})
if result.data["found"]:
print(f"Found: {result.data['athlete']['full_name']}")
# Search by name
result = await client.call_tool("search_athletes", {"name": "Mahomes"})
for athlete in result.data["athletes"]:
print(f"- {athlete['full_name']} ({athlete['position']})")
# Get team roster
result = await client.call_tool("get_athletes_by_team", {"team_id": "KC"})
print(f"KC has {result.data['count']} players")Tool Name: crawl_url
Crawls a URL and extracts its text content in a format understandable by LLMs.
Parameters:
url(string): The URL to crawl (must include http:// or https://)max_length(integer, optional): Maximum length of extracted text (default: 10000 characters)
Returns: Dictionary with the following fields:
url: The crawled URLtitle: Page title (if available)content: Cleaned text contentcontent_length: Length of extracted contentsuccess: Whether the crawl was successfulerror: Error message (if any)
Example Usage with MCP Client:
from fastmcp import Client
async with Client("http://localhost:9000/mcp/") as client:
result = await client.call_tool("crawl_url", {
"url": "https://example.com",
"max_length": 1000
})
if result.data["success"]:
print(f"Title: {result.data['title']}")
print(f"Content: {result.data['content']}")
else:
print(f"Error: {result.data['error']}")Features:
- Automatically extracts and cleans text content from HTML
- Removes scripts, styles, navigation, and footer elements
- Normalizes whitespace and formats text for LLM consumption
- Handles various error conditions (timeouts, HTTP errors, etc.)
- Configurable content length limiting
- Follows redirects automatically
- Sets appropriate User-Agent header
Tools: get_cbs_player_news, get_cbs_projections, get_cbs_expert_picks
These tools provide access to CBS Sports Fantasy Football content including player news, weekly projections, and expert picks.
Fetch the latest fantasy football player news from CBS Sports.
Parameters:
limit(integer, optional): Maximum number of news items to retrieve (default: 50, max: 100)
Returns: Dictionary with the following fields:
news: List of player news items with headlines, players, descriptionstotal_news: Number of news items returnedsource: Data source identifiersuccess: Whether the request was successfulerror: Error message (if any)
News Item Structure:
Each news item in the news list may contain:
player: Player nameheadline: News headlinedescription: Detailed news descriptionpublished: Publication timestampposition: Player position (QB, RB, WR, etc.)team: Team abbreviation
Fetch fantasy football projections from CBS Sports for a specific position and week.
Parameters:
position(string, required): Player position - QB, RB, WR, TE, K, or DST (default: QB)week(integer, required): NFL week number (1-18)season(integer, optional): Season year (default: 2025)scoring(string, optional): Scoring format - ppr, half-ppr, or standard (default: ppr)
Returns: Dictionary with the following fields:
projections: List of player projections with statistical predictionstotal_projections: Number of projections returnedweek: Week number requestedposition: Position filteredseason: Season yearscoring: Scoring format usedsource: Data source identifiersuccess: Whether the request was successfulerror: Error message (if any)
Projection Structure:
Each projection in the projections list contains:
player_name: Player's full nameplayer_url: Link to player page (if available)- Additional statistical fields varying by position (passing yards, touchdowns, receptions, etc.)
Fetch NFL expert picks against the spread from CBS Sports for a specific week.
Parameters:
week(integer, required): NFL week number (1-18)
Returns: Dictionary with the following fields:
picks: List of expert picks with game matchups and predictionstotal_picks: Number of picks returnedweek: Week number requestedsource: Data source identifiersuccess: Whether the request was successfulerror: Error message (if any)
Pick Structure:
Each pick in the picks list contains:
matchup: Game matchup descriptionaway_team: Away team name (if available)home_team: Home team name (if available)experts: List of expert predictionsexpert: Individual expert name (alternative format)prediction: Expert's prediction (alternative format)
Example Usage with MCP Client:
from fastmcp import Client
async with Client("http://localhost:9000/mcp/") as client:
# Get latest CBS player news
result = await client.call_tool("get_cbs_player_news", {"limit": 20})
if result.data["success"]:
print(f"Found {result.data['total_news']} news items")
for news in result.data["news"]:
if news.get('headline'):
print(f"- {news.get('player', 'Unknown')}: {news['headline']}")
# Get QB projections for week 11
result = await client.call_tool("get_cbs_projections", {
"position": "QB",
"week": 11,
"season": 2025,
"scoring": "ppr"
})
if result.data["success"]:
print(f"Found {result.data['total_projections']} QB projections for week 11")
for proj in result.data["projections"][:5]:
print(f"- {proj.get('player_name', 'Unknown')}")
# Get expert picks for week 10
result = await client.call_tool("get_cbs_expert_picks", {"week": 10})
if result.data["success"]:
print(f"Found {result.data['total_picks']} expert picks for week 10")
for pick in result.data["picks"][:3]:
print(f"- {pick.get('matchup', 'Unknown matchup')}")Basic Tools: get_league, get_rosters, get_league_users, get_matchups, get_playoff_bracket, get_transactions, get_traded_picks, get_nfl_state, get_trending_players
Strategic Tools: get_strategic_matchup_preview, get_season_bye_week_coordination, get_trade_deadline_analysis, get_playoff_preparation_plan
Analysis Tools: analyze_opponent - Opponent roster weakness analysis and exploitation strategies
Tools: get_waiver_log, check_re_entry_status, get_waiver_wire_dashboard
These advanced tools provide enhanced waiver wire intelligence for fantasy football decision making, addressing common issues like duplicate transaction tracking and identifying volatile players.
These tools provide comprehensive fantasy league management by connecting to the Sleeper API.
Get detailed information about a specific fantasy league.
Parameters:
league_id(string): The unique identifier for the league
Returns: Dictionary with league information, success status, and error (if any)
Get all rosters in a fantasy league.
Parameters:
league_id(string): The unique identifier for the league
Returns: Dictionary with rosters list, count, success status, and error (if any)
Get all users/managers in a fantasy league.
Parameters:
league_id(string): The unique identifier for the league
Returns: Dictionary with users list, count, success status, and error (if any)
Get matchups for a specific week in a fantasy league.
Parameters:
league_id(string): The unique identifier for the leagueweek(integer): Week number (1-22)
Returns: Dictionary with matchups list, week, count, success status, and error (if any)
Get playoff bracket information for a fantasy league.
Parameters:
league_id(string): The unique identifier for the league
Returns: Dictionary with bracket information, success status, and error (if any)
Get transactions for a fantasy league.
Parameters:
league_id(string): The unique identifier for the leagueround(integer, optional): Round number (1-18, omit for all transactions)
Returns: Dictionary with transactions list, round, count, success status, and error (if any)
Get traded draft picks for a fantasy league.
Parameters:
league_id(string): The unique identifier for the league
Returns: Dictionary with traded picks list, count, success status, and error (if any)
Get current NFL state information.
Parameters: None
Returns: Dictionary with NFL state information, success status, and error (if any)
Get trending players from fantasy leagues.
Parameters:
trend_type(string, optional): "add" or "drop" (default: "add")lookback_hours(integer, optional): Hours to look back (1-168, default: 24)limit(integer, optional): Maximum results (1-100, default: 25)
Returns: Dictionary with trending players list, parameters, count, success status, and error (if any)
Strategic preview of upcoming matchups for multi-week planning. Combines Sleeper league data with NFL schedules to identify bye weeks, challenging periods, and opportunities 4-8 weeks ahead.
Parameters:
league_id(string): The unique identifier for the leaguecurrent_week(integer): Current NFL week (1-22)weeks_ahead(integer, optional): Weeks to analyze ahead (1-8, default: 4)
Returns: Dictionary with strategic analysis including bye week alerts, opportunity windows, and trade recommendations
Season-long bye week coordination with fantasy league schedule. Analyzes entire NFL bye week calendar against your league's playoff schedule for strategic roster planning.
Parameters:
league_id(string): The unique identifier for the leagueseason(integer, optional): NFL season year (default: 2025)
Returns: Dictionary with coordination plan including bye week calendar, strategic periods, and timing recommendations
Strategic trade deadline timing analysis. Evaluates optimal trade timing by analyzing upcoming bye weeks, playoff schedules, and league patterns.
Parameters:
league_id(string): The unique identifier for the leaguecurrent_week(integer): Current NFL week for timeline analysis
Returns: Dictionary with trade analysis including timing windows, urgency factors, and strategic recommendations
Comprehensive playoff preparation plan combining league and NFL data. Provides detailed preparation strategy including roster optimization and readiness assessment.
Parameters:
league_id(string): The unique identifier for the leaguecurrent_week(integer): Current NFL week for timeline analysis
Returns: Dictionary with playoff plan, strategic priorities, NFL schedule insights, and readiness score (0-100)
Get waiver wire log with optional de-duplication.
Parameters:
league_id(string): The unique identifier for the leagueround(integer, optional): Round number (1-18, omit for all transactions)dedupe(boolean, optional): Enable de-duplication (default: true)
Returns: Dictionary with waiver log, duplicates found, transaction counts, success status, and error (if any)
Check re-entry status for players (dropped then re-added).
Parameters:
league_id(string): The unique identifier for the leagueround(integer, optional): Round number (1-18, omit for all transactions)
Returns: Dictionary with re-entry analysis, volatile players list, player counts, success status, and error (if any)
Get comprehensive waiver wire dashboard with analysis.
Parameters:
league_id(string): The unique identifier for the leagueround(integer, optional): Round number (1-18, omit for all transactions)
Returns: Dictionary with waiver log, re-entry analysis, dashboard summary, volatile players, success status, and error (if any)
Example Usage with MCP Client:
from fastmcp import Client
async with Client("http://localhost:9000/mcp/") as client:
# Get NFL state
result = await client.call_tool("get_nfl_state", {})
print(f"Current NFL week: {result.data['nfl_state']['week']}")
# Get trending players
result = await client.call_tool("get_trending_players", {
"trend_type": "add",
"limit": 10
})
print(f"Found {result.data['count']} trending players")
# Get league information (requires valid league_id)
result = await client.call_tool("get_league", {"league_id": "your_league_id"})
if result.data["success"]:
print(f"League: {result.data['league']['name']}")
# Strategic planning - Preview upcoming challenges
result = await client.call_tool("get_strategic_matchup_preview", {
"league_id": "your_league_id",
"current_week": 8,
"weeks_ahead": 6
})
if result.data["success"]:
critical_byes = result.data["strategic_preview"]["summary"]["critical_bye_weeks"]
print(f"Critical bye weeks coming: {len(critical_byes)}")
# Strategic planning - Trade deadline analysis
result = await client.call_tool("get_trade_deadline_analysis", {
"league_id": "your_league_id",
"current_week": 11
})
if result.data["success"]:
phase = result.data["trade_analysis"]["strategic_windows"]["current_phase"]
urgency = result.data["trade_analysis"]["strategic_windows"]["urgency"]
print(f"Trade strategy: {phase} ({urgency} urgency)")
# Strategic planning - Playoff preparation
result = await client.call_tool("get_playoff_preparation_plan", {
"league_id": "your_league_id",
"current_week": 12
})
if result.data["success"]:
score = result.data["readiness_score"]
phase = result.data["playoff_plan"]["preparation_phases"]["current_phase"]["name"]
print(f"Playoff readiness: {score}/100 ({phase})")Tool: analyze_opponent
This advanced tool provides comprehensive opponent roster analysis for fantasy football matchup preparation.
Analyze an opponent's roster to identify weaknesses and exploitation opportunities.
Parameters:
league_id(string): The unique identifier for the fantasy leagueopponent_roster_id(integer): Roster ID of the opponent to analyzecurrent_week(integer, optional): Current NFL week for matchup context
Returns: Dictionary with the following fields:
vulnerability_score: Overall opponent weakness score (0-100, higher = more vulnerable)vulnerability_level: Classification (high, moderate, low)position_assessments: Detailed assessment by position including:strength_score: Position group strength (0-100)depth_count: Number of players at positionaverage_snap_pct: Average snap percentageinjury_concerns: Count of injured playersusage_concerns: Count of players with declining usageweakness_level: Classification (strong, moderate, weak, critical)concerns: List of specific concerns
starter_weaknesses: Specific weaknesses in starting lineup with:player_id,player_name,positionweaknesses: List of weakness descriptionsseverity: High, moderate, or low
exploitation_strategies: Prioritized recommendations including:category: Type of strategy (position_weakness, starter_vulnerability)position: Position to targetpriority: Critical, high, moderaterecommendation: Strategic advicedetails: Supporting informationaction_items: Specific actions to take
matchup_context: Optional matchup information if current_week providedopponent_name: Display name of opponent (if available)success: Whether the analysis was successfulerror: Error message (if any)
Features:
- Position Strength Assessment: Evaluates each position group (QB, RB, WR, TE, K, DEF) based on depth, snap percentage, injury status, and usage trends
- Injury Analysis: Identifies players with practice status concerns (DNP, LP)
- Usage Trend Detection: Flags declining usage patterns that indicate player vulnerability
- Strategic Recommendations: Generates prioritized exploitation strategies based on identified weaknesses
- Matchup Context: Optional integration with current week matchup data
Example Usage with MCP Client:
from fastmcp import Client
async with Client("http://localhost:9000/mcp/") as client:
# Analyze opponent roster for current matchup
result = await client.call_tool("analyze_opponent", {
"league_id": "your_league_id",
"opponent_roster_id": 2,
"current_week": 10
})
if result.data["success"]:
print(f"Opponent: {result.data['opponent_name']}")
print(f"Vulnerability Score: {result.data['vulnerability_score']}/100")
print(f"Level: {result.data['vulnerability_level']}")
# Show position weaknesses
for position, assessment in result.data["position_assessments"].items():
if assessment["weakness_level"] in ["weak", "critical"]:
print(f"\n{position} Position - {assessment['weakness_level'].upper()}:")
print(f" Strength Score: {assessment['strength_score']}")
for concern in assessment['concerns']:
print(f" - {concern}")
# Show starter vulnerabilities
print("\nStarter Weaknesses:")
for weakness in result.data["starter_weaknesses"]:
print(f" {weakness['player_name']} ({weakness['position']}) - {weakness['severity']}:")
for w in weakness['weaknesses']:
print(f" - {w}")
# Show exploitation strategies
print("\nExploitation Strategies:")
for strategy in result.data["exploitation_strategies"][:3]:
print(f"\n [{strategy['priority'].upper()}] {strategy['recommendation']}")
for action in strategy['action_items']:
print(f" • {action}")Use Cases:
- Weekly Matchup Preparation: Identify opponent weaknesses before your matchup
- Lineup Decisions: Decide which players to start based on opponent vulnerabilities
- Waiver Wire Strategy: Prioritize pickups that exploit opponent position weaknesses
- Trade Targeting: Identify opponents who need help at positions where you have depth
pytest tests/ -v --cov=nfl_mcp --cov-report=term-missingnfl_mcp/
├── nfl_mcp/ # Main package
│ ├── __init__.py
│ ├── server.py # FastMCP server implementation
│ ├── database.py # SQLite database management
│ └── config.py # Shared configuration and utilities
├── tests/ # Unit tests
│ ├── __init__.py
│ └── test_server.py
├── Dockerfile # Container definition
├── Taskfile.yml # Task automation
├── pyproject.toml # Project configuration
├── requirements.txt # Dependencies
└── README.md
Run task --list to see all available tasks:
task install- Install dependenciestask test- Run unit tests with coveragetask run- Run server locallytask build- Build Docker imagetask run-docker- Build and run in Dockertask health-check- Check server healthtask clean- Clean up Docker resources
This server implements several security measures:
- Enhanced Input Validation:
- String inputs are validated against injection patterns (SQL, XSS, command injection)
- Numeric parameters have type checking and range validation
- URL validation includes private network blocking and dangerous pattern detection
- Content Sanitization: Web crawled content is sanitized to remove scripts and dangerous patterns
- URL Security: Only HTTP/HTTPS URLs are allowed with additional security checks
- Request Timeouts: All HTTP requests have reasonable timeout limits (30s total, 10s connect)
- User-Agent Headers: All requests are properly identified
- SQL Injection Prevention: All database queries use parameterized statements
- Rate Limiting: Built-in rate limiting utilities to prevent abuse
- No Code Execution: The server does not execute arbitrary code or eval statements
Input Validation Features:
- SQL injection pattern detection and prevention
- XSS injection pattern detection and prevention
- Command injection pattern detection and prevention
- Path traversal pattern detection and prevention
- HTML content sanitization with script removal
- Team ID, League ID, and other parameter format validation
- Safe character pattern matching for different input types
Rate Limiting:
- Configurable per-endpoint rate limiting
- In-memory storage for development (Redis recommended for production)
- Customizable limits and time windows
- Rate limit status reporting
When deploying in production:
- Run in a containerized environment
- Use proper network security controls
- Implement persistent rate limiting with Redis or similar
- Monitor for unusual request patterns
- Keep dependencies updated
- Consider additional WAF (Web Application Firewall) protection
MIT License - see LICENSE file for details.
{ "success": false, "stale": true, "retries_used": 3, "failure_reason": "timeout", "snapshot_fetched_at": "2025-09-13T11:22:33Z", "snapshot_age_seconds": 642 }