Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

[codex] Document and auto-detect Xiaohongshu source (#766)

yzyc410a2d141d8
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index d0f2f31a..d769a028 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -145,6 +145,7 @@ python3 skills/last30days/scripts/last30days.py "MCP servers" \
| Threads | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `threads` | Threads items | 10K free calls |
| Pinterest | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `pinterest` | Pinterest items | 10K free calls |
| LinkedIn | `SCRAPECREATORS_API_KEY` + `INCLUDE_SOURCES` contains `linkedin` | LinkedIn posts + articles (articles rank as high signal on person topics) | 10K free calls; power-user opt-in, not offered during first-run onboarding |
+| Xiaohongshu (RED) | logged-in x-mcp browser plugin or `xiaohongshu-mcp` service; optional `XIAOHONGSHU_API_BASE` for custom URLs | requested-only via `--search xhs` or `--search xiaohongshu`; auto-probes `http://localhost:18060` then `http://host.docker.internal:18060` | no last30days API key; depends on your local browser-session service |
| Bluesky | `BSKY_HANDLE` + `BSKY_APP_PASSWORD` | Bluesky items | yes (app password at bsky.app) |
| TruthSocial | `TRUTHSOCIAL_TOKEN` | TruthSocial items | yes |
| Web search | one of: `BRAVE_API_KEY`, `EXA_API_KEY`, `SERPER_API_KEY`, `PARALLEL_API_KEY` | `--auto-resolve` and Step 2 supplements | Brave has a free tier; native WebSearch on Claude Code / Codex / Gemini works as a fallback |
@@ -167,6 +168,9 @@ BRAVE_API_KEY=<your-brave-key>
# Optional sources
SCRAPECREATORS_API_KEY=<your-scrapecreators-key>
INCLUDE_SOURCES=tiktok,instagram
+# Xiaohongshu is requested-only: run with --search xhs after starting a local
+# browser-session service. Defaults probe localhost, then host.docker.internal.
+# XIAOHONGSHU_API_BASE=http://localhost:18060
# Add perplexity to INCLUDE_SOURCES when you want the paid Perplexity source.
# PERPLEXITY_API_KEY=<your-perplexity-key>
# INCLUDE_SOURCES=tiktok,instagram,perplexity
@@ -316,7 +320,7 @@ By default the engine decides the source set per query (everything available, mi
LAST30DAYS_DEFAULT_SEARCH=reddit,x,youtube,hn
```
-Accepts the same comma-separated names and aliases as `--search` (`web` → grounding, `hn` → hackernews, `bsky` → bluesky). Precedence: an explicit `--search` on the command line always wins; `LAST30DAYS_DEFAULT_SEARCH` applies only when the flag is omitted; when neither is set, per-query behavior is unchanged. `INCLUDE_SOURCES` / `EXCLUDE_SOURCES` keep their existing additive/subtractive roles on whichever set is selected.
+Accepts the same comma-separated names and aliases as `--search` (`web` → grounding, `hn` → hackernews, `bsky` → bluesky, `xhs` → xiaohongshu). Precedence: an explicit `--search` on the command line always wins; `LAST30DAYS_DEFAULT_SEARCH` applies only when the flag is omitted; when neither is set, per-query behavior is unchanged. `INCLUDE_SOURCES` / `EXCLUDE_SOURCES` keep their existing additive/subtractive roles on whichever set is selected.
### Audience register (`LAST30DAYS_REGISTER`)
diff --git a/README.md b/README.md
index 625a692f..6b701d47 100644
--- a/README.md
+++ b/README.md
@@ -77,11 +77,12 @@ If you're meeting with a CEO, have you read all their tweets and YouTube transcr
| **StockTwits** | Trader sentiment. Auto-activates when your topic is a ticker or crypto. |
| **Threads** | The post-Twitter text layer. Conversations from creators and brands. |
| **Pinterest** | Visual discovery. Pins, saves, and comments on products and ideas. |
+| **Xiaohongshu (RED)** | Chinese lifestyle, product, and creator signals. Requested explicitly with `--search xhs` when a logged-in x-mcp browser plugin or `xiaohongshu-mcp` service is running locally. |
| **Bluesky** | The decentralized social layer. AT Protocol posts from the post-Twitter migration. |
| **Perplexity** | Grounded Sonar synthesis, raw Search API rows, and Deep Research. |
| **Web** | The editorial coverage, the blog comparisons. One signal of many, not the only one. |
-Community contributors keep adding more. Truth Social, Xiaohongshu (RED), and others are in the engine with more on the way.
+Community contributors keep adding more. Truth Social and other niche sources are in the engine with more on the way.
A Reddit thread with 1,500 upvotes is a stronger signal than a blog post nobody read. A TikTok with 3.6M views tells you more about what's culturally relevant than a press release. Polymarket odds backed by $66K in volume are harder to argue with than a pundit's guess.
@@ -289,6 +290,7 @@ These platforms don't have relationships with each other. X doesn't know what Re
| YouTube | `brew install yt-dlp` | Free |
| Bluesky | App password from bsky.app | Free |
| TikTok + Instagram + Threads + Pinterest + LinkedIn + YouTube comments | ScrapeCreators key | 10,000 free calls, then PAYG |
+| Xiaohongshu (RED) | Run a logged-in x-mcp browser plugin or `xiaohongshu-mcp` service and request it with `--search xhs`; last30days auto-probes `http://localhost:18060` then `http://host.docker.internal:18060`, or use `XIAOHONGSHU_API_BASE` for a custom URL | No last30days API key; depends on your local browser-session service |
| Perplexity Sonar / Search API / Deep Research | Perplexity key, or OpenRouter key as Sonar fallback | Pay as you go |
| Web search | Brave Search key | 2,000 free queries/month |
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index 21bb5c8e..eca9125a 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -28,6 +28,7 @@ metadata:
- BSKY_HANDLE
- BSKY_APP_PASSWORD
- TRUTHSOCIAL_TOKEN
+ - XIAOHONGSHU_API_BASE
bins:
- node
- python3
@@ -50,6 +51,8 @@ metadata:
- digg
- bluesky
- truthsocial
+ - xiaohongshu
+ - rednote
- trends
- recency
- news
@@ -588,6 +591,7 @@ The magic of /last30days is Reddit comments + X posts together - and both are fr
**Other optional sources (add anytime):**
- `PERPLEXITY_API_KEY=xxx` (or `OPENROUTER_API_KEY=xxx`) - AI-synthesized research with citations; set `INCLUDE_SOURCES=perplexity`.
+- `XIAOHONGSHU_API_BASE=http://localhost:18060` - Xiaohongshu/RED via a logged-in x-mcp browser plugin or `xiaohongshu-mcp` service; optional unless the local service runs on a custom URL. Request it per run with `--search xhs`.
- `BSKY_HANDLE=you.bsky.social` + `BSKY_APP_PASSWORD=xxx` - Bluesky (free app password).
- `BRAVE_API_KEY=xxx` or `EXA_API_KEY=xxx` - web search backends.
diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.py
index 51582c96..a89b60ae 100644
--- a/skills/last30days/scripts/lib/doctor.py
+++ b/skills/last30days/scripts/lib/doctor.py
@@ -405,7 +405,10 @@ def _pinterest_record(config):
def _xiaohongshu_record(config):
- requires = "xiaohongshu-mcp service (XIAOHONGSHU_API_BASE); requested-only"
+ requires = (
+ "logged-in Xiaohongshu browser-session service; requested-only "
+ "(--search xhs)"
+ )
entry = prescriptions.get("xiaohongshu", "service_unreachable")
if config.get("XIAOHONGSHU_API_BASE"):
return _record(
@@ -415,7 +418,15 @@ def _xiaohongshu_record(config):
"probed (doctor makes no network calls)"
),
)
- return _record(status="opt-in", requires=requires, fix=_fix_text(entry))
+ return _record(
+ status="opt-in",
+ requires=requires,
+ fix=_fix_text(entry),
+ note=(
+ "auto-probes http://localhost:18060 first, then "
+ "http://host.docker.internal:18060"
+ ),
+ )
def _jobs_record(config):
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 19ce59e6..7870132d 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -81,6 +81,12 @@ AUTH_SOURCE_NONE: AuthSource = "none"
AUTH_STATUS_OK: AuthStatus = "ok"
AUTH_STATUS_MISSING: AuthStatus = "missing"
+XIAOHONGSHU_DEFAULT_API_BASES = (
+ "http://localhost:18060",
+ "http://host.docker.internal:18060",
+)
+XIAOHONGSHU_RESOLVED_API_BASE_KEY = "_XIAOHONGSHU_API_BASE_RESOLVED"
+
@dataclass(frozen=True)
class OpenAIAuth:
@@ -1058,9 +1064,52 @@ def get_instagram_token(config: dict[str, Any]) -> str:
def get_xiaohongshu_api_base(config: dict[str, Any]) -> str:
"""Get Xiaohongshu HTTP API base URL.
- Defaults to host.docker.internal so OpenClaw Docker can reach host service.
+ The availability probe caches the first logged-in local service it finds so
+ the later search request uses the same browser-backed session endpoint.
"""
- return (config.get('XIAOHONGSHU_API_BASE') or "http://host.docker.internal:18060").rstrip("/")
+ cached = config.get(XIAOHONGSHU_RESOLVED_API_BASE_KEY)
+ if cached:
+ return str(cached).rstrip("/")
+
+ explicit = config.get("XIAOHONGSHU_API_BASE")
+ if explicit:
+ return str(explicit).rstrip("/")
+
+ return XIAOHONGSHU_DEFAULT_API_BASES[0]
+
+
+def _xiaohongshu_api_base_candidates(config: dict[str, Any]) -> list[str]:
+ explicit = config.get("XIAOHONGSHU_API_BASE")
+ if explicit:
+ return [str(explicit).rstrip("/")]
+
+ candidates: list[str] = []
+ cached = config.get(XIAOHONGSHU_RESOLVED_API_BASE_KEY)
+ if cached:
+ candidates.append(str(cached).rstrip("/"))
+
+ for base in XIAOHONGSHU_DEFAULT_API_BASES:
+ if base not in candidates:
+ candidates.append(base)
+ return candidates
+
+
+def _xiaohongshu_base_logged_in(base: str, http_module: Any) -> bool:
+ # Keep the health probe snappy, but allow one retry for transient hiccups.
+ health = http_module.get(f"{base}/health", timeout=3, retries=2)
+ if not isinstance(health, dict):
+ return False
+ if not health.get("success"):
+ return False
+
+ # Login checks can be slower because some services consult the browser
+ # profile/session, so use a slightly longer timeout than the health probe.
+ login = http_module.get(f"{base}/api/v1/login/status", timeout=8, retries=2)
+ is_logged_in = (
+ login.get("data", {}).get("is_logged_in")
+ if isinstance(login, dict) else False
+ )
+ return bool(is_logged_in)
def is_xiaohongshu_available(config: dict[str, Any]) -> bool:
@@ -1068,32 +1117,20 @@ def is_xiaohongshu_available(config: dict[str, Any]) -> bool:
# Import here to avoid heavy imports at module load.
from . import http
- base = get_xiaohongshu_api_base(config)
- try:
- # Keep health probe snappy, but allow one retry for transient hiccups.
- health = http.get(f"{base}/health", timeout=3, retries=2)
- if not isinstance(health, dict):
- return False
- if not health.get("success"):
- return False
-
- # Login probe can be slower on some deployments (browser/session checks),
- # so use a slightly longer timeout to avoid false negatives.
- login = http.get(f"{base}/api/v1/login/status", timeout=8, retries=2)
- is_logged_in = (
- login.get("data", {}).get("is_logged_in")
- if isinstance(login, dict) else False
- )
- return bool(is_logged_in)
- except (OSError, http.HTTPError):
- return False
- except Exception as exc:
- sys.stderr.write(
- f"[last30days] WARNING: unexpected error checking Xiaohongshu: "
- f"{type(exc).__name__}: {exc}\n"
- )
- sys.stderr.flush()
- return False
+ for base in _xiaohongshu_api_base_candidates(config):
+ try:
+ if _xiaohongshu_base_logged_in(base, http):
+ config[XIAOHONGSHU_RESOLVED_API_BASE_KEY] = base
+ return True
+ except (OSError, http.HTTPError):
+ continue
+ except Exception as exc:
+ sys.stderr.write(
+ f"[last30days] WARNING: unexpected error checking Xiaohongshu "
+ f"at {base}: {type(exc).__name__}: {exc}\n"
+ )
+ sys.stderr.flush()
+ return False
# Backward compat alias
diff --git a/skills/last30days/scripts/lib/prescriptions.py b/skills/last30days/scripts/lib/prescriptions.py
index 2e931e9b..319dd828 100644
--- a/skills/last30days/scripts/lib/prescriptions.py
+++ b/skills/last30days/scripts/lib/prescriptions.py
@@ -205,13 +205,14 @@ REGISTRY: Dict[Tuple[str, str], Prescription] = dict((
_entry(
"xiaohongshu", "service_unreachable",
cause=(
- "xiaohongshu-mcp service is unreachable at XIAOHONGSHU_API_BASE "
- "(default http://host.docker.internal:18060)"
+ "Xiaohongshu browser-session service is unreachable or not logged "
+ "in; last30days auto-probes http://localhost:18060 and "
+ "http://host.docker.internal:18060 unless XIAOHONGSHU_API_BASE is set"
),
fix_nl=(
- "start the xpzouying/xiaohongshu-mcp service and log in from its "
- "web UI, then point XIAOHONGSHU_API_BASE at the running instance "
- "if it is not on the default host/port"
+ "start a local x-mcp browser plugin or xpzouying/xiaohongshu-mcp "
+ "service that can see your logged-in Xiaohongshu browser session; "
+ "set XIAOHONGSHU_API_BASE only when it runs on a custom host/port"
),
fix_cli="XIAOHONGSHU_API_BASE=http://localhost:18060",
anchor="api-keys-env",
diff --git a/tests/test_xiaohongshu_api.py b/tests/test_xiaohongshu_api.py
new file mode 100644
index 00000000..bce56a54
--- /dev/null
+++ b/tests/test_xiaohongshu_api.py
@@ -0,0 +1,172 @@
+"""Xiaohongshu source tests.
+
+These stay fully mocked because the real source depends on a logged-in local
+xiaohongshu-mcp service, which CI and contributors will not have by default.
+"""
+
+from datetime import datetime, timezone
+from unittest import mock
+
+import pytest
+
+import last30days as cli
+from lib import env, http, pipeline, xiaohongshu_api
+
+
+def test_search_flag_accepts_xhs_alias():
+ assert cli.parse_search_flag("xhs") == ["xiaohongshu"]
+ assert pipeline.normalize_requested_sources(["xhs"]) == ["xiaohongshu"]
+
+
+def test_xiaohongshu_requested_source_requires_live_logged_in_service():
+ with mock.patch.object(pipeline.env, "is_xiaohongshu_available", return_value=False):
+ assert "xiaohongshu" not in pipeline.available_sources(
+ {}, requested_sources=["xiaohongshu"],
+ )
+
+ with mock.patch.object(pipeline.env, "is_xiaohongshu_available", return_value=True):
+ assert "xiaohongshu" in pipeline.available_sources(
+ {}, requested_sources=["xiaohongshu"],
+ )
+
+
+def test_xiaohongshu_default_api_base_is_localhost():
+ assert env.get_xiaohongshu_api_base({}) == "http://localhost:18060"
+
+
+def test_xiaohongshu_availability_prefers_localhost_and_caches_base():
+ config = {}
+
+ def fake_get(url, **kwargs):
+ # This mimics an x-mcp/browser-backed service running in the user's
+ # normal local browser context.
+ assert url.startswith("http://localhost:18060/")
+ if url.endswith("/health"):
+ return {"success": True}
+ if url.endswith("/api/v1/login/status"):
+ return {"data": {"is_logged_in": True}}
+ raise AssertionError(f"unexpected URL: {url}")
+
+ with mock.patch.object(http, "get", side_effect=fake_get) as get_mock:
+ assert env.is_xiaohongshu_available(config) is True
+
+ assert get_mock.call_count == 2
+ assert config[env.XIAOHONGSHU_RESOLVED_API_BASE_KEY] == "http://localhost:18060"
+ assert env.get_xiaohongshu_api_base(config) == "http://localhost:18060"
+
+
+def test_xiaohongshu_availability_falls_back_to_docker_host():
+ config = {}
+
+ def fake_get(url, **kwargs):
+ if url.startswith("http://localhost:18060/"):
+ raise http.HTTPError("not running")
+ if url == "http://host.docker.internal:18060/health":
+ return {"success": True}
+ if url == "http://host.docker.internal:18060/api/v1/login/status":
+ return {"data": {"is_logged_in": True}}
+ raise AssertionError(f"unexpected URL: {url}")
+
+ with mock.patch.object(http, "get", side_effect=fake_get):
+ assert env.is_xiaohongshu_available(config) is True
+
+ assert (
+ config[env.XIAOHONGSHU_RESOLVED_API_BASE_KEY]
+ == "http://host.docker.internal:18060"
+ )
+ assert env.get_xiaohongshu_api_base(config) == "http://host.docker.internal:18060"
+
+
+def test_xiaohongshu_explicit_api_base_skips_default_probe():
+ config = {"XIAOHONGSHU_API_BASE": "http://custom.local:18060/"}
+ seen_urls = []
+
+ def fake_get(url, **kwargs):
+ seen_urls.append(url)
+ assert url.startswith("http://custom.local:18060/")
+ if url.endswith("/health"):
+ return {"success": True}
+ if url.endswith("/api/v1/login/status"):
+ return {"data": {"is_logged_in": True}}
+ raise AssertionError(f"unexpected URL: {url}")
+
+ with mock.patch.object(http, "get", side_effect=fake_get):
+ assert env.is_xiaohongshu_available(config) is True
+
+ assert seen_urls == [
+ "http://custom.local:18060/health",
+ "http://custom.local:18060/api/v1/login/status",
+ ]
+ assert config[env.XIAOHONGSHU_RESOLVED_API_BASE_KEY] == "http://custom.local:18060"
+
+
+def test_to_int_accepts_chinese_count_suffixes():
+ assert xiaohongshu_api._to_int("1.2万") == 12000
+ assert xiaohongshu_api._to_int("3亿") == 300000000
+ assert xiaohongshu_api._to_int("42") == 42
+ assert xiaohongshu_api._to_int(None) == 0
+
+
+def test_search_feeds_normalizes_xiaohongshu_response():
+ timestamp_ms = int(datetime(2026, 7, 1, tzinfo=timezone.utc).timestamp() * 1000)
+ response = {
+ "data": {
+ "feeds": [
+ {
+ "id": "note-1",
+ "xsecToken": "token-1",
+ "noteCard": {
+ "displayTitle": "Popular matcha latte",
+ "desc": "A creator review with useful comments.",
+ "time": timestamp_ms,
+ "interactInfo": {
+ "likedCount": "1.2万",
+ "commentCount": "345",
+ "collectedCount": "6,789",
+ },
+ },
+ }
+ ]
+ }
+ }
+
+ with mock.patch.object(xiaohongshu_api.http, "get", return_value={"data": {"is_logged_in": True}}) as get_mock, \
+ mock.patch.object(xiaohongshu_api.http, "post", return_value=response) as post_mock:
+ items = xiaohongshu_api.search_feeds(
+ "matcha latte", "2026-06-01", "2026-07-01",
+ "http://localhost:18060/", depth="default",
+ )
+
+ assert get_mock.call_args.args[0] == "http://localhost:18060/api/v1/login/status"
+ assert post_mock.call_args.args[0] == "http://localhost:18060/api/v1/feeds/search"
+ payload = post_mock.call_args.args[1]
+ assert payload["keyword"] == "matcha latte"
+ assert payload["filters"]["publish_time"] == "一周内"
+
+ assert items == [
+ {
+ "id": "XHS1",
+ "title": "Popular matcha latte",
+ "url": "https://www.xiaohongshu.com/explore/note-1?xsec_token=token-1",
+ "source_domain": "xiaohongshu.com",
+ "snippet": "A creator review with useful comments.",
+ "date": "2026-07-01",
+ "date_confidence": "high",
+ "relevance": 1.0,
+ "why_relevant": "Xiaohongshu engagement: likes=12000, comments=345, favorites=6789",
+ "engagement": {
+ "likes": 12000,
+ "comments": 345,
+ "favorites": 6789,
+ },
+ }
+ ]
+
+
+def test_search_feeds_requires_logged_in_xiaohongshu_session():
+ with mock.patch.object(xiaohongshu_api.http, "get", return_value={"data": {"is_logged_in": False}}):
+ with pytest.raises(http.HTTPError, match="not logged in"):
+ xiaohongshu_api.search_feeds(
+ "matcha latte", "2026-06-01", "2026-07-01",
+ "http://localhost:18060",
+ )