Skip to main content
Glama
cnych

Backlinks MCP

by cnych

keyword_difficulty

Analyze keyword competition levels to identify ranking opportunities by assessing search difficulty scores for targeted keywords.

Instructions

Get keyword difficulty for the specified keyword

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
keywordYes
countryNous

Implementation Reference

  • MCP tool handler decorated with @mcp.tool(). Obtains captcha token and delegates to helper function get_keyword_difficulty.
    @mcp.tool()
    def keyword_difficulty(keyword: str, country: str = "us") -> Optional[Dict[str, Any]]:
        """
        Get keyword difficulty for the specified keyword
        """
        site_url = f"https://ahrefs.com/keyword-difficulty/?country={country}&input={urllib.parse.quote(keyword)}"
        token = get_capsolver_token(site_url)
        if not token:
            raise Exception(f"Failed to get verification token for keyword: {keyword}")
        return get_keyword_difficulty(token, keyword, country)
  • Core helper function implementing the keyword difficulty logic: makes API request to Ahrefs, parses response, extracts difficulty score, SERP results with metrics.
    def get_keyword_difficulty(token: str, keyword: str, country: str = "us") -> Optional[Dict[str, Any]]:
        """
        Get keyword difficulty information
        
        Args:
            token (str): Verification token
            keyword (str): Keyword to query
            country (str): Country/region code, default is "us"
            
        Returns:
            Optional[Dict[str, Any]]: Dictionary containing keyword difficulty information, returns None if request fails
        """
        if not token:
            return None
        
        url = "https://ahrefs.com/v4/stGetFreeSerpOverviewForKeywordDifficultyChecker"
        
        payload = {
            "captcha": token,
            "country": country,
            "keyword": keyword
        }
        
        headers = {
            "accept": "*/*",
            "content-type": "application/json; charset=utf-8",
            "referer": f"https://ahrefs.com/keyword-difficulty/?country={country}&input={keyword}"
        }
        
        try:
            response = requests.post(url, json=payload, headers=headers)
            if response.status_code != 200:
                return None
            
            data: Optional[List[Any]] = response.json()
            # 检查响应数据格式
            if not isinstance(data, list) or len(data) < 2 or data[0] != "Ok":
                return None
            
            # 提取有效数据
            kd_data = data[1]
            
            # 格式化返回结果
            result = {
                "difficulty": kd_data.get("difficulty", 0),  # Keyword difficulty
                "shortage": kd_data.get("shortage", 0),      # Keyword shortage
                "lastUpdate": kd_data.get("lastUpdate", ""), # Last update time
                "serp": {
                    "results": []
                }
            }
            
            # 处理SERP结果
            if "serp" in kd_data and "results" in kd_data["serp"]:
                serp_results = []
                for item in kd_data["serp"]["results"]:
                    # 只处理有机搜索结果
                    if item.get("content") and item["content"][0] == "organic":
                        organic_data = item["content"][1]
                        if "link" in organic_data and organic_data["link"][0] == "Some":
                            link_data = organic_data["link"][1]
                            result_item = {
                                "title": link_data.get("title", ""),
                                "url": link_data.get("url", [None, {}])[1].get("url", ""),
                                "position": item.get("pos", 0)
                            }
                            
                            # 添加指标数据(如果有)
                            if "metrics" in link_data and link_data["metrics"]:
                                metrics = link_data["metrics"]
                                result_item.update({
                                    "domainRating": metrics.get("domainRating", 0),
                                    "urlRating": metrics.get("urlRating", 0),
                                    "traffic": metrics.get("traffic", 0),
                                    "keywords": metrics.get("keywords", 0),
                                    "topKeyword": metrics.get("topKeyword", ""),
                                    "topVolume": metrics.get("topVolume", 0)
                                })
                            
                            serp_results.append(result_item)
                
                result["serp"]["results"] = serp_results
            
            return result
        except Exception:
            return None

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

C2.6/5.0
Behavior2/5

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

No annotations provided, so description must carry full burden. It does not disclose how difficulty is calculated, what unit/scale is used, or any side effects. Bare minimum.

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

Conciseness3/5

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

Single sentence of 8 words is concise but lacks substance. Appropriate length for the content, but more detail would improve informativeness.

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?

Given no annotations, no output schema, and 2 params requiring explanation, the description is inadequate. Leaves agent guessing about return values, scope, and usage nuances.

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

Parameters2/5

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

Schema has 0% description coverage. Description only mentions 'specified keyword' without explaining its meaning or format. Country parameter and default are not explained. Adds minimal value to schema.

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 'Get keyword difficulty for the specified keyword' clearly states the action and resource. It is distinct from sibling tools like get_backlinks_list and get_traffic, though sibling differentiation is implicit rather than explicit.

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?

No guidance on when to use this tool compared to alternatives. Lacks context about prerequisites 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.