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
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. It states the tool 'gets' data, implying a read-only operation, but doesn't clarify aspects like whether it requires authentication, has rate limits, returns a numerical score or textual assessment, or involves external API calls. The description is minimal and misses key behavioral traits needed for safe and effective use.

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 a single, efficient sentence with no wasted words, making it appropriately concise. However, it's front-loaded with the core action but lacks structure for additional details like parameters or usage, which could enhance clarity without sacrificing brevity. It earns a high score for conciseness but not the top due to minimal content.

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 the tool's complexity (2 parameters, no annotations, no output schema), the description is incomplete. It doesn't explain what 'keyword difficulty' entails, how results are returned, or the role of parameters like 'country'. For a tool that likely provides SEO metrics, more context is needed to guide the agent effectively, making this inadequate for the task.

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?

The input schema has 2 parameters with 0% description coverage, so the description must compensate. It mentions 'keyword' but doesn't explain its format (e.g., single word, phrase) or constraints. It omits the 'country' parameter entirely, leaving its purpose (e.g., regional SEO data) and default value ('us') undocumented. This fails to add meaningful semantics beyond the bare schema.

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

Purpose3/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 verb ('Get') and resource ('keyword difficulty'), making the purpose understandable. However, it lacks specificity about what 'keyword difficulty' represents (e.g., SEO competition score, ranking challenge) and doesn't distinguish this tool from its siblings like 'keyword_generator', which might also involve keyword analysis. This vagueness prevents a higher score.

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 'keyword_generator' for generating keywords or 'get_traffic' for traffic data, nor does it specify contexts where keyword difficulty is relevant (e.g., SEO planning, content strategy). Without any usage context or exclusions, the agent must infer when this tool is appropriate.

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/cnych/backlinks-mcp'

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