Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(api): align NLP Moz and GSC behaviors

Danielc938a78e2b0c
diff --git a/scripts/backlinks_auth.py b/scripts/backlinks_auth.py
index c9d96d8..0e332b2 100644
--- a/scripts/backlinks_auth.py
+++ b/scripts/backlinks_auth.py
@@ -128,7 +128,13 @@ def check_credentials(service: str) -> dict:
api_key = config.get("moz_api_key")
if api_key:
result["available"] = True
- result["method"] = "api_key"
+ result["method"] = "api_key_configured"
+ result["verified"] = False
+ result["note"] = (
+ "Moz credentials are configured but not live-verified by --check. "
+ "Run a Moz command such as `python scripts/moz_api.py metrics "
+ "example.com --json` to test quota and permissions."
+ )
else:
result["error"] = (
"No Moz API key found. Set MOZ_API_KEY environment variable "
@@ -140,14 +146,20 @@ def check_credentials(service: str) -> dict:
api_key = config.get("bing_api_key")
if api_key:
result["available"] = True
- result["method"] = "api_key"
+ result["method"] = "api_key_configured"
+ result["verified"] = False
sites = config.get("bing_verified_sites", [])
if sites:
result["verified_sites"] = sites
+ result["note"] = (
+ "Bing credentials and site list are configured but not live-verified "
+ "by --check. Run a Bing Webmaster query to test access."
+ )
else:
result["note"] = (
- "No verified sites listed. Add 'bing_verified_sites' to config "
- "for site-specific backlink queries."
+ "Bing API key is configured but not live-verified. No verified "
+ "sites are listed; add 'bing_verified_sites' to config for "
+ "site-specific backlink queries."
)
else:
result["error"] = (
@@ -310,6 +322,9 @@ TIER 1: MOZ API (free signup, 2,500 rows/month)
Provides: Domain Authority, Page Authority, Spam Score, link counts,
referring domains, anchor text distribution (any domain).
Rate limit: 1 request per 10 seconds.
+ Note: `--check moz` reports whether credentials are configured; run
+ `python scripts/moz_api.py metrics example.com --json` for a live
+ permission/quota test.
TIER 2: + BING WEBMASTER TOOLS API (free, verified sites)
-----------------------------------------------------------
@@ -344,6 +359,8 @@ PREMIUM: DATAFORSEO EXTENSION (paid, most comprehensive)
VERIFY CONFIGURATION:
python scripts/backlinks_auth.py --check
python scripts/backlinks_auth.py --tier
+ `--check` is configuration-only for Moz/Bing and does not claim live
+ verification unless a specific API query has been run.
""")
diff --git a/scripts/gsc_query.py b/scripts/gsc_query.py
index 7385f2f..10120f8 100644
--- a/scripts/gsc_query.py
+++ b/scripts/gsc_query.py
@@ -36,6 +36,11 @@ except ImportError:
from google_auth import get_oauth_credentials, load_config
GSC_SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"]
+INDEXATION_NOTE = (
+ "Sitemaps API contents[].submitted reflects submitted URL counts only. "
+ "Use the URL Inspection API as the indexation truth for whether specific "
+ "URLs are indexed."
+)
def _build_gsc_service():
@@ -229,6 +234,10 @@ def list_sitemaps(site_url: str) -> dict:
try:
response = service.sitemaps().list(siteUrl=site_url).execute()
for sm in response.get("sitemap", []):
+ contents = [
+ {k: v for k, v in item.items() if k != "indexed"}
+ for item in sm.get("contents", [])
+ ]
result["sitemaps"].append({
"path": sm.get("path"),
"last_submitted": sm.get("lastSubmitted"),
@@ -237,7 +246,8 @@ def list_sitemaps(site_url: str) -> dict:
"type": sm.get("type"),
"warnings": sm.get("warnings", 0),
"errors": sm.get("errors", 0),
- "contents": sm.get("contents", []),
+ "contents": contents,
+ "indexation_note": INDEXATION_NOTE,
})
except Exception as e:
result["error"] = f"Error listing sitemaps: {e}"
@@ -360,6 +370,8 @@ def main():
for sm in result.get("sitemaps", []):
status = "pending" if sm.get("is_pending") else "processed"
print(f" {sm['path']} [{status}] errors={sm.get('errors', 0)} warnings={sm.get('warnings', 0)}")
+ if result.get("sitemaps"):
+ print(f"\nNote: {INDEXATION_NOTE}")
else:
totals = result.get("totals", {})
print(f"=== Search Analytics: {prop} ===")
diff --git a/scripts/moz_api.py b/scripts/moz_api.py
index 20cf7c4..b091106 100644
--- a/scripts/moz_api.py
+++ b/scripts/moz_api.py
@@ -14,6 +14,7 @@ Usage:
"""
import argparse
+import base64
import json
import sys
import time
@@ -45,6 +46,21 @@ RATE_LIMIT_DELAY = 10
RATE_LIMIT_FILE = os.path.expanduser("~/.cache/claude-seo/moz_last_request.lock")
+def _moz_basic_auth_header(api_key: str) -> str | None:
+ """Return a Basic auth header for accessId:secret credentials."""
+ if ":" in api_key:
+ encoded = base64.b64encode(api_key.encode("utf-8")).decode("ascii")
+ return f"Basic {encoded}"
+
+ try:
+ decoded = base64.b64decode(api_key, validate=True).decode("utf-8")
+ except (ValueError, UnicodeDecodeError):
+ return None
+ if ":" not in decoded:
+ return None
+ return f"Basic {api_key}"
+
+
def _rate_limit():
"""Enforce Moz free tier rate limit: 1 request per 10 seconds.
@@ -93,9 +109,13 @@ def _moz_request(path: str, body: dict, api_key: str) -> dict:
headers = {
"Content-Type": "application/json",
- "x-moz-token": api_key,
"User-Agent": "ClaudeSEO/1.8.0",
}
+ basic_auth = _moz_basic_auth_header(api_key)
+ if basic_auth:
+ headers["Authorization"] = basic_auth
+ else:
+ headers["x-moz-token"] = api_key
try:
response = requests.post(
diff --git a/scripts/nlp_analyze.py b/scripts/nlp_analyze.py
index fa4b85b..60717fe 100644
--- a/scripts/nlp_analyze.py
+++ b/scripts/nlp_analyze.py
@@ -42,6 +42,7 @@ except ImportError:
from url_safety import URLSafetyError, safe_requests_get
NLP_ENDPOINT = "https://language.googleapis.com/v2/documents:annotateText"
+NLP_V1_ENTITIES_ENDPOINT = "https://language.googleapis.com/v1/documents:analyzeEntities"
# Free tier: 5,000 units/month per feature
# Paid: $0.001 per 1,000-character unit for entity/sentiment
@@ -90,19 +91,71 @@ def analyze_text(
if features is None:
features = ["entities", "sentiment", "classify"]
- # Build request
+ document = {
+ "type": "PLAIN_TEXT",
+ "content": text[:100000], # API limit
+ "languageCode": language,
+ }
+
+ # Entities still use v1 because it returns Knowledge Graph metadata
+ # and salience consistently. Other features stay on v2 annotateText.
+ wants_entities = "entities" in features
+ if wants_entities:
+ body = {
+ "document": document,
+ "encodingType": "UTF8",
+ }
+ try:
+ resp = requests.post(
+ NLP_V1_ENTITIES_ENDPOINT,
+ headers=google_api_key_headers(key),
+ json=body,
+ timeout=30,
+ )
+
+ if resp.status_code == 403:
+ result["error"] = (
+ "Cloud Natural Language API access denied. Enable it in "
+ "GCP Console: APIs & Services > Library > Cloud Natural Language API. "
+ "Billing must be enabled on the project."
+ )
+ return result
+
+ if resp.status_code == 429:
+ result["error"] = "NLP API quota exceeded. Free tier: 5,000 units/month."
+ return result
+
+ resp.raise_for_status()
+ entity_data = resp.json()
+ except requests.exceptions.RequestException as e:
+ result["error"] = f"NLP API request failed: {redact_google_api_key(e)}"
+ return result
+
+ for entity in entity_data.get("entities", []):
+ mentions = entity.get("mentions", [])
+ result["entities"].append({
+ "name": entity.get("name", ""),
+ "type": entity.get("type", "UNKNOWN"),
+ "salience": round(entity.get("salience", 0), 4),
+ "sentiment_score": entity.get("sentiment", {}).get("score"),
+ "sentiment_magnitude": entity.get("sentiment", {}).get("magnitude"),
+ "mention_count": len(mentions),
+ "metadata": entity.get("metadata", {}),
+ })
+
+ result["entities"].sort(key=lambda e: e["salience"], reverse=True)
+
feature_map = {}
for f in features:
api_feature = FEATURES.get(f)
- if api_feature:
+ if api_feature and api_feature != "extractEntities":
feature_map[api_feature] = True
+ if not feature_map:
+ return result
+
body = {
- "document": {
- "type": "PLAIN_TEXT",
- "content": text[:100000], # API limit
- "languageCode": language,
- },
+ "document": document,
"features": feature_map,
"encodingType": "UTF8",
}
@@ -133,22 +186,6 @@ def analyze_text(
result["error"] = f"NLP API request failed: {redact_google_api_key(e)}"
return result
- # Entities
- for entity in data.get("entities", []):
- mentions = entity.get("mentions", [])
- result["entities"].append({
- "name": entity.get("name", ""),
- "type": entity.get("type", "UNKNOWN"),
- "salience": round(entity.get("salience", 0), 4),
- "sentiment_score": entity.get("sentiment", {}).get("score"),
- "sentiment_magnitude": entity.get("sentiment", {}).get("magnitude"),
- "mention_count": len(mentions),
- "metadata": entity.get("metadata", {}),
- })
-
- # Sort by salience (most important first)
- result["entities"].sort(key=lambda e: e["salience"], reverse=True)
-
# Document sentiment
doc_sentiment = data.get("documentSentiment", {})
if doc_sentiment:
diff --git a/skills/seo-google/SKILL.md b/skills/seo-google/SKILL.md
index 16cb635..7bd554a 100644
--- a/skills/seo-google/SKILL.md
+++ b/skills/seo-google/SKILL.md
@@ -144,7 +144,9 @@ Batch inspection from a file (one URL per line). Rate limited to 2,000/day per s
### `/seo google sitemaps <property>`
-List submitted sitemaps with status, errors, warnings.
+List submitted sitemaps with status, errors, warnings. Sitemap contents report
+submitted counts only; URL Inspection API is the indexation truth for whether
+specific URLs are indexed.
**Script:** `python scripts/gsc_query.py sitemaps --property <property> --json`
diff --git a/tests/test_google_api_key_safety.py b/tests/test_google_api_key_safety.py
index 72a3191..1185b5b 100644
--- a/tests/test_google_api_key_safety.py
+++ b/tests/test_google_api_key_safety.py
@@ -114,7 +114,11 @@ def test_nlp_uses_header_and_redacts_errors() -> None:
return _ErrorResponse(url)
with patch.object(nlp_analyze.requests, "post", side_effect=fake_post):
- result = nlp_analyze.analyze_text("Kenya has marathon runners.", api_key=SECRET)
+ result = nlp_analyze.analyze_text(
+ "Kenya has marathon runners.",
+ features=["sentiment"],
+ api_key=SECRET,
+ )
assert captured["url"] == nlp_analyze.NLP_ENDPOINT
assert captured["headers"]["X-Goog-Api-Key"] == SECRET
diff --git a/tests/test_gsc_query.py b/tests/test_gsc_query.py
new file mode 100644
index 0000000..224846f
--- /dev/null
+++ b/tests/test_gsc_query.py
@@ -0,0 +1,65 @@
+"""Google Search Console sitemap output regressions."""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+from unittest.mock import patch
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+_SCRIPTS = REPO_ROOT / "scripts"
+if str(_SCRIPTS) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS))
+
+import gsc_query # noqa: E402
+
+
+class FakeExecute:
+ def execute(self) -> dict:
+ return {
+ "sitemap": [
+ {
+ "path": "https://example.com/sitemap.xml",
+ "lastSubmitted": "2026-01-01T00:00:00Z",
+ "isPending": False,
+ "isSitemapsIndex": False,
+ "type": "sitemap",
+ "warnings": 0,
+ "errors": 0,
+ "contents": [
+ {"type": "web", "submitted": 10, "indexed": 7},
+ {"type": "image", "submitted": 4},
+ ],
+ }
+ ]
+ }
+
+
+class FakeSitemaps:
+ def list(self, siteUrl: str):
+ return FakeExecute()
+
+
+class FakeService:
+ def sitemaps(self):
+ return FakeSitemaps()
+
+
+def test_sitemaps_strip_deprecated_indexed_counts_and_point_to_url_inspection() -> None:
+ with patch.object(gsc_query, "_build_gsc_service", return_value=FakeService()):
+ result = gsc_query.list_sitemaps("sc-domain:example.com")
+
+ sitemap = result["sitemaps"][0]
+ assert result["error"] is None
+ assert all("indexed" not in item for item in sitemap["contents"])
+ assert sitemap["contents"][0] == {"type": "web", "submitted": 10}
+ assert "URL Inspection API" in sitemap["indexation_note"]
+
+
+def test_seo_google_docs_identify_url_inspection_as_indexation_truth() -> None:
+ text = (REPO_ROOT / "skills" / "seo-google" / "SKILL.md").read_text(encoding="utf-8")
+ sitemap_section = text[text.index("### `/seo google sitemaps <property>`"):]
+ assert "URL Inspection API" in sitemap_section
+ assert "indexation truth" in sitemap_section
diff --git a/tests/test_moz_api.py b/tests/test_moz_api.py
new file mode 100644
index 0000000..79cf8ef
--- /dev/null
+++ b/tests/test_moz_api.py
@@ -0,0 +1,81 @@
+"""Moz API authentication and credential-status regressions."""
+
+from __future__ import annotations
+
+import base64
+import os
+import sys
+from unittest.mock import patch
+
+
+_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")
+if _SCRIPTS not in sys.path:
+ sys.path.insert(0, _SCRIPTS)
+
+import backlinks_auth # noqa: E402
+import moz_api # noqa: E402
+
+
+class FakeResponse:
+ status_code = 200
+ text = ""
+
+ def json(self) -> dict:
+ return {"results": []}
+
+
+def test_moz_request_supports_colon_credentials_as_http_basic() -> None:
+ captured: dict = {}
+
+ def fake_post(url: str, **kwargs):
+ captured.update({"url": url, **kwargs})
+ return FakeResponse()
+
+ with patch.object(moz_api, "_rate_limit"), \
+ patch.object(moz_api.requests, "post", side_effect=fake_post):
+ result = moz_api._moz_request("/v2/url_metrics", {"targets": ["example.com"]}, "access-id:secret")
+
+ expected = base64.b64encode(b"access-id:secret").decode("ascii")
+ assert result["status"] == "success"
+ assert captured["headers"]["Authorization"] == f"Basic {expected}"
+ assert "x-moz-token" not in captured["headers"]
+
+
+def test_moz_request_accepts_preencoded_basic_credentials() -> None:
+ captured: dict = {}
+ encoded = base64.b64encode(b"access-id:secret").decode("ascii")
+
+ def fake_post(url: str, **kwargs):
+ captured.update(kwargs)
+ return FakeResponse()
+
+ with patch.object(moz_api, "_rate_limit"), \
+ patch.object(moz_api.requests, "post", side_effect=fake_post):
+ moz_api._moz_request("/v2/url_metrics", {"targets": ["example.com"]}, encoded)
+
+ assert captured["headers"]["Authorization"] == f"Basic {encoded}"
+ assert "x-moz-token" not in captured["headers"]
+
+
+def test_moz_request_keeps_v2_token_header_for_plain_api_keys() -> None:
+ captured: dict = {}
+
+ def fake_post(url: str, **kwargs):
+ captured.update(kwargs)
+ return FakeResponse()
+
+ with patch.object(moz_api, "_rate_limit"), \
+ patch.object(moz_api.requests, "post", side_effect=fake_post):
+ moz_api._moz_request("/v2/url_metrics", {"targets": ["example.com"]}, "mozscape-key")
+
+ assert captured["headers"]["x-moz-token"] == "mozscape-key"
+ assert "Authorization" not in captured["headers"]
+
+
+def test_configured_moz_credentials_are_not_reported_live_verified() -> None:
+ with patch.object(backlinks_auth, "load_config", return_value={"moz_api_key": "mozscape-key"}):
+ result = backlinks_auth.check_credentials("moz")
+
+ assert result["available"] is True
+ assert result["verified"] is False
+ assert "not live-verified" in result["note"]
diff --git a/tests/test_nlp_analyze.py b/tests/test_nlp_analyze.py
new file mode 100644
index 0000000..8b4cdb6
--- /dev/null
+++ b/tests/test_nlp_analyze.py
@@ -0,0 +1,89 @@
+"""Functional tests for Google Cloud Natural Language routing."""
+
+from __future__ import annotations
+
+import os
+import sys
+from unittest.mock import patch
+
+
+_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")
+if _SCRIPTS not in sys.path:
+ sys.path.insert(0, _SCRIPTS)
+
+import nlp_analyze # noqa: E402
+
+
+class FakeResponse:
+ def __init__(self, payload: dict, status_code: int = 200) -> None:
+ self._payload = payload
+ self.status_code = status_code
+ self.text = ""
+
+ def raise_for_status(self) -> None:
+ return None
+
+ def json(self) -> dict:
+ return self._payload
+
+
+def test_entity_extraction_uses_v1_and_other_features_use_v2() -> None:
+ calls: list[dict] = []
+
+ def fake_post(url: str, **kwargs):
+ calls.append({"url": url, **kwargs})
+ if url == nlp_analyze.NLP_V1_ENTITIES_ENDPOINT:
+ return FakeResponse({
+ "entities": [
+ {
+ "name": "Kenya",
+ "type": "LOCATION",
+ "salience": 0.9,
+ "metadata": {
+ "mid": "/m/019rg5",
+ "wikipedia_url": "https://en.wikipedia.org/wiki/Kenya",
+ },
+ "mentions": [{"text": {"content": "Kenya"}}],
+ }
+ ]
+ })
+ return FakeResponse({
+ "documentSentiment": {"score": 0.4, "magnitude": 1.2},
+ "categories": [{"name": "/Sports", "confidence": 0.7}],
+ })
+
+ with patch.object(nlp_analyze.requests, "post", side_effect=fake_post):
+ result = nlp_analyze.analyze_text(
+ "Kenya has marathon runners.",
+ features=["entities", "sentiment", "classify"],
+ api_key="AIzaSyDUMMYSECRET",
+ )
+
+ assert [call["url"] for call in calls] == [
+ nlp_analyze.NLP_V1_ENTITIES_ENDPOINT,
+ nlp_analyze.NLP_ENDPOINT,
+ ]
+ assert "features" not in calls[0]["json"]
+ assert "extractEntities" not in calls[1]["json"]["features"]
+ assert result["entities"][0]["metadata"]["mid"] == "/m/019rg5"
+ assert result["entities"][0]["salience"] == 0.9
+ assert result["sentiment"]["tone"] == "positive"
+ assert result["categories"][0]["name"] == "/Sports"
+
+
+def test_entities_only_skips_v2_annotate_text_call() -> None:
+ calls: list[str] = []
+
+ def fake_post(url: str, **kwargs):
+ calls.append(url)
+ return FakeResponse({"entities": []})
+
+ with patch.object(nlp_analyze.requests, "post", side_effect=fake_post):
+ result = nlp_analyze.analyze_text(
+ "Kenya has marathon runners.",
+ features=["entities"],
+ api_key="AIzaSyDUMMYSECRET",
+ )
+
+ assert calls == [nlp_analyze.NLP_V1_ENTITIES_ENDPOINT]
+ assert result["error"] is None