fix(unbrowse): surface target HTTP errors in fetched pages (#7257)

* fix(unbrowse): surface target HTTP errors in fetched pages

* fix(unbrowse): retain empty-page status and final URL
This commit is contained in:
kunkun403 2026-10-23 22:49:45 -04:00 committed by GitHub
parent 46da5008cd
commit 991459829b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 86 additions and 3 deletions

View File

@ -186,6 +186,8 @@ streams simulate chunks from a non-streaming response, while no-tool streams sta
Serper web and image search preserve valid entries in mixed result lists. A malformed `organic`/`images` container, or a non-empty list holding no object entries, returns Serper's format error; missing, null, or empty containers keep the existing "No results found" / "No images found" response. Format errors log the container field name only, without queries, credentials, or payload values.
Unbrowse web fetch preserves the extracted text but prefixes a warning when the target page's HTTP status is 400–599, even when the scraping service itself returns a successful response. Empty-page errors retain that status too, and both messages include the reported final URL when available.
Tencent Cloud WSA web search contains malformed HTTP-success payloads the same way: a `Pages` container that is not a list, or a non-empty container holding no usable page, returns the provider's format error, while malformed page entries in an otherwise valid container are skipped so the valid rows survive. Missing, null, or empty `Pages` keep the existing "No results found" response.
Serply web search contains malformed HTTP-success payloads the same way in every vertical: a `results`/`entries`/`articles` container that is not a list, or a non-empty list with no object entries, returns the provider's format error, while non-object entries in an otherwise valid list are skipped in order. Missing, null, or empty containers keep the existing "No results found" response.

View File

@ -165,10 +165,19 @@ def web_fetch_tool(url: str) -> str:
if error is not None:
return f"Error: {error}"
metadata = data.get("metadata")
status = metadata.get("statusCode") if isinstance(metadata, dict) else None
failure = ""
if isinstance(status, int) and not isinstance(status, bool) and 400 <= status <= 599:
failure = f"target page responded with HTTP {status}"
final_url = data.get("finalUrl")
if isinstance(final_url, str) and final_url.strip():
failure += f" (final URL: {final_url.strip()})"
content = _clip(data.get("markdown") or "", _UNBROWSE_FETCH_MAX_CHARS)
if not content:
return "Error: No content found"
return f"Error: No content found ({failure})" if failure else "Error: No content found"
metadata = data.get("metadata")
title = (metadata.get("title") if isinstance(metadata, dict) else None) or "Untitled"
return f"# {title}\n\n{content}"
warning = f"Warning: {failure}.\n\n" if failure else ""
return f"{warning}# {title}\n\n{content}"

View File

@ -0,0 +1,72 @@
"""Preserve the target HTTP status across both Unbrowse MCP payload forms."""
import json
from types import SimpleNamespace
import httpx
import pytest
from deerflow.community.unbrowse import tools
@pytest.mark.parametrize("structured", [False, True], ids=["text", "structured"])
@pytest.mark.parametrize("status", [400, 403, 404, 429, 500, 503, 599])
@pytest.mark.parametrize("markdown", ["Body", "", None])
def test_fetch_warns_about_target_http_failure(monkeypatch, structured, status, markdown):
result = _fetch(monkeypatch, structured, {"title": "Page", "statusCode": status}, markdown=markdown)
if markdown:
assert result == f"Warning: target page responded with HTTP {status}.\n\n# Page\n\nBody"
else:
assert result == f"Error: No content found (target page responded with HTTP {status})"
@pytest.mark.parametrize("structured", [False, True], ids=["text", "structured"])
@pytest.mark.parametrize("markdown", ["Body", "", None])
def test_fetch_reports_redirect_destination_for_target_failure(monkeypatch, structured, markdown):
result = _fetch(monkeypatch, structured, {"title": "Page", "statusCode": 404}, markdown=markdown, finalUrl="https://example.invalid/missing")
detail = "target page responded with HTTP 404 (final URL: https://example.invalid/missing)"
if markdown:
assert result == f"Warning: {detail}.\n\n# Page\n\nBody"
else:
assert result == f"Error: No content found ({detail})"
@pytest.mark.parametrize("structured", [False, True], ids=["text", "structured"])
@pytest.mark.parametrize("final_url", [None, "", " ", 42, {}, []])
def test_fetch_ignores_empty_or_non_string_final_url(monkeypatch, structured, final_url):
result = _fetch(monkeypatch, structured, {"statusCode": 404}, finalUrl=final_url)
assert result == "Warning: target page responded with HTTP 404.\n\n# Untitled\n\nBody"
@pytest.mark.parametrize("structured", [False, True], ids=["text", "structured"])
@pytest.mark.parametrize("markdown", ["Body", "", None])
def test_fetch_preserves_success_response_with_final_url(monkeypatch, structured, markdown):
result = _fetch(monkeypatch, structured, {"statusCode": 200}, markdown=markdown, finalUrl="https://example.invalid/redirected")
assert result == ("# Untitled\n\nBody" if markdown else "Error: No content found")
@pytest.mark.parametrize("structured", [False, True], ids=["text", "structured"])
@pytest.mark.parametrize("metadata", [None, {}, {"statusCode": 200}, {"statusCode": 301}, {"statusCode": None}, {"statusCode": "404"}, {"statusCode": True}, {"statusCode": 404.5}, {"statusCode": []}, {"statusCode": 600}])
def test_fetch_preserves_response_without_valid_error_status(monkeypatch, structured, metadata):
assert _fetch(monkeypatch, structured, metadata) == "# Untitled\n\nBody"
def _fetch(monkeypatch, structured, metadata, markdown="Body", **fields):
payload = {"markdown": markdown, "metadata": metadata, **fields}
result = {"content": [{"type": "text", "text": json.dumps(payload)}], "isError": False}
if structured:
result["structuredContent"] = payload
requests = []
def respond(request):
requests.append(request)
assert json.loads(request.content)["params"]["name"] == "unbrowse.scrape"
return httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": result})
real_client = httpx.Client
transport = httpx.MockTransport(respond)
monkeypatch.setattr(tools.httpx, "Client", lambda **kwargs: real_client(transport=transport, **kwargs))
monkeypatch.setattr(tools, "get_app_config", lambda: SimpleNamespace(get_tool_config=lambda _: SimpleNamespace(model_extra={"api_key": "synthetic"})))
output = tools.web_fetch_tool.invoke({"url": "https://example.invalid/page"})
assert len(requests) == 1
return output