MCP Ahrefs
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MCP Ahrefs show me the top 5 backlinks for example.com"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP Ahrefs
Ahrefs MCP Server for SAAGA
Quick Start with AI Assistant
Need help getting started? Have your AI coding assistant guide you!
Simply tell your AI assistant: "I have a MCP Ahrefs project. Please read and follow WORKING_WITH_SAAGA_PROMPT.md to help me understand and work with this MCP server."
For quick reference, the .ai-prompts.md file contains a condensed version of key patterns.
For detailed technical documentation, see docs/DECORATOR_PATTERNS.md.
Related MCP server: ahrefs-mcp
Testing with MCP Inspector
Ready to test your MCP server? The MCP Inspector Guide provides:
Step-by-step setup instructions with virtual environment troubleshooting
Test examples for all included tools
JSON mode instructions for parallel tools
Common issues and solutions
Quick start:
source .venv/bin/activate # Or use: uv shell
uv run mcp dev mcp_ahrefs/server/app.pyTesting with Claude CLI
This project includes a convenient test script for testing your MCP server with Claude:
# Test with a simple prompt
./test_mcp_with_claude.sh "List all available tools"
# Test a specific tool
./test_mcp_with_claude.sh "Run the echo_tool with message 'Hello World'"
# Test with multiple tools
./test_mcp_with_claude.sh "Test calculate_fibonacci with n=10 and echo_tool with message 'Done'"
# On Windows
.\test_mcp_with_claude.ps1 "List all available tools"The script automatically:
Uses the generated
mcp.integration_test.jsonconfiguration (created by cookiecutter)Runs Claude with the Sonnet model
Includes proper MCP configuration flags
Provides colored output for better readability
MCP Integration Testing
This project includes comprehensive integration tests that validate tools work correctly with real MCP client interactions:
Running Integration Tests
# Run all integration tests
test-mcp-integration
# Run with verbose output
test-mcp-integration --verbose
# Test specific tool
test-mcp-integration --tool echo_tool
# List all available tools
test-mcp-integration --list
# Cross-platform scripts also available
./test_mcp_integration.sh # Unix/Mac
.\test_mcp_integration.ps1 # WindowsWhat's Tested
The integration tests validate:
Tool Discovery: All tools are discoverable with correct schemas (no "kwargs" parameters)
Parameter Conversion: String parameters from MCP are converted to appropriate types
Error Handling: Invalid parameters and exceptions return proper error responses
SAAGA Integration: Decorators work correctly in the full MCP protocol flow
Protocol Compliance: Tools work with real MCP client connections
Generating Tests for New Tools
When you add a new tool, generate integration tests for it:
# Generate test template
generate-mcp-tests my_new_tool
# This creates a test template you can customize
# Add it to tests/integration/test_mcp_integration.pyIntegration vs Unit Tests
Unit Tests (
test_decorators.py): Test SAAGA decorators in isolationIntegration Tests (
test_mcp_integration.py): Test complete MCP protocol flow with real client
Run both test suites to ensure full coverage:
# Run all tests
pytest
# Run only unit tests
pytest tests/test_decorators.py
# Run only integration tests
test-mcp-integrationOverview
This MCP server was generated using the SAAGA MCP Server Cookie Cutter template. It includes:
FastMCP Integration: Modern MCP framework with dual transport support
SAAGA Decorators: Automatic exception handling, logging, and parallelization
Platform-Aware Configuration: Cross-platform configuration management
Streamlit Admin UI: Web-based configuration and monitoring interface
SQLite Logging: Comprehensive logging with database persistence
Installation
Prerequisites
Python 3.12 or higher
UV - An extremely fast Python package manager
Install from Source
# Install UV (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh # On macOS/Linux
# Or visit https://github.com/astral-sh/uv for Windows instructions
git clone <your-repository-url>
cd mcp_ahrefs
uv venv
uv syncDevelopment Installation
git clone <your-repository-url>
cd mcp_ahrefs
uv venv
uv sync --extra devUsage
Running the MCP Server
The server can be run in two modes:
1. STDIO Mode (for MCP clients like Claude Desktop)
# Run with default settings
uv run python -m mcp_ahrefs.server.app
# Run with custom log level
uv run python -m mcp_ahrefs.server.app --log-level DEBUG
# Run the server directly
uv run python mcp_ahrefs/server/app.py
uv run mcp_ahrefs-server2. SSE Mode (for web-based clients)
# Run with SSE transport
uv run python -m mcp_ahrefs.server.app --transport sse --port 3001
# Run with custom host and port
uv run python -m mcp_ahrefs.server.app --transport sse --host 0.0.0.0 --port 8080Command Line Options
uv run python -m mcp_ahrefs.server.app --helpAvailable options:
--transport: Choose between "stdio" (default) or "sse"--host: Host to bind to for SSE transport (default: 127.0.0.1)--port: Port to bind to for SSE transport (default: 3001)--log-level: Logging level - DEBUG, INFO, WARNING, ERROR (default: INFO)
MCP Client Configuration
Claude Desktop Configuration
Add the following to your Claude Desktop MCP settings (claude_desktop_config.json):
{
"mcpServers": {
"mcp_ahrefs": {
"command": "uv",
"args": ["run", "python", "-m", "mcp_ahrefs.server.app"],
"cwd": "/Users/jakub/Ragnarson/saaga/mcp_ahrefs"
}
}
}Advanced Configuration Options
{
"mcpServers": {
"mcp_ahrefs": {
"command": "uv",
"args": [
"run", "python", "-m", "mcp_ahrefs.server.app",
"--log-level", "DEBUG"
],
"cwd": "/Users/jakub/Ragnarson/saaga/mcp_ahrefs",
"env": {
"UV_PROJECT_ENVIRONMENT": "/Users/jakub/Ragnarson/saaga/mcp_ahrefs/.venv"
}
}
}
}Using with System Python (Alternative)
{
"mcpServers": {
"mcp_ahrefs": {
"command": "/Users/jakub/Ragnarson/saaga/mcp_ahrefs/.venv/bin/python",
"args": ["-m", "mcp_ahrefs.server.app"]
}
}
}Using with uv tool
{
"mcpServers": {
"mcp_ahrefs": {
"command": "uv",
"args": ["--directory=/Users/jakub/Ragnarson/saaga/mcp_ahrefs", "run" ,"mcp_ahrefs-server"]
}
}
}Configuration File Locations
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonLinux:
~/.config/Claude/claude_desktop_config.jsonWindows:
%APPDATA%/Claude/claude_desktop_config.json
Admin UI
Launch the Streamlit admin interface:
uv run streamlit run mcp_ahrefs/ui/app.pyDashboard

