AI & ML

Building an MCP Server for SEO Data: Query Googlebot Logs From Claude or Another AI Client

· 5 min read
Community Article
Community articles are authored by SitePoint Premium contributors. Content is screened before publication, and SitePoint reserves the right to moderate or remove articles that violate our guidelines. Views expressed are those of the authors and do not necessarily reflect those of SitePoint.

Building an MCP Server for SEO Data: Query Googlebot Logs From Claude or Another AI Client

DJ
Div John
Published in
·Updated:

The AI briefing for Developers

Stay up to date with AI tools, model releases, and developer workflows that matter.

Weekly. Free. One click to leave.

Share this article

Building an MCP Server for SEO Data: Query Googlebot Logs From Claude or Another AI Client
SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools
Start Free Trial

7 Day Free Trial. Cancel Anytime.

SEO data usually lives in separate places: a crawler, Search Console, analytics, and server logs that only a developer can reach. Answering a question such as "which URLs did Googlebot request last week, and how many returned errors?" means exporting, joining and checking. The Model Context Protocol (MCP) offers another route: expose the data as tools that an AI assistant can call, so it answers from the source instead of from memory.

This tutorial builds a small, read-only MCP server in Python that summarizes Googlebot activity in an access log. It verifies the requests against Google's published IP ranges, returns only aggregates and warns when the numbers could mislead. It then shows how to connect the server to a client, how to extend it safely, and when a hosted server from an SEO platform may be the better choice. All code was run with Python 3.13 and mcp 2.3.0, and the tests pass.

Key Takeaways

  • MCP makes data callable. A server exposes tools, and a client such as an AI assistant discovers and calls them.
  • Start read-only. Tools that only read and aggregate are much easier to reason about than tools with side effects.
  • Verify bots before counting them. The Googlebot user agent is trivial to fake, so match IPs against Google's published ranges.
  • Return aggregates, not raw logs. It limits what a tool call can leak and keeps responses small.
  • Treat answers as claims to check. Surface warnings in the output and keep a way to trace a number back to the source.

Why Give an Assistant Live Data?

Developers are already using AI tools, but they do not fully trust them. The Stack Overflow Developer Survey 2025 reports that 84% of respondents use or plan to use AI tools, and that more developers actively distrust the accuracy of AI tools (46%) than trust it (33%). It also describes AI agents as not yet mainstream: 14.1% of respondents use them daily and 37.9% do not plan to use them.

That mix suggests a design goal. People want the speed of an assistant without unsupported claims, and connecting it to a data source gives it something concrete to work from and something you can check. It does not make the assistant correct, so the server design below puts as many checks as possible into the tools themselves.

How MCP Fits Together

The MCP architecture overview describes three participants. A host is the AI application, a client is the component inside it that holds a connection, and a server is the program that provides context. Servers can expose tools (functions the AI can call), resources (data) and prompts (templates). The two transports are stdio, for local servers that usually serve one client, and Streamable HTTP, for remote servers that can serve many.

This tutorial uses one tool over stdio, which is the simplest setup to build and test. The same server logic can be hosted remotely later.

Step 1: Parse and Verify Log Lines

Google's guide to verifying Googlebot describes two methods: a reverse DNS lookup followed by a forward lookup, or matching the request IP against published JSON range files in CIDR format. The code below uses the second method because it works offline and is easy to test. Download the current range file (for example googlebot.json, which has a prefixes list with ipv4Prefix or ipv6Prefix entries) and refresh it periodically, because the ranges change.

The helper module parses combined-format log lines, builds network objects from the range file and aggregates only the requests that claim to be Googlebot. It reports verified and unverified counts separately and adds a warning when they differ or when lines could not be parsed.

"""Log analysis helpers for an SEO MCP server. Standard library only."""
import ipaddress
import re
from collections import Counter

LINE = re.compile(
    r'^(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] "(?P<method>[A-Z]+) (?P<path>\S+)[^"]*" '
    r'(?P<status>\d{3}) \S+ "[^"]*" "(?P<agent>[^"]*)"')

def parse_line(line):
    m = LINE.match(line)
    if not m:
        return None
    d = m.groupdict()
    d["status"] = int(d["status"])
    d["day"] = d["time"].split(":", 1)[0]          # e.g. 12/Oct/2026
    return d

def load_networks(ranges_json):
    """Build network objects from Google's published IP range file (prefixes list)."""
    nets = []
    for p in ranges_json.get("prefixes", []):
        cidr = p.get("ipv4Prefix") or p.get("ipv6Prefix")
        if cidr:
            nets.append(ipaddress.ip_network(cidr))
    return nets

def is_verified(ip, networks):
    try:
        addr = ipaddress.ip_address(ip)
    except ValueError:
        return False
    return any(addr.version == n.version and addr in n for n in networks)

