logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

trakt-media-connector

Interface with the Trakt.tv API to access current entertainment metadata, track personal viewing logs, facilitate content discovery, and generate tailored media suggestions for AI agents.

Author

trakt-media-connector logo

wwiens

No License

Quick Info

GitHub GitHub Stars 10
NPM Weekly Downloads 0
Tools 1
Last Updated 2026-02-19

Tags

apisapitrakttrakt apitrakt_mcpserver accesswwiens trakt_mcpserver

📺 AI Conduit for Trakt Ecosystem Data

Connector Status Development Environment AI Engine

This Model Context Protocol (MCP) server establishes a crucial communication channel between large language models (LLMs) and the comprehensive Trakt.tv web service. It furnishes LLMs with the capability to query live catalog information and retrieve individual user consumption histories.

Engineered via the FastMCP framework, the architecture enforces rigorous domain separation across critical domains: user authentication, media inventory management (shows/movies), behavioral tracking, social feedback mechanisms, data retrieval, and session check-in functionality.

🧑‍💻 An AI-Driven Prototype

Except for this introductory section, the entirety of this component—documentation and underlying code logic—was synthesized by artificial intelligence. This endeavor was motivated by a desire to explore MCP integration alongside advanced tooling within the Cursor IDE, resulting in this specialized data bridge.

🧠 Understanding MCP

Model Context Protocol (MCP) is an established open standard designed to permit LLMs, such as Claude, secure and structured interaction with external data reservoirs and operational systems. MCP standardizes the means by which AI systems can:

  • Obtain data updates superseding their static training knowledge base.
  • Establish secure connections to third-party Application Programming Interfaces (APIs) via dedicated intermediary servers.
  • Invoke specialized functional routines reliably.
  • Perform secure read/write operations against external state.
  • Interpret and manage intricate datasets that are cumbersome for pure text processing.

