Skip to content
This repository was archived by the owner on Jul 27, 2026. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion strands-mcp/src/strands_mcp_server/utils/cache.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import logging
import time
from typing import Dict

from ..config import doc_config
from . import doc_fetcher, indexer, text_processor

logger = logging.getLogger(__name__)

# Global state
_INDEX: indexer.IndexSearch | None = None
_URL_CACHE: Dict[str, doc_fetcher.Page | None] = {} # url -> Page (None if not fetched yet)
_URL_TITLES: Dict[str, str] = {} # url -> curated title from llms.txt
_LINKS_LOADED = False
_FAILED_FETCHES: Dict[str, float] = {} # url -> timestamp of last failed attempt

SNIPPET_HYDRATE_MAX = 5 # how many top results to hydrate with content
NEGATIVE_CACHE_TTL = 300 # seconds to wait before retrying a failed URL


def load_links_only() -> None:
Expand Down Expand Up @@ -64,17 +70,29 @@ def ensure_page(url: str) -> doc_fetcher.Page | None:
Returns:
The cached or newly fetched Page object, or None if fetch failed

Negative caching: failed URLs are remembered for ``NEGATIVE_CACHE_TTL``
seconds so that repeated calls in the same session don't waste time on
serial timeouts.

"""
page = _URL_CACHE.get(url)
if page is not None:
return page

# Negative cache hit — skip the fetch if the last failure is recent
last_fail = _FAILED_FETCHES.get(url)
if last_fail is not None and time.monotonic() - last_fail < NEGATIVE_CACHE_TTL:
return None

try:
raw = doc_fetcher.fetch_and_clean(url)
display_title = text_processor.format_display_title(url, raw.title, _URL_TITLES)
page = doc_fetcher.Page(url=url, title=display_title, content=raw.content)
_URL_CACHE[url] = page
return page
except Exception:
except Exception as exc:
_FAILED_FETCHES[url] = time.monotonic()
logger.warning("Failed to fetch %s: %s", url, exc)
return None


Expand Down
105 changes: 105 additions & 0 deletions strands-mcp/tests/test_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""Tests for cache module — negative caching and page loading."""

from unittest.mock import patch

import pytest

from strands_mcp_server.utils import cache, doc_fetcher


@pytest.fixture(autouse=True)
def _reset_globals():
"""Reset cache globals before each test."""
cache._URL_CACHE.clear()
cache._URL_TITLES.clear()
cache._LINKS_LOADED = False
cache._FAILED_FETCHES.clear()


class TestNegativeCache:
"""Tests that failed fetches are negatively cached to avoid serial timeouts."""

def test_swallowed_error_no_longer_silent(self):
"""Exception in ensure_page is now logged, not silently swallowed."""
with patch.object(cache, "logger") as mock_logger, patch.object(
doc_fetcher, "fetch_and_clean", side_effect=ConnectionError("timeout")
):
tru_result = cache.ensure_page("https://strandsagents.com/broken.md")

assert tru_result is None
mock_logger.warning.assert_called_once()
args, _ = mock_logger.warning.call_args
assert "https://strandsagents.com/broken.md" in str(args)

def test_consecutive_call_within_ttl_returns_none(self):
"""Repeated calls within negative cache TTL skip the fetch."""
with patch.object(doc_fetcher, "fetch_and_clean", side_effect=ConnectionError("timeout")):
# First call — fails, records the failure
tru_first = cache.ensure_page("https://strandsagents.com/broken.md")
assert tru_first is None

# Second call — should hit negative cache, not call fetch_and_clean
with patch.object(doc_fetcher, "fetch_and_clean") as mock_fetch:
tru_second = cache.ensure_page("https://strandsagents.com/broken.md")

assert tru_second is None
mock_fetch.assert_not_called()

def test_successful_fetch_after_ttl_expiry_stores_in_positive_cache(self):
"""After blackout window expires, a retry succeeds and URL moves to positive cache."""
url = "https://strandsagents.com/valid.md"
failed_at = 100.0
page = doc_fetcher.Page(url=url, title="Valid Doc", content="Some content.")

# First call fails — stored in _FAILED_FETCHES at timestamp 100.0
with (
patch.object(cache.time, "monotonic", return_value=failed_at),
patch.object(doc_fetcher, "fetch_and_clean", side_effect=ConnectionError("timeout")),
):
assert cache.ensure_page(url) is None
assert cache._FAILED_FETCHES.get(url) == failed_at
assert cache._URL_CACHE.get(url) is None

# Advance clock past TTL boundary — retry the fetch
with (
patch.object(cache.time, "monotonic", return_value=failed_at + cache.NEGATIVE_CACHE_TTL),
patch.object(doc_fetcher, "fetch_and_clean", return_value=page),
):
tru_result = cache.ensure_page(url)

assert tru_result is not None
assert tru_result.title == "Valid Doc"
# URL should be in the positive cache now
assert cache._URL_CACHE.get(url) is not None

def test_no_negative_cache_for_same_url_different_session_after_ttl(self):
"""After TTL expires, the fetch is retried."""
url = "https://strandsagents.com/retry.md"
failed_at = 200.0
page = doc_fetcher.Page(url=url, title="Retry Doc", content="Content now available.")

# First call fails — stored in _FAILED_FETCHES at timestamp 200.0
with (
patch.object(cache.time, "monotonic", return_value=failed_at),
patch.object(doc_fetcher, "fetch_and_clean", side_effect=ConnectionError("timeout")),
):
assert cache.ensure_page(url) is None
assert cache._FAILED_FETCHES.get(url) == failed_at

# Hit negative cache (just before expiry)
with (
patch.object(cache.time, "monotonic", return_value=failed_at + cache.NEGATIVE_CACHE_TTL - 0.001),
patch.object(doc_fetcher, "fetch_and_clean") as mock_fetch,
):
assert cache.ensure_page(url) is None
mock_fetch.assert_not_called()

# Advance past TTL boundary — fetch is retried
with (
patch.object(cache.time, "monotonic", return_value=failed_at + cache.NEGATIVE_CACHE_TTL),
patch.object(doc_fetcher, "fetch_and_clean", return_value=page),
):
tru_result = cache.ensure_page(url)

assert tru_result is not None
assert tru_result.title == "Retry Doc"