Skip to main content
Glama
Ukenn2112

Bangumi TV MCP Service

by Ukenn2112

get_episodes

Retrieve and filter episodes for a specific anime or media subject by specifying IDs, episode types, and pagination settings. Supports MainStory, SP, OP, ED, PV, MAD, and Other types.

Instructions

List episodes for a subject.

Supported Episode Types (integer enum):
0: MainStory, 1: SP, 2: OP, 3: ED, 4: PV, 5: MAD, 6: Other

Args:
    subject_id: The ID of the subject.
    episode_type: Optional filter by episode type (integer value from EpType enum).
    limit: Pagination limit. Max 200. Defaults to 100.
    offset: Pagination offset. Defaults to 0.

Returns:
    Formatted list of episodes or an error message.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
episode_typeNo
limitNo
offsetNo
subject_idYes

Implementation Reference

  • main.py:755-828 (handler)
    The handler function implementing the 'get_episodes' MCP tool. It is decorated with @mcp.tool() for automatic registration. Fetches episodes from Bangumi API endpoint /v0/episodes for a given subject_id, applies optional episode_type filter, handles pagination, processes the response, formats episode details using EpType enum, and returns a formatted string summary.
    @mcp.tool()
    async def get_episodes(
        subject_id: int,
        episode_type: Optional[EpType] = None,
        limit: int = 100,
        offset: int = 0,
    ) -> str:
        """
        List episodes for a subject.
    
        Supported Episode Types (integer enum):
        0: MainStory, 1: SP, 2: OP, 3: ED, 4: PV, 5: MAD, 6: Other
    
        Args:
            subject_id: The ID of the subject.
            episode_type: Optional filter by episode type (integer value from EpType enum).
            limit: Pagination limit. Max 200. Defaults to 100.
            offset: Pagination offset. Defaults to 0.
    
        Returns:
            Formatted list of episodes or an error message.
        """
        query_params: Dict[str, Any] = {
            "subject_id": subject_id,
            "limit": min(limit, 200),
            "offset": offset,
        }
        if episode_type is not None:
            query_params["type"] = int(episode_type)
    
        response = await make_bangumi_request(
            method="GET", path="/v0/episodes", query_params=query_params
        )
    
        error_msg = handle_api_error_response(response)
        if error_msg:
            return error_msg
    
        # Expecting a dictionary with 'data' and 'total'
        if not isinstance(response, dict) or "data" not in response:
            return f"Unexpected API response format for get_episodes: {response}"
    
        episodes = response.get("data", [])
        if not episodes:
            return f"No episodes found for subject ID {subject_id} with the given criteria."
    
        formatted_results = []
        for ep in episodes:
            ep_id = ep.get("id")
            name = ep.get("name")
            name_cn = ep.get("name_cn")
            sort = ep.get("sort")
    
            ep_type_int = ep.get("type")
            ep_type_str = "Unknown Type"
            if ep_type_int is not None:
                try:
                    ep_type_str = EpType(ep_type_int).name
                except ValueError:
                    ep_type_str = f"Unknown Type ({ep_type_int})"
    
            airdate = ep.get("airdate")
    
            formatted_results.append(
                f"Episode ID: {ep_id}, Type: {ep_type_str}, Number: {sort}, Name: {name_cn or name}, Airdate: {airdate}"
            )
    
        total = response.get("total", 0)
        results_text = f"Found {len(episodes)} episodes (Total: {total}).\n" + "---\n".join(
            formatted_results
        )
    
        return results_text
  • main.py:39-52 (schema)
    EpType IntEnum defines the episode types used as input parameter type for the get_episodes tool (episode_type: Optional[EpType]), providing schema/validation for episode filtering (0: Main Story, 1: SP, 2: OP, etc.).
    class EpType(IntEnum):
        """
        章节类型
        0 = 本篇, 1 = 特别篇, 2 = OP, 3 = ED, 4 = 预告/宣传/广告, 5 = MAD, 6 = 其他
        """
    
        MAIN_STORY = 0
        SP = 1
        OP = 2
        ED = 3
        PV = 4
        MAD = 5
        OTHER = 6
  • Shared helper function make_bangumi_request used by get_episodes to perform authenticated HTTP requests to the Bangumi API, handle errors, and return JSON responses.
    async def make_bangumi_request(
        method: str,
        path: str,
        query_params: Optional[Dict[str, Any]] = None,
        json_body: Optional[Dict[str, Any]] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> Any:
        """Make a request to the Bangumi API with proper headers and error handling."""
        request_headers = headers.copy() if headers else {}
        request_headers["User-Agent"] = USER_AGENT
        request_headers["Accept"] = "application/json"
    
        if BANGUMI_TOKEN:
            request_headers["Authorization"] = f"Bearer {BANGUMI_TOKEN}"
    
        url = f"{BANGUMI_API_BASE}{path}"
    
        async with httpx.AsyncClient() as client:
            try:
                print(
                    f"DEBUG: Making {method} request to {url} with params={query_params}, json={json_body}"
                )
                response = await client.request(
                    method=method,
                    url=url,
                    params=query_params,
                    json=json_body,
                    headers=request_headers,
                    timeout=30.0,
                )
                response.raise_for_status()
                # Return the raw JSON response, let the calling tool handle its structure (dict or list)
                json_response = response.json()
                print(
                    f"DEBUG: Received response (type: {type(json_response)}, keys/length: {list(json_response.keys()) if isinstance(json_response, dict) else len(json_response) if isinstance(json_response, list) else 'N/A'})"
                )
                return json_response
            except httpx.HTTPStatusError as e:
                error_msg = (
                    f"HTTP error occurred: {e.response.status_code} - {e.response.text}"
                )
                print(f"ERROR: {error_msg}")
                # Try to parse the error response body if it's JSON
                try:
                    error_details = e.response.json()
                    return {
                        "error": error_msg,
                        "status_code": e.response.status_code,
                        "details": error_details,
                    }
                except json.JSONDecodeError:
                    return {
                        "error": error_msg,
                        "status_code": e.response.status_code,
                        "details": e.response.text,
                    }
            except httpx.RequestError as e:
                error_msg = f"An error occurred while requesting {e.request.url!r}: {e}"
                print(f"ERROR: {error_msg}")
                return {"error": error_msg}
            except Exception as e:
                error_msg = f"An unexpected error occurred: {e}"
                print(f"ERROR: {error_msg}")
                return {"error": error_msg}
  • Shared helper function handle_api_error_response used by get_episodes to check API responses for errors and format error messages.
    def handle_api_error_response(response: Any) -> Optional[str]:
        """
        Checks if the API response indicates an error and returns a formatted error message.
        Handles both dictionary-based errors and returns from make_bangumi_request on failure.
        """
        # Check for error structure returned by make_bangumi_request on HTTPStatusError or RequestError
        if isinstance(response, dict) and (
            "error" in response or "status_code" in response
        ):
            # This is an error dictionary created by our helper
            status_code = response.get("status_code", "N/A")
            error_msg = response.get("error", "Unknown error during request.")
            details = response.get("details", "")
            return f"Bangumi API Request Error (Status {status_code}): {error_msg}. Details: {details}".strip()
    
        # Check for error structure returned by Bangumi API itself (often dictionaries)
        # Safely check if the response is a dictionary before accessing its keys
        if isinstance(response, dict):
            if "title" in response and "description" in response:
                # This looks like a common Bangumi error response structure
                error_title = response.get("title", "API Error")
                error_description = response.get("description", "No description provided.")
                # The API might return a status code in the body too, or rely on HTTP status
                return f"Bangumi API Error: {error_title}. {error_description}".strip()
    
            # Check if it's a dictionary but *not* empty and *doesn't* look like a success response from list endpoints
            # Check for specific error fields if structure varies
            # Add more checks here if other error dictionary formats are observed
            # Example: if "message" in response and "code" in response: return f"API Error {response['code']}: {response['message']}"
            pass  # If it's a dictionary but doesn't match known error formats, assume it's a valid data response for now
    
        # If it's not a dictionary, or it's a dictionary that doesn't match known error formats, assume it's not an error
        return None
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It adds some context: it lists supported episode types with an integer enum, mentions pagination with a max limit of 200, and notes that it returns a formatted list or error. However, it doesn't cover critical aspects like rate limits, authentication needs, or whether it's read-only (implied by 'List' but not explicit). The description compensates partially but leaves gaps.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured and appropriately sized. It starts with a clear purpose statement, followed by an enum list, and then details parameters and returns in a bullet-like format. Every sentence adds value, with no wasted words. However, it could be slightly more front-loaded by integrating the enum into the purpose statement for faster scanning.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (4 parameters, no output schema, no annotations), the description is partially complete. It covers parameters well and hints at returns, but lacks details on output format (e.g., structure of the 'formatted list'), error handling specifics, or behavioral traits like pagination behavior beyond limits. For a list tool with no annotations, more context on results would enhance completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds significant meaning beyond the input schema, which has 0% schema description coverage. It explains each parameter: 'subject_id' as the ID of the subject, 'episode_type' as an optional filter with enum details, 'limit' with max and default values, and 'offset' with default. This fully compensates for the schema's lack of descriptions, making parameters clear and actionable.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'List episodes for a subject.' It specifies the verb ('List') and resource ('episodes for a subject'), making it easy to understand. However, it doesn't explicitly differentiate from sibling tools like 'get_episode_details' or 'browse_subjects,' which could provide similar or overlapping functionality.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'get_episode_details' (for specific episodes) or 'browse_subjects' (for broader subject listings), leaving the agent to infer usage based on context alone. This lack of explicit comparison reduces clarity in tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Ukenn2112/BangumiMCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server