MCP revolves around defining three primary elements:

  1. Resources: URI-like pointers referencing structured external data (e.g., trakt://movies/popular).
  2. Tools: Abstracted functions the AI can invoke (e.g., retrieve_popular_films).
  3. Sessions: Contextual links managing secured communication channels.

Servers like this one serve as universal adapters, extending AI functionality without necessitating core model modification.

🎬 About Trakt

Trakt.tv is the definitive platform for automatically logging and cataloging media consumption across numerous digital distributors. Its offerings include:

  • Detailed aggregation of viewing history across services.
  • Social integration for peer interaction regarding watched content.
  • Algorithmic suggestions derived from personal viewing vectors.
  • A robust, developer-facing API ecosystem.

Trakt dominates media logging with: - A user base exceeding 14 million participants. - Extensive metadata covering millions of titles. - Wide interoperability with major playback engines.

This MCP layer leverages Trakt's API wealth to inject current entertainment intelligence directly into AI dialogue streams.

🛠️ AI-Accelerated Development Flow

This project benefited significantly from contemporary AI development aids:

  • Cursor: For iterative, prompt-driven code generation.
  • Aider: For collaborative AI code pairing during implementation.
  • Claude Code: For specific function definition and refinement.

This synergistic approach highlights the velocity achievable in creating specialized MCP components through AI partnership.

✨ Functional Capabilities

🌐 Public Catalog Access

  • Retrieve globally trending and currently popular television series and films.
  • Identify top-rated, most-favorited, and most-played media items.
  • Access up-to-the-second metrics from the global Trakt user base.
  • Results are structured with essential metadata: titles, release years, and engagement indices.
  • Detailed score reporting: View mean ratings and distribution statistics for media.

👤 Private User Metrics (Requires Authentication)

  • Access Watched Series Log: Retrieve the user's entire history of tracked television programs.
  • Pinpoint the precise date and time of the last interaction with a series.
  • Quantify total play counts per series.
  • Session Logging: Instantly mark content as watched via a 'check-in' mechanism.
  • Input methods: Unique series identifier (ID) or descriptive title.
  • Optional social syndication to external platforms (Twitter, Mastodon, Tumblr).
  • Ability to attach custom narrative context to the check-in.
  • Timestamps displayed in localized, readable formats.
  • Media Lookup: Search titles to obtain unique identifiers and auxiliary data.
  • Rating Management: Functions to inspect, establish, or revoke personal ratings across movies, series, seasons, and episodes, supporting paginated retrieval.
  • Secure OAuth2 device code flow for Trakt credential exchange.

🗣️ Community Feedback Tools

  • Retrieve Media Commentary: Read user discussions associated with films or series.
  • Granular Commentary Access: Fetch comments specific to seasons or individual episodes.
  • Discussion Depth: View specific comment threads and associated replies.
  • Spoiler Filtering: Comments flagged as spoilers are suppressed by default.
  • Visibility Toggle: Option to override spoiler suppression manually.
  • Review Identification: Longer-form commentary is categorized as "reviews."
  • Rating Breakdown Visualization: See histograms detailing how users assigned scores (1-10).

🔄 Core Infrastructure

  • Exposes Trakt API payloads via standardized MCP resource endpoints.
  • Provides programmatic tools for instantaneous retrieval of media statistics.
  • Enables the AI to furnish contextually relevant media suggestions.
  • Simplified credential handling and explicit logout mechanism.

As of the operational date, notable high-velocity shows include: - "The White Lotus" (2021) - 7,870 active watchers - "Daredevil: Born Again" (2025) - 6,738 active watchers - "Severance" (2022) - 4,507 active watchers

The current high-demand cinematic releases are: - "Black Bag" (2025) - 1,491 active watchers - "A Working Man" (2025) - 1,226 active watchers - "Mickey 17" (2025) - 764 active watchers

🔌 Defined Access Points (Resources)

Series Endpoints

Resource Path Purpose Sample Output Data
trakt://shows/trending Top series by viewership volume (last 24h) Title, Year, Watcher Count
trakt://shows/popular Series ranked by aggregated community ratings Title, Year, Popularity Index
trakt://shows/favorited Series most frequently marked as personal favorites Title, Year, Favorite Tally
trakt://shows/played Series with the highest cumulative playback counts Title, Year, Play Count
trakt://shows/watched Series viewed by the largest unique user base Title, Year, Unique Viewer Count

Film Endpoints

Resource Path Purpose Sample Output Data
trakt://movies/trending Top films by viewership volume (last 24h) Title, Year, Watcher Count
trakt://movies/popular Films ranked by aggregated community ratings Title, Year, Popularity Index
trakt://movies/favorited Films most frequently marked as personal favorites Title, Year, Favorite Tally
trakt://movies/played Films with the highest cumulative playback counts Title, Year, Play Count
trakt://movies/watched Films viewed by the largest unique user base Title, Year, Unique Viewer Count

User Management Endpoints

Resource Path Purpose Sample Output Data
trakt://user/auth/status Current status of the secure token linkage Auth State, Token Expiration Time
trakt://user/watched/shows User's personal compilation of viewed television series Title, Year, Date Last Seen, Play Count
trakt://user/watched/movies User's personal compilation of viewed motion pictures Title, Year, Date Last Seen, Play Count

⚙️ Invokable Functions (Tools)

Series Operations

# Retrieve currently trending shows (optional count limit)
retrieve_trending_series(limit=10)

# Retrieve highly rated series
retrieve_popular_series(limit=10)

# Fetch series marked as favorites over a specified period
retrieve_favorited_series(limit=10, interval="weekly")

# Fetch series with the highest play counts over a period
retrieve_played_series(limit=10, interval="weekly")

# Fetch series with the most unique watchers over a period
retrieve_watched_series(limit=10, interval="weekly")

# Search media catalog for a series title
search_series_catalog(search_term="Breaking Bad", max_results=5)

# Obtain detailed community ratings for a specific series ID
get_series_ratings(series_identifier="game-of-thrones")

# Retrieve the complete production profile for a series (rich metadata, status, ratings)
get_series_profile(series_identifier="game-of-thrones", comprehensive=True)  # Comprehensive by default

# Retrieve minimal series identification data (ID, title, year)
get_series_profile(series_identifier="game-of-thrones", comprehensive=False)

# Fetch associated video content (e.g., trailers) with embedded formatting
get_series_media(series_identifier="game-of-thrones")

# Search media catalog for movies by title
search_film_catalog(search_term="The Godfather", max_results=5)

Film Operations

# Retrieve currently trending movies (optional count limit)
retrieve_trending_films(limit=10)

# Retrieve highly rated films
retrieve_popular_films(limit=10)

# Fetch films marked as favorites over a specified period
retrieve_favorited_films(limit=10, interval="weekly")

# Fetch films with the highest play counts over a period
retrieve_played_films(limit=10, interval="weekly")

# Fetch films with the most unique watchers over a period
retrieve_watched_films(limit=10, interval="weekly")

# Obtain community ratings for a specific film ID
get_film_ratings(film_identifier="tron-legacy-2010")

# Retrieve the full production profile for a film (metadata, status, genres, runtime)
get_film_profile(film_identifier="tron-legacy-2010", comprehensive=True)  # Comprehensive by default

# Retrieve minimal film identification data
get_film_profile(film_identifier="tron-legacy-2010", comprehensive=False)

# Fetch associated video content (e.g., trailers)
get_film_media(film_identifier="tron-legacy-2010", text_links_only=False)

Authorization & User Record Management

# Initiate the Trakt device authorization sequence
initiate_device_linkage()

# Poll to confirm successful user credential exchange
query_linkage_status()

# Invalidate the current user session token
terminate_user_session()

# Retrieve all series logged as watched by the authorized user
get_user_watched_series(pagination_limit=0)  # 0 fetches all records

# Retrieve all movies logged as watched by the authorized user
get_user_watched_films(pagination_limit=0)

# Fetch user's established ratings, filterable by type, score, and page
fetch_user_evaluations(media_type="movies", score=10, page_number=1)

# Input new user ratings for media items (movies, series, episodes)
record_user_evaluation(media_type="movies", entries=[
    {"trakt_uid": "314", "value": 9}
])

# Erase existing user ratings based on their Trakt ID
delete_user_evaluation(media_type="movies", entries=[
    {"trakt_uid": "314"}
])

Current Consumption Logging (Check-in)

# Method A: Precise logging via Series ID (Recommended)
# Step 1: Locate ID via search_series_catalog()
# Step 2: Log activity
log_current_activity(season_num=1, episode_num=3, series_id="1388", user_note="Loving this show!")

# Method B: Convenient logging via Title
log_current_activity(
    season_num=1, 
    episode_num=1,
    series_title="Breaking Bad", 
    release_year=2008, 
    user_note="I'm the one who knocks!",
    share_to_twitter=True,
    share_to_mastodon=False,
    share_to_tumblr=False
)

Community Feedback Retrieval (Comments)

# Retrieve public commentary for a movie (default sort: newest, spoiler hiding enabled)
get_film_discussions(film_id="123", max_comments=10, reveal_spoilers=False)

# Retrieve show commentary, sorted by community likes
get_series_discussions(series_id="456", max_comments=10, reveal_spoilers=False, sort_metric="likes")

# Get segment-specific commentary (e.g., Season 1), sorted by highest rating
get_season_discussions(series_id="456", season_index=1, max_comments=10, reveal_spoilers=False, sort_metric="rating")

# Get episode-specific commentary, sorted by reply count
get_episode_discussions(series_id="456", season_index=1, episode_index=3, max_comments=10, reveal_spoilers=False, sort_metric="replies")

# Fetch a single, specific commentary thread
get_single_discussion(comment_identifier="789", reveal_spoilers=False)

# Retrieve nested replies within a discussion thread (default sort: oldest first)
get_discussion_replies(comment_identifier="789", max_replies=10, reveal_spoilers=False, sort_metric="oldest")

🔒 Authorization Protocol

The system employs Trakt's interactive device authorization sequence:

  1. User queries necessitate personal data trigger the linkage process.
  2. The user is furnished with a one-time verification code and a redirection URL.
  3. Upon successfully entering the code on the external Trakt portal and granting permissions, the AI must be notified of completion.
  4. The AI polls for status confirmation before proceeding to fetch personal records.
  5. The resulting access token is persistently stored in auth_token.json for subsequent, non-interactive use.

Session revocation can be executed via the terminate_user_session utility.

🚀 Deployment Guide

  1. Source Acquisition bash git clone [Repository URL] cd [directory_name]

  2. Dependency Installation bash pip install -r requirements.txt

  3. Configuration Initialization bash cp .env.example .env Edit .env to incorporate your Trakt credentials: TRAKT_CLIENT_ID=your_client_id TRAKT_CLIENT_SECRET=your_client_secret

  4. Server Initialization (Direct Execution) bash python server.py

🐳 Dockerized Deployment (SSE/HTTP Transport)

This method runs the connector via Docker, tunneling MCP communication over Server-Sent Events (SSE) on port 8080.

Method 1: docker run Command

# Build the image artifact
docker build -t trakt_mcpserver .

# Execute container, loading configuration from .env file
docker run -it --rm \
  --env-file .env \
  -p 8080:8080 \
  trakt_mcpserver

# Alternatively, inject secrets directly into the run command
docker run -it --rm \
  -e TRAKT_CLIENT_ID=your_client_id \
  -e TRAKT_CLIENT_SECRET=your_client_secret \
  -p 8080:8080 \
  trakt_mcpserver

Method 2: docker compose Utility

# Builds the image and initiates the service stack
docker compose up

🧪 Verification and Quality Assurance

Interacting via MCP Inspector

# List all available functional tools
npx @modelcontextprotocol/inspector --cli python server.py --method tools/list

# List accessible data endpoints
npx @modelcontextprotocol/inspector --cli python server.py --method resources/list

Integration in Claude Desktop

Update your Claude Desktop configuration file (config.json) by adding the following structure:

{
  "mcpServers": {
    "trakt_media": {
      "command": "python",
      "args": ["/path/to/your/server.py"],
      "env": {
        "TRAKT_CLIENT_ID": "your_client_id",
        "TRAKT_CLIENT_SECRET": "your_client_secret"
      }
    }
  }
}

Testing Suite Execution

# Install necessary testing dependencies
pip install -r requirements-dev.txt

# Execute comprehensive test suite
pytest

# Detailed, interactive test run
pytest -v -s

# Static type verification
pyright

# Code formatting and linting checks using Ruff
ruff check --fix    # Corrects stylistic and minor error issues
ruff format         # Enforces standardized code layout

💬 Suggested AI Prompts

Once active, the AI assistant can handle queries such as:

  • "Report the most popular television series currently available."
  • "Which motion pictures are trending this week?"
  • "List the series with the highest recorded plays this month."
  • "Display my fully cataloged television history." (Requires linkage)
  • "When did I last view the series 'The Expanse'?" (Requires linkage)
  • "Detail the film collection I have logged." (Requires linkage)
  • "What score did I assign to 'Pulp Fiction'?" (Requires linkage)
  • "Establish a 9/10 rating for the film 'Dune'." (Requires linkage)
  • "Locate series matching 'The Wire'."
  • "Log my viewing of Season 3, Episode 4 of 'Succession'."
  • "Log viewing for show ID 1388, Season 1 Episode 3, and notify Twitter."
  • "What are the current community discussions regarding the series 'Severance'?"
  • "Retrieve public sentiment on the movie 'Oppenheimer'."
  • "Show me discussions for Season 2 of 'Loki'."
  • "Fetch dialogue concerning Game of Thrones S1E1, ensuring spoilers are visible."
  • "Examine comment thread #789."
  • "List the top-rated replies to comment ID 789."
  • "What is the consensus rating for 'The Sopranos'?"
  • "Show the rating spread for the film 'Alien'."
  • "Provide the extended metadata for the series 'Foundation'."
  • "Give me the essential identifiers for the movie 'Blade Runner'."

👤 Personal Data Benefits

Upon successful authentication, the agent gains access to:

  • Comprehensive personal viewing archives for films and series.
  • Exact time-stamps of last consumption.
  • Frequency statistics for re-watching content.
  • Real-time progress tracking via direct session check-ins.
  • Direct integration with social media platforms for activity sharing.

🔮 Trajectory for Future Expansion

Planned enhancements include:

  • Expanding user scope for deeper personal metric access.
  • Integrating broadcast/release calendar notifications.
  • Implementing 'scrobbling' synchronization for passive tracking.
  • Developing personalized content suggestion engines.
  • Adding support for additional third-party social data sinks.

📄 Licensing

Governed by the MIT License.


Developed through 🧠 AI symbiosis and human oversight

Leveraging the Claude processing core

WIKIPEDIA NOTE: XMLHttpRequest (XHR) represents an API implemented via a JavaScript object, facilitating the dispatch of HTTP queries from a client-side browser environment to a remote server. Its primary utility lies in enabling asynchronous data exchange post-page load, forming the technical bedrock of AJAX. Before XHR, server interaction mandated full-page reloads via form submissions or link navigation.

== Historical Context == The foundational concept originated in 2000 within Microsoft Outlook development, subsequently implemented in Internet Explorer 5 (1999). The initial implementation used proprietary object instantiations (ActiveXObject(...)) before standardizing to the XMLHttpRequest nomenclature, which gained universal adoption across major browser engines by 2006 (IE7, Gecko 2002, Safari 1.2 (2004), Opera 8.0 (2005)).

=== Standardization Evolution === The W3C formalized the object specification starting in 2006. The Level 2 specification, introduced in 2008, augmented functionality to include progress monitoring, relaxed cross-site access restrictions, and binary stream handling. Development control migrated to WHATWG in late 2012, where it is maintained as a living document using Web IDL definitions.

== Operational Steps == Standard XHR interaction follows a predictable sequence:

  1. Instantiation: Creation of the XMLHttpRequest object instance.
  2. Configuration (open method): Defining the request method (GET, POST, etc.), specifying the target resource Uniform Resource Identifier (URI), and setting the synchronization mode (asynchronous being standard).
  3. Listener Setup: For async operations, an event handler must be defined to react to state transitions.
  4. Transmission (send method): Dispatching the actual request payload (if applicable).
  5. Response Handling: Monitoring the object's readyState. Upon reaching state 4 ('done'), the server response is available in properties like responseText or response.

Beyond this core flow, XHR permits custom header injection for server instruction, payload uploading via the send argument, granular response parsing (e.g., direct JSON interpretation), and mechanisms for request cancellation or timeout enforcement.

See Also

`