def summarize(lines, networks, max_rows=10):
    """Aggregate Googlebot-claiming requests. Never returns raw log lines."""
    claimed = verified = 0
    unparsed = 0
    status_verified = Counter()
    not_found = Counter()
    for line in lines:
        rec = parse_line(line)
        if rec is None:
            unparsed += 1
            continue
        if "googlebot" not in rec["agent"].lower():
            continue
        claimed += 1
        if is_verified(rec["ip"], networks):
            verified += 1
            status_verified[rec["status"]] += 1
            if rec["status"] == 404:
                not_found[rec["path"]] += 1
    warnings = []
    if claimed - verified:
        warnings.append("%d of %d requests claiming to be Googlebot did not match "
                        "Google's published IP ranges and are excluded from the verified figures."
                        % (claimed - verified, claimed))
    if unparsed:
        warnings.append("%d lines could not be parsed; counts may be incomplete." % unparsed)
    errors = sum(n for s, n in status_verified.items() if s >= 400)
    return {
        "claimed_googlebot_requests": claimed,
        "verified_googlebot_requests": verified,
        "verified_status_counts": dict(sorted(status_verified.items())),
        "verified_error_rate": round(errors / verified, 4) if verified else None,
        "top_404_paths": not_found.most_common(max_rows),
        "warnings": warnings,
    }

Step 2: Expose It as an MCP Tool

The server file wires the helper into a tool. It is read-only, caps how many rows one call can return, and never returns raw log lines. The type hints and docstring become the tool schema and description that the client shows to the model, so write them as if a colleague will read them.

"""A read-only MCP server that answers questions about Googlebot activity in an access log."""
import json
import sys
from pathlib import Path
from mcp.server.mcpserver import MCPServer
from seo_logs import load_networks, summarize

def build_server(log_path, ranges_path):
    networks = load_networks(json.loads(Path(ranges_path).read_text()))
    mcp = MCPServer("seo-logs")

    @mcp.tool()
    def googlebot_summary(max_rows: int = 10) -> dict:
        """Summarize verified Googlebot requests: status counts, error rate and top 404 paths."""
        max_rows = max(1, min(max_rows, 50))          # cap what one call can return
        with open(log_path, encoding="utf-8", errors="replace") as f:
            return summarize(f, networks, max_rows)

    return mcp

if __name__ == "__main__":
    build_server(sys.argv[1], sys.argv[2]).run()      # stdio transport by default

Note that mcp 2.x renamed FastMCP to MCPServer. If you use the 1.x SDK, the import and constructor differ, so check the SDK documentation for the version you install.

Step 3: Test It

The tests cover parsing, IP matching (including IPv6 and an address outside a range), the aggregates, warnings, the absence of raw IPs in the output, and an end-to-end call through the MCP client API. Verified requests exclude a fake Googlebot from a non-Google IP, so its 404 does not appear in the top 404 list.

import asyncio, json, tempfile, os
from seo_logs import parse_line, load_networks, is_verified, summarize
from server import build_server
from mcp.client import Client

RANGES = {"creationTime": "2026-01-01T00:00:00.000000", "prefixes": [
    {"ipv4Prefix": "66.249.64.0/27"}, {"ipv6Prefix": "2001:4860:4801:10::/64"}]}
BOT = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"

def row(ip, path, status, agent=BOT):
    return f'{ip} - - [12/Oct/2026:10:00:00 +0000] "GET {path} HTTP/1.1" {status} 512 "-" "{agent}"'

LOG = [
    row("66.249.64.5", "/a/", 200), row("66.249.64.6", "/old/", 404), row("66.249.64.7", "/old/", 404),
    row("66.249.64.8", "/b/", 500), row("2001:4860:4801:10::1", "/c/", 200),
    row("203.0.113.9", "/fake/", 404),                         # claims Googlebot, wrong IP
    row("198.51.100.4", "/human/", 200, "Mozilla/5.0 Firefox"),  # not a bot at all
    "garbage line",
]

rec = parse_line(LOG[1])
assert rec["status"] == 404 and rec["path"] == "/old/" and rec["day"] == "12/Oct/2026"
assert parse_line("garbage line") is None

nets = load_networks(RANGES)
assert is_verified("66.249.64.5", nets) and is_verified("2001:4860:4801:10::1", nets)
assert not is_verified("203.0.113.9", nets) and not is_verified("not-an-ip", nets)
assert not is_verified("66.249.64.40", nets)                    # outside the /27

s = summarize(LOG, nets)
assert s["claimed_googlebot_requests"] == 6 and s["verified_googlebot_requests"] == 5
assert s["verified_status_counts"] == {200: 2, 404: 2, 500: 1}
assert s["verified_error_rate"] == 0.6
assert s["top_404_paths"] == [("/old/", 2)]                   # the fake /fake/ 404 is excluded
assert any("did not match" in w for w in s["warnings"]) and any("could not be parsed" in w for w in s["warnings"])
assert "66.249.64.5" not in json.dumps(s)                       # no raw log data leaks out
assert summarize([], nets)["verified_error_rate"] is None

