src/index.js
// AgentRove native agent: trend-research (MIT).
// Reads RSS/Atom feeds (as text, or fetched from hosts the user explicitly lists) and the public
// Hacker News Algolia API, then compares term frequencies between two time windows.
// No HTML scraping. Feed content is untrusted data and is never executed or obeyed.
import { readFileSync } from "node:fs";
import { defineAgent, validate, makeContext, handleMcpMessage, runCli, runMcpStdio } from "../sdk/index.js";
import { ToolError } from "./errors.js";
import { parseFeed, safeHttpUrl, stripHtml, stripTitleHtml } from "./feed.js";
import { fetchText, normaliseHosts, publicHostsOnly, pinnedFetch } from "./net.js";
import { STOPWORDS, termMapOf } from "./text.js";
export { makeContext, handleMcpMessage, runCli, runMcpStdio };
const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));
const DAY = 86400000;
const FEED_ACCEPT = "application/rss+xml, application/atom+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8";
const dnsRejections = new WeakMap(); // input object -> hosts that failed the DNS/public-address check
function collectFeed(parsed, items, seen) {
let added = 0;
for (const it of parsed.items) {
const key = normUrl(it.url);
if (seen.has(key)) continue;
seen.add(key);
items.push(it);
added++;
}
return added;
}
function normUrl(raw) {
try {
const u = new URL(raw);
u.hash = "";
for (const k of [...u.searchParams.keys()]) if (/^utm_/i.test(k)) u.searchParams.delete(k);
return `${u.protocol}//${u.hostname.toLowerCase()}${u.port ? `:${u.port}` : ""}${u.pathname.replace(/\/+$/, "")}${u.search}`;
} catch {
return String(raw);
}
}
// ------------------------------------------------------------------------------------------------
// parse_feeds: feed XML supplied by the caller (no network)
// ------------------------------------------------------------------------------------------------
async function parse_feeds(input, ctx) {
const maxItems = input.max_items_per_feed ?? 500;
const items = [];
const seen = new Set();
const feeds = [];
for (const [i, f] of input.feeds.entries()) {
const feedUrl = f.url !== undefined ? safeHttpUrl(f.url) : undefined;
if (f.url !== undefined && !feedUrl) throw new ToolError("invalid_input", `feeds[${i}].url must be an http(s) URL`);
try {
const parsed = parseFeed(f.xml, { feedUrl, maxItems });
const added = collectFeed(parsed, items, seen);
feeds.push({ index: i, ok: true, format: parsed.format, title: parsed.title.slice(0, 200), item_count: added, skipped: parsed.skipped, ...(feedUrl ? { url: feedUrl } : {}) });
} catch (e) {
feeds.push({ index: i, ok: false, error: `${e.code ?? "error"}: ${String(e.message).slice(0, 300)}`, ...(feedUrl ? { url: feedUrl } : {}) });
}
}
return { items, feeds, parsed_at: ctx.now().toISOString() };
}
// ------------------------------------------------------------------------------------------------
// fetch_feeds: https feeds from hosts the user listed in allowed_hosts
// ------------------------------------------------------------------------------------------------
async function fetch_feeds(input, ctx) {
const hosts = normaliseHosts(input.allowed_hosts);
const dnsRejected = dnsRejections.get(input) ?? [];
const urls = input.urls.map((raw, i) => {
let u;
try {
u = new URL(raw);
} catch {
throw new ToolError("invalid_input", `urls[${i}] is not a valid URL`);
}
if (u.protocol !== "https:") throw new ToolError("invalid_input", `urls[${i}] must use https`);
if (u.username || u.password) throw new ToolError("invalid_input", `urls[${i}] must not contain credentials`);
const h = u.hostname.toLowerCase().replace(/\.$/, "");
if (!hosts.includes(h)) throw new ToolError("network_denied", `urls[${i}]: host ${h} is not listed in allowed_hosts`);
return u.toString();
});
const maxBytes = input.max_bytes_per_feed ?? 2_000_000;
const maxItems = input.max_items_per_feed ?? 500;
const items = [];
const seen = new Set();
const feeds = [];
for (const url of urls) {
const host = new URL(url).hostname.toLowerCase();
if (dnsRejected.includes(host)) {
feeds.push({ url, ok: false, error: "network_denied: host did not resolve to public addresses only" });
continue;
}
try {
const { text, finalUrl } = await fetchText(ctx, url, { maxBytes, accept: FEED_ACCEPT });
const parsed = parseFeed(text, { feedUrl: finalUrl, maxItems });
const added = collectFeed(parsed, items, seen);
feeds.push({ url, ok: true, final_url: finalUrl, format: parsed.format, title: parsed.title.slice(0, 200), item_count: added, skipped: parsed.skipped });
} catch (e) {
feeds.push({ url, ok: false, error: `${e.code ?? "error"}: ${String(e.message).slice(0, 300)}` });
}
}
return { items, feeds, fetched_at: ctx.now().toISOString() };
}
// ------------------------------------------------------------------------------------------------
// fetch_hn: public Hacker News search API (hn.algolia.com)
// ------------------------------------------------------------------------------------------------
async function fetch_hn(input, ctx) {
const now = ctx.now().getTime();
const to = input.to !== undefined ? Date.parse(input.to) : now;
const from = input.from !== undefined ? Date.parse(input.from) : to - 14 * DAY;
if (!(to > from)) throw new ToolError("invalid_input", "to must be after from");
const tags = input.tags ?? "story";
const hitsPerPage = input.max_hits ?? 200;
const params = new URLSearchParams({
query: input.query,
tags,
hitsPerPage: String(hitsPerPage),
numericFilters: `created_at_i>=${Math.floor(from / 1000)},created_at_i<${Math.floor(to / 1000)}`,
});
const url = `https://hn.algolia.com/api/v1/search_by_date?${params}`;
const { text } = await fetchText(ctx, url, { maxBytes: 10_000_000, accept: "application/json" });
let json;
try {
json = JSON.parse(text);
} catch {
throw new ToolError("bad_response", "Hacker News API did not return JSON");
}
const hits = Array.isArray(json?.hits) ? json.hits : [];
const items = [];
for (const h of hits) {
const id = /^\d{1,12}$/.test(String(h?.objectID)) ? String(h.objectID) : null;
const title = typeof h?.title === "string" && h.title ? h.title : typeof h?.story_title === "string" ? h.story_title : "";
if (!id || !title) continue;
const discussion = `https://news.ycombinator.com/item?id=${id}`;
const item = { url: safeHttpUrl(h.url) ?? discussion, title: stripTitleHtml(title).slice(0, 500), source_name: "Hacker News", discussion_url: discussion };
const t = Date.parse(h.created_at ?? "");
if (!Number.isNaN(t)) item.published_at = new Date(t).toISOString();
else if (Number.isFinite(h.created_at_i)) item.published_at = new Date(h.created_at_i * 1000).toISOString();
if (typeof h.story_text === "string" && h.story_text) item.excerpt = stripHtml(h.story_text).slice(0, 600);
if (Number.isInteger(h.points)) item.hn_points = h.points;
if (Number.isInteger(h.num_comments)) item.hn_comments = h.num_comments;
items.push(item);
}
const out = {
items,
query: { query: input.query, tags, from: new Date(from).toISOString(), to: new Date(to).toISOString(), max_hits: hitsPerPage },
fetched_at: new Date(now).toISOString(),
notes: ["hn_points and hn_comments are copied from the Hacker News Algolia API response at fetched_at; they are not estimates."],
};
if (Number.isInteger(json?.nbHits)) out.total_hits = json.nbHits;
if (out.total_hits > items.length) out.notes.push(`The API reported ${out.total_hits} matches; only the newest ${items.length} were returned (max_hits).`);
return out;
}
// ------------------------------------------------------------------------------------------------
// analyze_trends: term trends between a baseline window and a current window
// ------------------------------------------------------------------------------------------------
function parseWindow(w, label) {
const start = Date.parse(w.start);
const end = Date.parse(w.end);
if (!(end > start)) throw new ToolError("invalid_input", `${label}.end must be after ${label}.start`);
return { start, end };
}
const round2 = (x) => Math.round(x * 100) / 100;
async function analyze_trends(input, ctx) {
const now = ctx.now().getTime();
const days = input.window_days ?? 7;
const cur = input.current ? parseWindow(input.current, "current") : { start: now - days * DAY, end: now };
const base = input.baseline ? parseWindow(input.baseline, "baseline") : { start: cur.start - (cur.end - cur.start), end: cur.start };
if (base.start < cur.end && cur.start < base.end) throw new ToolError("invalid_input", "baseline and current windows must not overlap");
const stop = new Set([...STOPWORDS, ...(input.stopwords_extra ?? []).map((s) => s.toLowerCase().trim())]);
const minCount = input.min_count ?? 3;
const maxTerms = input.max_terms ?? 25;
const maxSources = input.max_sources_per_term ?? 10;
const bigrams = input.include_bigrams ?? true;
const direction = input.direction ?? "rising";
const fields = input.fields ?? ["title", "excerpt"];
const mergePlurals = input.merge_plurals ?? true;
const seen = new Set();
let undated = 0;
let duplicates = 0;
let outside = 0;
const curDocs = [];
const baseDocs = [];
for (const it of input.items) {
const key = normUrl(it.url);
if (seen.has(key)) {
duplicates++;
continue;
}
seen.add(key);
const t = Date.parse(it.published_at ?? "");
if (Number.isNaN(t)) {
undated++;
continue;
}
const text = fields.map((f) => (typeof it[f] === "string" ? it[f] : "")).join(" . ");
const doc = { url: it.url, t, terms: termMapOf(text, stop, bigrams, mergePlurals) };
if (t >= cur.start && t < cur.end) curDocs.push(doc);
else if (t >= base.start && t < base.end) baseDocs.push(doc);
else outside++;
}
const curCounts = new Map();
const sources = new Map();
const surfaces = new Map(); // key -> Map(surface form -> number of current items using it)
for (const d of curDocs) {
for (const [term, forms] of d.terms) {
curCounts.set(term, (curCounts.get(term) ?? 0) + 1);
if (!sources.has(term)) sources.set(term, []);
sources.get(term).push(d);
if (!surfaces.has(term)) surfaces.set(term, new Map());
for (const f of forms) surfaces.get(term).set(f, (surfaces.get(term).get(f) ?? 0) + 1);
}
}
const baseCounts = new Map();
for (const d of baseDocs) for (const term of d.terms.keys()) baseCounts.set(term, (baseCounts.get(term) ?? 0) + 1);
// Display the wording most items used (ties: the shorter, then alphabetical).
const display = (key) =>
[...surfaces.get(key)].sort((a, b) => b[1] - a[1] || a[0].length - b[0].length || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))[0][0];
const nc = curDocs.length;
const nb = baseDocs.length;
let rows = [];
for (const [term, count] of curCounts) {
if (count < minCount) continue;
const b = baseCounts.get(term) ?? 0;
const change = round2((count + 1) / (nc + 1) / ((b + 1) / (nb + 1)));
const status = b === 0 ? "new" : change >= 1.5 ? "rising" : change <= 0.67 ? "falling" : "steady";
const srcs = sources
.get(term)
.slice()
.sort((x, y) => y.t - x.t || (x.url < y.url ? -1 : x.url > y.url ? 1 : 0))
.slice(0, maxSources)
.map((d) => d.url);
rows.push({ key: term, term: display(term), kind: term.includes(" ") ? "bigram" : "unigram", count, baseline_count: b, change, status, sources: srcs });
}
if (direction === "rising") rows = rows.filter((r) => r.status === "new" || r.status === "rising");
// A unigram that only ever appears inside one reported bigram adds nothing: drop it.
const bigramRows = rows.filter((r) => r.kind === "bigram");
rows = rows.filter((r) => r.kind === "bigram" || !bigramRows.some((bg) => bg.count === r.count && bg.key.split(" ").includes(r.key)));
rows.sort((a, b) => b.change - a.change || b.count - a.count || (a.term < b.term ? -1 : a.term > b.term ? 1 : 0));
rows = rows.slice(0, maxTerms).map(({ key, ...row }) => {
const forms = [...surfaces.get(key).keys()].filter((f) => f !== row.term).sort();
return forms.length ? { ...row, variants: forms } : row;
});
const notes = [
"count = number of distinct items in the current window whose title/excerpt mention the term; baseline_count is the same for the baseline window.",
...(mergePlurals ? ["Regular plurals are counted with their singular (\"server\" and \"servers\" are one term); other spellings seen are listed in variants."] : []),
"change = ((count+1)/(current_items+1)) / ((baseline_count+1)/(baseline_items+1)). Above 1 means a larger share of items mention the term now.",
"These counts describe only the feeds and results you supplied. They are not a measure of overall popularity.",
];
if (nc === 0) notes.push("No items fall inside the current window, so no terms are reported.");
if (nb === 0 && nc > 0) notes.push("The baseline window has no items, so every term is marked new and change ratios are not meaningful.");
if (undated) notes.push(`${undated} item(s) without a valid published_at were ignored.`);
if (duplicates) notes.push(`${duplicates} duplicate item(s) (same URL) were ignored.`);
if (outside) notes.push(`${outside} item(s) fell outside both windows.`);
return {
report: {
window: {
baseline: { start: new Date(base.start).toISOString(), end: new Date(base.end).toISOString(), item_count: nb },
current: { start: new Date(cur.start).toISOString(), end: new Date(cur.end).toISOString(), item_count: nc },
},
generated_at: new Date(now).toISOString(),
terms: rows,
notes,
},
};
}
// ------------------------------------------------------------------------------------------------
// Agent. fetch_feeds widens the network allowlist for ONE call to the exact hosts the user listed
// in allowed_hosts (validated: public DNS names only, each resolved and checked against private
// address ranges when the real network is used).
// ------------------------------------------------------------------------------------------------
const agent = defineAgent(manifest, { parse_feeds, fetch_feeds, fetch_hn, analyze_trends });
const sdkCall = agent.call.bind(agent);
agent.call = async function call(name, input, ctxOverrides = {}) {
if (name !== "fetch_feeds" && name !== "fetch_hn") return sdkCall(name, input, ctxOverrides);
// On the real network (no injected fetch) every request goes through pinnedFetch: the SDK still checks
// the allowlist on each hop, and the TCP connection goes only to an address that was resolved and
// checked at connect time, so a DNS answer that changes after the pre-check (rebinding) is refused.
const realNetwork = !ctxOverrides.fetch;
const rest = { ...ctxOverrides };
delete rest.lookup; // the resolver override is for the DNS checks only, not the SDK
if (realNetwork) rest.fetch = pinnedFetch({ resolver: ctxOverrides.lookup });
if (name === "fetch_hn") return sdkCall(name, input, rest);
if (validate(agent.tool(name).input_schema, input).length) return sdkCall(name, input, rest); // SDK reports invalid_input
const hosts = normaliseHosts(input.allowed_hosts);
let usable = hosts;
// DNS pre-check for a clear early refusal. An injected fetch (tests, custom transports) owns its own
// egress, so the check runs only for the real network or when a resolver is injected.
if (ctxOverrides.lookup || realNetwork) {
const { ok, rejected } = await publicHostsOnly(hosts, ctxOverrides.lookup);
usable = ok;
dnsRejections.set(input, rejected);
}
return sdkCall(name, input, { ...rest, extraHosts: [...(rest.extraHosts ?? []), ...usable] });
};
export default agent;