Skip to main content
Glama
878787ya

YouTube Comments MCP Server

by 878787ya

fetch_comments

Retrieve public YouTube video comments as structured JSON. Specify video URL, sort by relevance or time, and set maximum results up to 1000.

Instructions

Fetch public comments for a YouTube video and return a JSON string. Args: videoUrl: Full YouTube video URL. order: "relevance" (default) or "time". max: Max total comments to return (100–1000 建議).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
videoUrlYes
orderNorelevance
maxNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • server.py:50-50 (registration)
    The @mcp.tool() decorator registers fetch_comments as an MCP tool on the FastMCP server instance.
    @mcp.tool()
  • Main handler function that extracts video ID from URL, paginates through YouTube commentThreads API, collects top-level comments and replies, and returns a JSON string with results.
    async def fetch_comments(videoUrl: str, order: str = "relevance", max: int = 300) -> str:
        """
        Fetch public comments for a YouTube video and return a JSON string.
        Args:
          videoUrl: Full YouTube video URL.
          order: "relevance" (default) or "time".
          max: Max total comments to return (100–1000 建議).
        """
        if not os.environ.get("YOUTUBE_API_KEY"):
            return "ERROR: Missing YOUTUBE_API_KEY in environment."
        video_id = _extract_video_id(videoUrl)
        if not video_id:
            return "ERROR: Cannot parse video ID from URL."
        order = order if order in ("relevance", "time") else "relevance"
    
        items: List[Dict[str, Any]] = []
        page_token = None
        try:
            async with httpx.AsyncClient() as client:
                while True:
                    params = {
                        "part": "snippet,replies",
                        "videoId": video_id,
                        "maxResults": 100,
                        "order": order,
                        "textFormat": "plainText",
                    }
                    if page_token:
                        params["pageToken"] = page_token
                    data = await _yt_get(client, "commentThreads", params)
    
                    for th in data.get("items", []):
                        top = th.get("snippet", {}).get("topLevelComment", {})
                        if top:
                            items.append(_pack_comment(top))
                        for rep in th.get("replies", {}).get("comments", []) or []:
                            items.append(_pack_comment(rep, parent_id=top.get("id") if top else None))
    
                        if len(items) >= max:
                            break
                    if len(items) >= max:
                        break
                    page_token = data.get("nextPageToken")
                    if not page_token:
                        break
    
            return json.dumps({
                "video_id": video_id,
                "order": order,
                "requested": max,
                "total_returned": len(items),
                "items": items
            }, ensure_ascii=False)
        except httpx.HTTPStatusError as e:
            return f"ERROR: HTTP {e.response.status_code} – {e.response.text}"
        except Exception as e:
            return f"ERROR: {type(e).__name__}: {e}"
  • Input schema defined via function signature (videoUrl: str, order: str = "relevance", max: int = 300) and docstring in the tool definition.
    async def fetch_comments(videoUrl: str, order: str = "relevance", max: int = 300) -> str:
        """
        Fetch public comments for a YouTube video and return a JSON string.
        Args:
          videoUrl: Full YouTube video URL.
          order: "relevance" (default) or "time".
          max: Max total comments to return (100–1000 建議).
        """
  • Helper function to extract a YouTube video ID from various URL formats (youtube.com/watch, youtu.be, /embed/).
    def _extract_video_id(video_url: str) -> str:
        """Support https://www.youtube.com/watch?v=..., https://youtu.be/..., /embed/..."""
        try:
            u = urlparse(video_url)
            if u.netloc.endswith("youtu.be"):
                return u.path.strip("/")
            if "youtube.com" in u.netloc:
                qs = parse_qs(u.query or "")
                if "v" in qs:
                    return qs["v"][0]
                m = re.search(r"/embed/([A-Za-z0-9_-]{6,})", u.path or "")
                if m:
                    return m.group(1)
            m = re.search(r"([A-Za-z0-9_-]{11})", video_url)
            return m.group(1) if m else ""
        except Exception:
            return ""
  • Helper function to extract and format a comment item from the YouTube API response into a simplified dictionary.
    def _pack_comment(item: Dict[str, Any], parent_id: Optional[str] = None) -> Dict[str, Any]:
        s = item.get("snippet", {})
        return {
            "id": item.get("id"),
            "parentId": parent_id,
            "author": s.get("authorDisplayName"),
            "publishedAt": s.get("publishedAt"),
            "likeCount": s.get("likeCount", 0),
            "text": s.get("textOriginal") or s.get("textDisplay") or "",
        }
Behavior2/5

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

No annotations exist, so description bears full burden. It mentions 'public' but omits authentication requirements, rate limits, error handling, or side effects. Fails to disclose important behavioral traits.

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

Conciseness5/5

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

Two sentences with args list, front-loaded with purpose. No wasted words, concise yet informative.

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?

Output schema exists but description does not leverage it. Lacks mention of pagination, error responses, or field details. Adequate for simple tool but could be more complete.

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

Parameters4/5

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

With 0% schema coverage, description adds meaning: specifies videoUrl as full URL, order options, and max range suggestion. Enhances understanding beyond schema types.

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

Purpose5/5

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

Description clearly states verb 'Fetch' and resource 'public comments for a YouTube video', with immediate purpose. No siblings exist, so no differentiation needed.

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

Usage Guidelines4/5

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

Provides parameter usage (order default, max range suggestion) and notes public availability. Lacks explicit when-to-use/alternatives, but no siblings make this acceptable.

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

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/878787ya/yt_mcp'

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