async def end_to_end():
    with tempfile.TemporaryDirectory() as d:
        log, rng = os.path.join(d, "access.log"), os.path.join(d, "googlebot.json")
        open(log, "w").write("\n".join(LOG)); open(rng, "w").write(json.dumps(RANGES))
        async with Client(build_server(log, rng)) as client:
            tools = (await client.list_tools()).tools
            assert [t.name for t in tools] == ["googlebot_summary"]
            result = await client.call_tool("googlebot_summary", {"max_rows": 5})
            data = json.loads(result.content[0].text)
            assert data["verified_googlebot_requests"] == 5 and data["top_404_paths"][0][0] == "/old/"
asyncio.run(end_to_end())
print("all tests passed")

Save the three files together, install the SDK with pip install mcp, and run the tests with Python 3. In our run, python3 test_seo_logs.py printed all tests passed. We also ran the server over stdio with a real client connection and received the summary.

Step 4: Connect It to a Client

A local stdio server is started by the client. In Claude Desktop, according to the MCP project's guide to local servers, you open Settings, choose the Developer tab, select Edit Config and add an entry under mcpServers with a command and args, using absolute paths, then restart the app. For this server the entry would look like this, with your own paths:

{
  "mcpServers": {
    "seo-logs": {
      "command": "python3",
      "args": ["/absolute/path/server.py", "/var/log/nginx/access.log", "/absolute/path/googlebot.json"]
    }
  }
}

Other clients have their own settings screens or commands, and some only connect to remote servers, which means hosting the server over Streamable HTTP with authentication. Check each client's documentation for what it supports and for the approval prompts it shows before tool calls. Once connected, start with a question that exercises the tool, such as "Summarize Googlebot activity in the log and tell me what the 404s have in common," then check the answer against the log.

Design Rules for Safer SEO Tools

  • Keep tools read-only first. If you add anything that creates alerts, exports data or starts crawls, make it a separate tool and rely on the client's confirmation step, since MCP also lets servers ask users for input.
  • Return warnings with the data. The summary says how many claimed bot requests were excluded and how many lines failed to parse, so a number never travels without its caveat.
  • Cap and aggregate. Limit rows, avoid raw log lines and strip anything personal before it reaches a model.
  • State the data source and date range. If an answer does not say which log and period it used, ask for them. The sample module does not filter by date, so add that before relying on it for time-based questions.
  • Protect access. For a remote server, use authentication and revocable tokens, and review what the server can reach.
  • Verify before reporting. Treat recommendations as a first pass and confirm them in the source system.

Hosted MCP Servers From SEO Platforms

Building your own server makes sense when the data is yours, such as server logs, or when you need control over what is exposed. Several SEO platforms also host MCP servers so you do not have to build one. For example, JetOctopus’s SEO MCP offers a server that, according to its documentation, connects AI clients to crawl data, server logs, Search Console and Google Analytics 4. Evaluate any hosted server on the same points as your own: which data sources it covers, whether actions with side effects ask for confirmation, what it logs, whether its answers link back to the underlying data and what your plan allows. The Stack Overflow figures above are a reminder to check an assistant's output against the source either way.

Limits of This Server

  • It reads one log file in combined format. Other formats and rotated or compressed logs need more code.
  • It matches IPs against a range file you download, so a stale file undercounts verified requests. A reverse DNS check is the other method Google documents.
  • It has no date filter, no per-URL drill-down and no Search Console or analytics data. Those would be separate tools, each with its own tests.
  • Reading a whole log on every call is fine for small files and slow for large ones. Index or pre-aggregate before exposing big logs.
  • Counts from logs depend on logging configuration and caching layers, so they may not equal what Search Console reports.

Frequently Asked Questions

Do I need a hosted server to use MCP with SEO data?

No. A local stdio server like the one above works with clients that support local servers. Hosted servers are convenient when a vendor already covers the data sources you need.

Can the assistant change anything with this server?

Not as written. The only tool reads a log file and returns aggregates. Add write actions only deliberately, as separate tools with confirmation.

Why verify Googlebot instead of trusting the user agent?

Any client can send a Googlebot user agent. Matching the IP against Google's published ranges keeps fake traffic out of the numbers that matter.

How much should I trust the assistant's answers?

Treat them as claims to check. Surveys such as Stack Overflow's show that many developers distrust AI accuracy, so keep the source data one click away.

Conclusion

MCP turns SEO data into something an assistant can query, but the value depends on the design of the server. A small read-only tool that verifies bots, aggregates results and reports its own caveats is more useful than a broad one that returns everything. Start with one tool and tests, connect it to a client, check its answers against the source and expand only when each new tool has its own safeguards.

proton_pass_2026_11_footer
Source: Div John · www.sitepoint.com