The dashboard provides:
Real-time server status monitoring
Project information and configuration overview
Quick access to common actions
System resource usage
Configuration Editor

The configuration editor features:
Live configuration editing with validation
Diff preview showing pending changes
Export/import functionality (JSON & YAML formats)
Reset to defaults with confirmation dialog
Automatic server restart notifications
Log Viewer

The log viewer includes:
Date range filtering for historical analysis
Status filtering (success/error/all)
Tool-specific filtering
Export capabilities for further analysis
Real-time log updates
AI Assistant Instructions
When working with this MCP Ahrefs MCP server in an AI coding assistant (like Claude, Cursor, or GitHub Copilot):
Understanding the Server Architecture
This server uses SAAGA decorators that automatically wrap all MCP tools with:
Exception handling: All errors are caught and returned as structured error responses
Comprehensive logging: All tool invocations are logged with timing and parameters
Optional parallelization: Tools marked for parallel execution run concurrently
Key Points for AI Assistants
Tool Registration Pattern: Tools are registered with decorators already applied. Do NOT manually wrap tools with decorators - this is handled automatically in
server/app.py.Parameter Types: MCP passes all parameters as strings from the client. Ensure your tools handle type conversion:
def my_tool(count: str) -> dict: # Convert string to int count_int = int(count) return {"result": count_int * 2}Error Handling: Tools can raise exceptions freely - the exception_handler decorator will catch them and return proper error responses.
Async Support: Both sync and async tools are supported. The decorators automatically detect and handle both patterns.
Logging: Check logs at the platform-specific data directory for debugging:
macOS:
~/Library/Application Support/mcp_ahrefs/logs.dbLinux:
~/.local/share/mcp_ahrefs/logs.dbWindows:
%APPDATA%/mcp_ahrefs/logs.db
Common Tasks
Adding a new tool:
# In mcp_ahrefs/tools/my_new_tool.py
def my_new_tool(param: str) -> dict:
"""Description of what this tool does."""
# Implementation
return {"result": "processed"}
# In mcp_ahrefs/tools/__init__.py
from .my_new_tool import my_new_tool
example_tools.append(my_new_tool)Testing with MCP Inspector:
# From the project root
uv run mcp dev mcp_ahrefs/server/app.pyDebugging a tool:
Check the SQLite logs for error messages
Run with
--log-level DEBUGfor verbose outputTest directly with MCP Inspector to see parameter handling
Important Implementation Notes
The server uses the standard MCP SDK (
from mcp.server.fastmcp import FastMCP)Function signatures are preserved through careful decorator implementation
The
register_tools()function inserver/app.pyhandles all decorator applicationTools should return JSON-serializable Python objects (dict, list, str, int, etc.)
Configuration
Configuration files are stored in platform-specific locations:
macOS:
~/Library/Application Support/mcp_ahrefs/Linux:
~/.local/share/mcp_ahrefs/Windows:
%APPDATA%/mcp_ahrefs/
Configuration Options
log_level: Logging level (INFO)log_retention_days: Days to retain logs (30)server_port: HTTP server port (3001)
Development
Project Structure
mcp_ahrefs/
├── mcp_ahrefs/
│ ├── config.py # Platform-aware configuration
│ ├── server/
│ │ └── app.py # FastMCP server with decorators
│ ├── tools/ # Your MCP tools
│ ├── decorators/ # SAAGA decorators
│ └── ui/ # Streamlit admin UI
├── tests/ # Test suite
├── docs/ # Documentation
└── pyproject.toml # Project configurationAdding New Tools
Create a new Python file in
mcp_ahrefs/tools/Define your tool function
Import and register it in
server/app.py
Example:
# mcp_ahrefs/tools/my_tool.py
def my_tool(message: str) -> str:
"""Example MCP tool."""
return f"Processed: {message}"
# The server will automatically apply SAAGA decoratorsRunning Tests
pytest tests/Code Quality
This project uses several code quality tools:
# Format code
black mcp_ahrefs/
isort mcp_ahrefs/
# Lint code
flake8 mcp_ahrefs/
mypy mcp_ahrefs/SAAGA Decorators
This server automatically applies three key decorators to your MCP tools:
Exception Handler: Graceful error handling with logging
Tool Logger: Comprehensive logging to SQLite database
Parallelize: Optional parallel processing for compute-intensive tools
Logging
Logs are stored in a SQLite database with the following schema:
timestamp: When the tool was calledtool_name: Name of the MCP toolduration_ms: Execution time in millisecondsstatus: Success/failure statusinput_args: Tool input argumentsoutput_summary: Summary of tool outputerror_message: Error details (if any)
Contributing
Fork the repository
Create a feature branch
Make your changes
Add tests for new functionality
Run the test suite
Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For issues and questions:
Create an issue on GitHub
Check the documentation in the
docs/directoryReview the test suite for usage examples
Acknowledgments
FastMCP for the MCP framework
SAAGA for the decorator patterns
Cookiecutter for the templating system
Available Tools
6 toolscalculate_fibonacciB
Calculate the nth Fibonacci number.
This is a more computationally intensive example that demonstrates
how tools can handle more complex operations.
Args:
n: The position in the Fibonacci sequence (must be >= 0)
Returns:
Dictionary containing the Fibonacci number and calculation info
Inputs: n (required). Returns: result
echo_toolA
Echo back the input message.
This is a simple example tool that demonstrates basic MCP tool functionality.
It will be automatically decorated with SAAGA decorators for exception handling
and logging.
Args:
message: The message to echo back
Returns:
The echoed message with a prefix
Inputs: message (required). Returns: result
get_timeA
Get the current time.
Returns the current time in a human-readable format.
Returns:
Current time as a string
Inputs: no named parameters. Returns: result
process_batch_dataA
Parallelized version of process_batch_data.
This function accepts a list of keyword argument dictionaries and executes
process_batch_data concurrently for each set of arguments.
Original function signature: process_batch_data(items: List, operation: str)
Args:
kwargs_list (List[Dict[str, Any]]): A list of dictionaries, where each
dictionary provides the keyword arguments
for a single call to process_batch_data.
Returns:
List[Any]: A list containing the results of each call to process_batch_data,
in the same order as the input kwargs_list.
Original docstring: Process a batch of data items.
This is an example of a tool that benefits from parallelization.
It will be automatically decorated with the parallelize decorator
in addition to exception handling and logging.
Args:
items: List of strings to process
operation: Operation to perform ('upper', 'lower', 'reverse')
Returns:
Processed items with metadata
Inputs: kwargs_list (required). Returns: result
random_numberA
Generate a random number within a specified range.
Args:
min_value: Minimum value (default: 1)
max_value: Maximum value (default: 100)
Returns:
Dictionary containing the random number and range info
Inputs: min_value, max_value. Returns: result
simulate_heavy_computationB
Parallelized version of simulate_heavy_computation.
This function accepts a list of keyword argument dictionaries and executes
simulate_heavy_computation concurrently for each set of arguments.
Original function signature: simulate_heavy_computation(complexity: int)
Args:
kwargs_list (List[Dict[str, Any]]): A list of dictionaries, where each
dictionary provides the keyword arguments
for a single call to simulate_heavy_computation.
Returns:
List[Any]: A list containing the results of each call to simulate_heavy_computation,
in the same order as the input kwargs_list.
Original docstring: Simulate a heavy computation task.
This tool demonstrates parallelization benefits by performing
a computationally intensive task that can be parallelized.
Args:
complexity: Complexity level (1-10, higher = more computation)
Returns:
Dictionary containing computation results
Inputs: kwargs_list (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Multiple tools have overlapping computational purposes that could cause confusion. calculate_fibonacci and simulate_heavy_computation both perform intensive calculations, while process_batch_data and simulate_heavy_computation both offer parallelized processing. The echo_tool and get_time are distinct but the computational tools lack clear boundaries.
Most tools follow a consistent verb_noun naming pattern (calculate_fibonacci, echo_tool, get_time, process_batch_data, random_number, simulate_heavy_computation). The only minor deviation is 'echo_tool' using 'tool' as a suffix while others don't, but overall the naming is quite predictable.
With 6 tools, the count is reasonable for a utility server, but feels borderline thin for a server named 'MCP Ahrefs' which suggests SEO/web analytics functionality. These generic utility tools don't align well with the implied domain, making the count feel mismatched to the server name.
For a server named 'MCP Ahrefs' (implying SEO/backlink analytics), there are significant gaps - no tools for domain analysis, backlink checking, keyword research, or any actual Ahrefs-like functionality. As a generic utility set, it lacks coherent coverage of any specific domain, making it incomplete for any focused purpose.
Maintenance
Related MCP Connectors
Official Ahrefs MCP server. Access SEO data, including backlinks, keywords, and competitor research.
Hosted SEO MCP server for AI agents: keyword research, live Google SERPs and Maps, local rank tracking, backlinks, site audits, competitor research, and Search Console data.
Audit, rank-track and analyze SEO for sites via an authenticated MCP server.
Ahrefs: Ahrefs API: SEO powerhouse featuring keyword research, backlink analysis, and SERP tracking.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceProvides SEO automation with tools for keyword research, SERP analysis, and competitor analysis through Google Ads API integration, enabling AI assistants to access these capabilities via MCP.50ISC
- AlicenseAqualityDmaintenanceMCP server for the Ahrefs API v3 that provides live SEO data including keyword research, SERP analysis, backlink profiles, and domain authority to MCP clients like Claude.16MIT
- AlicenseBqualityBmaintenanceEnables MCP hosts to access 22 SEO Intellect API tools, handling task submission, polling, and retrieval for SEO analysis workflows.22MIT
- FlicenseNot gradedqualityBmaintenanceProvides SEO audits, content analysis, and domain overviews through an MCP server, including on-page, technical, and authority metrics with built-in browser rendering and anti-bot handling.-