Skip to main content
Glama

get_trending_topics

Identify trending topics on YouTube Shorts to discover content ideas. Analyze viral metrics and categories for content strategy.

Instructions

发现当前 YouTube Shorts 上的热门话题和趋势。分析多个分类的热门内容,帮助选题。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
categoryNo内容分类all
hours_agoNo时间范围(小时),最大 30 天

Implementation Reference

  • The main handler function that implements the get_trending_topics tool. It searches for videos by category keywords, analyzes them with ViralAnalyzer, removes duplicates, ranks them, and generates a markdown report with the top 10 trending videos.
    async def get_trending_topics(
        category: str = "all",
        hours_ago: int = 24
    ) -> list[TextContent]:
        """工具 3 的实现:获取热门话题"""
        
        # 定义分类关键词
        category_keywords = {
            "tech": ["AI", "coding", "tech", "programming", "software"],
            "entertainment": ["funny", "comedy", "entertainment", "viral"],
            "education": ["tutorial", "learn", "education", "how to"],
            "gaming": ["gaming", "gameplay", "game", "esports"],
            "all": [""]  # 空关键词表示全局搜索
        }
        
        keywords = category_keywords.get(category, [""])
        
        try:
            client = YouTubeClient()
            analyzer = ViralAnalyzer()
            
            all_videos = []
            
            # 对每个关键词搜索
            for keyword in keywords:
                videos = client.get_trending_shorts(
                    keyword=keyword,
                    hours_ago=hours_ago,
                    max_results=5  # 每个关键词取 5 个
                )
                all_videos.extend(videos)
            
            if not all_videos:
                return [TextContent(
                    type="text",
                    text=f"未找到 {category} 分类的热门视频"
                )]
            
            # 分析并排序
            all_videos = analyzer.analyze_videos(all_videos)
            all_videos = analyzer.rank_videos(all_videos)
            
            # 去重(按视频 ID)
            seen = set()
            unique_videos = []
            for v in all_videos:
                if v.video_id not in seen:
                    seen.add(v.video_id)
                    unique_videos.append(v)
            
            # 取前 10
            top_videos = unique_videos[:10]
            
            # 生成报告
            report = f"# 🎯 {category.upper()} 分类热门话题\n\n"
            report += f"**时间范围**: 最近 {hours_ago} 小时\n\n"
            report += "---\n\n"
            report += VideoData.markdown_header() + "\n"
            
            for video in top_videos:
                report += video.to_markdown_row() + "\n"
            
            return [TextContent(type="text", text=report)]
        
        except Exception as e:
            return [TextContent(
                type="text",
                text=f"❌ 获取热门话题失败: {str(e)}"
            )]
  • src/server.py:206-230 (registration)
    Tool registration in the list_tools() function that defines the schema for get_trending_topics, including its name, description, and input parameters (category with enum values, and hours_ago with constraints).
    Tool(
        name="get_trending_topics",
        description=(
            "发现当前 YouTube Shorts 上的热门话题和趋势。"
            "分析多个分类的热门内容,帮助选题。"
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "category": {
                    "type": "string",
                    "description": "内容分类",
                    "enum": ["tech", "entertainment", "education", "gaming", "all"],
                    "default": "all"
                },
                "hours_ago": {
                    "type": "integer",
                    "description": "时间范围(小时),最大 30 天",
                    "default": 24,
                    "minimum": 1,
                    "maximum": 720
                }
            }
        }
    ),
  • src/server.py:338-342 (registration)
    The routing logic in the call_tool() handler that maps the tool name 'get_trending_topics' to its handler function, extracting and passing the arguments.
    elif name == "get_trending_topics":
        return await get_trending_topics(
            category=arguments.get("category", "all"),
            hours_ago=arguments.get("hours_ago", 24)
        )
  • The VideoData model used by get_trending_topics handler for formatting output. Provides to_markdown_row() and markdown_header() methods to generate the report table.
    class VideoData(BaseModel):
        """YouTube Shorts 视频数据模型"""
        
        video_id: str = Field(..., description="视频 ID")
        title: str = Field(..., description="视频标题")
        channel_name: str = Field(..., description="频道名称")
        channel_id: str = Field(..., description="频道 ID")
        channel_subscribers: Optional[int] = Field(None, description="频道订阅数")
        
        views: int = Field(..., description="播放量")
        likes: int = Field(default=0, description="点赞数")
        comments: int = Field(default=0, description="评论数")
        
        published_at: datetime = Field(..., description="发布时间")
        duration: str = Field(..., description="视频时长")
        
        url: str = Field(..., description="视频链接")
        thumbnail_url: Optional[str] = Field(None, description="缩略图链接")
        description: Optional[str] = Field(None, description="视频描述")
        
        engagement_rate: float = Field(default=0.0, description="互动率 (%)")
        
        class Config:
            """Pydantic 配置"""
            json_encoders = {
                datetime: lambda v: v.isoformat()
            }
        
        def to_markdown_row(self) -> str:
            """转换为 Markdown 表格行"""
            published_time = self.published_at.strftime('%Y-%m-%d %H:%M')
            return (
                f"| [{self.title[:40]}...]({self.url}) "
                f"| {self.channel_name[:20]} "
                f"| {self.views:,} "
                f"| {self.likes:,} "
                f"| {self.comments:,} "
                f"| {self.engagement_rate:.2f}% "
                f"| {published_time} |"
            )
        
        @staticmethod
        def markdown_header() -> str:
            """Markdown 表格头"""
            return (
                "| 标题 | 频道 | 播放量 | 点赞数 | 评论数 | 互动率 | 发布时间 |\n"
                "|------|------|--------|--------|--------|--------|----------|"
            )
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it mentions discovering and analyzing trends, it doesn't describe what the tool actually returns (e.g., list of topics, metrics, examples), how it sources data, whether it requires authentication, rate limits, or freshness of data. The description is too vague about the tool's actual behavior beyond the high-level purpose.

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 concise with two sentences that directly state the tool's purpose. There's no unnecessary information or repetition. However, it could be slightly more front-loaded by immediately clarifying the scope (YouTube Shorts) rather than having it in the middle of the first sentence.

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

Completeness2/5

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

For a tool with 2 parameters, no annotations, and no output schema, the description is inadequate. It doesn't explain what the tool returns (crucial for a discovery/analysis tool), how results are structured, data sources, or limitations. The purpose is clear, but the description lacks essential context about the tool's behavior and outputs that would help an agent use it effectively.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already fully documents both parameters (category with enum values and hours_ago with range constraints). The description doesn't add any parameter-specific information beyond what's in the schema. It mentions '多个分类' (multiple categories) which aligns with the category parameter, but provides no additional context about parameter usage or semantics.

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: '发现当前 YouTube Shorts 上的热门话题和趋势' (discover current trending topics and trends on YouTube Shorts) and '分析多个分类的热门内容,帮助选题' (analyze trending content across multiple categories to help with topic selection). It specifies the resource (YouTube Shorts trending topics) and the action (discover/analyze). However, it doesn't explicitly differentiate from sibling tools like 'get_youtube_shorts_trends' or 'discover_niche_trends', which appear related.

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 mentions analyzing multiple categories to help with topic selection, but doesn't specify when this tool is appropriate compared to siblings like 'get_youtube_shorts_trends' (which appears similar) or 'discover_niche_trends' (which might focus on different aspects of trends). There's no mention of prerequisites, limitations, or typical use cases.

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/Xeron2000/viral-shorts'

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