Skip to content

feat(mcp): add FastMCP server, agent tools, and documentation (#561) - #690

Open
ColinTWilliams wants to merge 4 commits into
swar:masterfrom
ColinTWilliams:feat/mcp-server
Open

feat(mcp): add FastMCP server, agent tools, and documentation (#561)#690
ColinTWilliams wants to merge 4 commits into
swar:masterfrom
ColinTWilliams:feat/mcp-server

Conversation

@ColinTWilliams

@ColinTWilliams ColinTWilliams commented Sep 4, 2026

Copy link
Copy Markdown

Summary

Hi Randy (@rsforbes) — following up on our discussion in #561 regarding adding Model Context Protocol (MCP) server support to nba_api!

This PR adds an official, lightweight FastMCP server and agent tools to nba_api, enabling AI coding assistants and LLMs (Claude Desktop, Cursor, Antigravity, Factory Droid, Windsurf, etc.) to query NBA statistics, play-type analytics, and shot tracking directly via the open Model Context Protocol standard.


Design & Architecture

  1. Zero Base Dependencies (Optional Extra):
    • Core nba_api users are completely unaffected.
    • MCP dependencies are isolated under [project.optional-dependencies] mcp = ["mcp>=1.2.0"].
    • Users install via:
      pip install "nba-api[mcp]"
  2. Standard Console Entrypoint:
    • Added [project.scripts] nba-mcp = "nba_api.mcp.server:main".
    • Users and AI clients can launch the server immediately with nba-mcp or python -m nba_api.mcp.server.
  3. SDK Compatibility (1.x & 2.x):
    • Handles both mcp.server.mcpserver.MCPServer (v2.x) and mcp.server.fastmcp.FastMCP (v1.x) gracefully.
  4. Resilience & Ergonomics:
    • Dynamic Season Resolution: Automatically resolves the current active season (_get_default_season()) so tools remain current without hardcoded year constants.
    • Diacritic Normalization: Accent-insensitive fuzzy matching (_strip_accents) handles international spellings seamlessly (e.g., "Luka Doncic" matches "Luka Dončić").
    • Payload Truncation Notice: Automatically alerts calling agents if a query hits NBA.com's 102,400 row ceiling on league-wide shot charts, advising how to get complete player stats or use tracking leaderboards.
    • 2PT / 3PT Action Splits: Provides explicit FG2A, FG2M, FG2_PCT, FG3A, FG3M, and FG3_PCT breakdowns in get_shot_chart_actions.
    • Smart Endpoint Argument Resolution: query_raw_endpoint auto-populates required positional parameters (team_id=0, player_id=0) and maps parameter aliases between standard names and _nullable variants (e.g., season -> season_nullable).
    • Timeout Resilience: Automatic retry wrapper (_call_with_retry) absorbs occasional NBA.com read timeouts and high-latency aggregation queries.
    • Deprecation-Safe: Uses ScoreboardV3 (avoiding ScoreboardV2 line score deprecations) and context_measure_simple='FGA' for ShotChartDetail (ensuring misses are captured alongside makes).

Exposed MCP Tools (10)

Tool Description
get_player_stats Career and season stats (per-game or totals) for any player.
get_player_gamelog Recent individual game logs for a player.
get_scoreboard Live/final scores, line scores, and game status for any date.
get_team_roster Active or historical roster with bio, position, and age.
get_synergy_play_types Synergy offensive/defensive play-type efficiency (P&R Ball Handler, Isolation, Post Up, Spot Up, Transition, etc.).
get_shot_tracking Second Spectrum tracking splits (Pullups, Catch & Shoot, dribbles, defender distance).
get_shot_chart_actions Physical shot mechanics (Step Back, Fadeaway, Pullup, Floater, Hook Shot).
get_advanced_stats True Shooting % (TS%), Usage Rate (USG%), Net Rating, PIE, AST%, REB%.
get_hustle_stats Deflections, Screen Assists, Charges Drawn, Loose Balls, Box Outs.
query_raw_endpoint General-purpose bridge to query any of the 130+ nba_api.stats.endpoints by class name.

Documentation & Skills

  • docs/mcp.md: Configuration guide for Claude Desktop (claude_desktop_config.json), Cursor (mcp.json), and CLI agents.
  • README.md & docs/table_of_contents.md: Linked to the new MCP documentation.
  • skills/nba-stats/: Included universal Agent Skill definition (SKILL.md) and reference guides (references/endpoints.md, references/recipes.md, references/gotchas.md).

Verification & Testing

  • Added comprehensive unit test suite in tests/unit/mcp/test_mcp_server.py verifying accent normalization, player/team resolution, tool registration, season calculation, shot chart 2PT/3PT breakdowns, truncation notices, and dynamic raw endpoint parameter defaults.
  • All 11 MCP unit tests pass (100%).
  • All 533 total repository unit tests continue to pass (pytest tests/unit).
  • Verified against CircleCI multi-Python matrix (Python 3.10, 3.11, 3.12, 3.13 all passing green).
  • Code formatted and validated with ruff check and ruff format adhering to the project's line-length = 88 and target-version = "py310" settings.

Implements official Model Context Protocol (MCP) server support for nba_api.
Exposes 10 specialized tools for LLMs and AI agents covering player stats,
game logs, live scoreboards, Synergy play types, Second Spectrum shot tracking,
shot mechanics, advanced metrics, hustle stats, and arbitrary raw endpoints.

Includes:
- Optional dependency 'mcp' in pyproject.toml (pip install 'nba-api[mcp]')
- Console script entrypoint
ba-mcp
- FastMCP / MCPServer backward and forward compatibility
- Diacritic/accent normalization for player search
- Documentation in docs/mcp.md and Agent Skills standard reference in skills/nba-stats
- Unit tests with 100% pass rate in tests/unit/mcp/test_mcp_server.py

Follow-up to discussion in Issue swar#561.
@ColinTWilliams
ColinTWilliams requested a review from swar as a code owner September 4, 2026 02:58
- Add mcp to [tool.poetry.group.dev.dependencies] so CI environments install it for pytest
- Synchronize poetry.lock with pyproject.toml changes to satisfy poetry install in CircleCI
- Add pytest.importorskip('mcp') in test_mcp_server.py for environments without mcp
@ColinTWilliams

ColinTWilliams commented Sep 4, 2026

Copy link
Copy Markdown
Author

full transparency Gemini 3.8 Flash wrote this PR because I wanted to test the model and Antigravity.

I did try out the MCP with good success though. here's an example of Gemini 3.8 Flash using the MCP to give an answer:

Prompt:

using shot tracking and play type data, where does ryan rollins rank in step-back 3 point shooting frequency and accuracy in 2025-2026 season league-wide using sensible rate cutoffs?

Response:

In the 2025–26 NBA regular season, Ryan Rollins emerged as one of the league's highest-volume and most efficient off-the-dribble shot creators for the Milwaukee Bucks.

Summary of Rankings & Metrics:
• Step-Back 3-Point Volume/Frequency: Across the full season, Rollins attempted 127 step-back 3-pointers (1.71 3PA/G), ranking top 10 league-wide in step-back 3PT frequency behind primary initiators like Luka Dončić, James Harden, and Donovan Mitchell.
• Step-Back 3-Point Accuracy: Converting 52 of 127 (40.9% 3P%), Rollins ranked number 4 league-wide among high-volume step-back shooters (min. 50 attempts), trailing only Shai Gilgeous-Alexander (45.0%), Jamal Murray (50.0%), and Stephen Curry (41.5%).
• Overall Pull-Up 3PT Profile: Pull-up 3s accounted for 42.3% of his total offensive shot diet (214 pull-up 3PA, converting at a 39.3% clip), complementing an 80th-percentile isolation efficiency (1.03 PPP).

for Rollins at least, I did a quick check to verify answers here: https://www.nba.com/stats/events?CF=SHOT_TYPE*R*3:ACTION_TYPE*E*step%20back:EVENT_TYPE*E*Made&CFID=&CFPARAMS=&ContextMeasure=FGA&PlayerID=1631157&Season=2025-26&SeasonType=Regular%20Season&TeamID=1610612749&flag=3&sct=plot&section=playe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant