evidence-mcp-dev 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +74 -23
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -628,21 +628,31 @@ import TurndownService from "turndown";
628
628
  import { gfm } from "@joplin/turndown-plugin-gfm";
629
629
  var td = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced", bulletListMarker: "-" });
630
630
  td.use(gfm);
631
- td.remove(["script", "style", "nav", "noscript", "iframe", "button", "input", "select", "textarea", "header", "footer", "aside"]);
631
+ td.remove(["script", "style", "nav", "noscript", "iframe", "input", "select", "textarea", "header", "footer", "aside"]);
632
+ var inHeading = (n) => {
633
+ for (let p = n.parentNode; p; p = p.parentNode) if (/^h[1-6]$/i.test(String(p.nodeName)) || String(p.nodeName).toLowerCase() === "div" && /(^|\s)h[1-6](\s|$)/.test(String(p.className ?? ""))) return true;
634
+ return false;
635
+ };
636
+ td.addRule("buttons", {
637
+ filter: (n) => String(n.nodeName).toLowerCase() === "button",
638
+ replacement: (content, n) => inHeading(n) && !n.getAttribute?.("aria-haspopup") ? content : ""
639
+ });
640
+ var heading = (level, content) => {
641
+ const t = content.replace(/\s+/g, " ").trim();
642
+ return t ? `
643
+
644
+ ${"#".repeat(level)} ${t}
645
+
646
+ ` : "\n\n";
647
+ };
648
+ td.addRule("headings", { filter: ["h1", "h2", "h3", "h4", "h5", "h6"], replacement: (content, n) => heading(Number(String(n.nodeName).charAt(1)), content) });
632
649
  var FURNITURE = /gdpr|cookie|onetrust|consent|advert|\bad-slot\b/i;
633
650
  td.remove(((n) => ["div", "section"].includes(String(n.nodeName).toLowerCase()) && FURNITURE.test(`${n.className ?? ""} ${n.id ?? ""}`)));
634
651
  td.addRule("drop-svg", { filter: (n) => n.nodeName.toLowerCase() === "svg", replacement: () => "" });
635
652
  td.addRule("drop-images", { filter: ["img"], replacement: () => "" });
636
653
  td.addRule("div-headings", {
637
654
  filter: (n) => String(n.nodeName).toLowerCase() === "div" && /(^|\s)h[1-6](\s|$)/.test(String(n.className ?? "")),
638
- replacement: (content, n) => {
639
- const level = /(^|\s)h([1-6])(\s|$)/.exec(String(n.className))[2];
640
- return `
641
-
642
- ${"#".repeat(Number(level))} ${content.trim()}
643
-
644
- `;
645
- }
655
+ replacement: (content, n) => heading(Number(/(^|\s)h([1-6])(\s|$)/.exec(String(n.className))[2]), content)
646
656
  });
647
657
  function htmlToMarkdown(html) {
648
658
  return td.turndown(html).replace(/\n{3,}/g, "\n\n").trim() + "\n";
@@ -1349,6 +1359,17 @@ var looksLikePdf = (bytes) => bytes.subarray(0, 5).toString("latin1") === "%PDF-
1349
1359
  import { request as httpsRequest } from "https";
1350
1360
  var ENDPOINT = "https://api.brightdata.com/request";
1351
1361
  var TIMEOUT_MS2 = 6e4;
1362
+ function pageReason(error, msg) {
1363
+ const t = `${error} ${msg}`;
1364
+ const st = /response status was rejected: (\d{3})/i.exec(t);
1365
+ if (st) return `HTTP ${st[1]}`;
1366
+ const rb = /Requested URL \((.+?)\) is restricted in accordance with robots\.txt/.exec(t);
1367
+ if (rb) return `robots.txt restricts ${rb[1]}`;
1368
+ if (/robots\.txt/i.test(t)) return "robots.txt restricts the page";
1369
+ if (/captcha|protection page/i.test(t)) return "challenge not cleared (captcha)";
1370
+ if (/Residential Failed/i.test(t)) return "no residential exit";
1371
+ return null;
1372
+ }
1352
1373
  function post(url, init) {
1353
1374
  return new Promise((resolve4, reject) => {
1354
1375
  const req = httpsRequest(url, { method: "POST", headers: { ...init.headers, "Content-Length": String(Buffer.byteLength(init.body)) }, signal: init.signal }, (res) => {
@@ -1386,7 +1407,8 @@ async function get(url, postImpl = post, signal) {
1386
1407
  });
1387
1408
  const why = res.headers.get("x-brd-err-msg") ?? res.headers.get("x-brd-error");
1388
1409
  if (!res.ok) throw new Error(`unlocker HTTP ${res.status}${why ? `: ${why}` : ""}`);
1389
- if (res.headers.get("x-brd-error")) throw new Error(`unlocker refused: ${why}`);
1410
+ const err = res.headers.get("x-brd-error");
1411
+ if (err) throw new Error(pageReason(err, res.headers.get("x-brd-err-msg") ?? "") ?? `unlocker refused: ${why}`);
1390
1412
  return { bytes: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? "" };
1391
1413
  }
1392
1414
  var brightdata = { name: "brightdata", keyVar: "FH_BRIGHTDATA_API_KEY", get: (url, signal) => get(url, post, signal) };
@@ -1395,6 +1417,13 @@ var brightdata = { name: "brightdata", keyVar: "FH_BRIGHTDATA_API_KEY", get: (ur
1395
1417
  var TIMEOUT_MS3 = 6e4;
1396
1418
  var ACCOUNT = /* @__PURE__ */ new Set([401, 402, 403, 429]);
1397
1419
  async function get2(url, fetchImpl = fetch, signal) {
1420
+ try {
1421
+ return await request(url, fetchImpl, signal);
1422
+ } catch (e) {
1423
+ throw e?.name === "TimeoutError" ? new Error("timeout") : e;
1424
+ }
1425
+ }
1426
+ async function request(url, fetchImpl, signal) {
1398
1427
  const key2 = process.env.FH_ZENROWS_API_KEY?.trim();
1399
1428
  if (!key2) throw new Error("not configured");
1400
1429
  const r = await fetchImpl(`https://api.zenrows.com/v1/?apikey=${encodeURIComponent(key2)}&url=${encodeURIComponent(url)}&mode=auto`, { signal: timeoutOr(TIMEOUT_MS3, signal) });
@@ -1417,6 +1446,13 @@ var zenrows = { name: "zenrows", keyVar: "FH_ZENROWS_API_KEY", get: (url, signal
1417
1446
  var TIMEOUT_MS4 = 6e4;
1418
1447
  var ACCOUNT2 = /* @__PURE__ */ new Set([401, 402, 403, 429]);
1419
1448
  async function get3(url, fetchImpl = fetch, signal) {
1449
+ try {
1450
+ return await request2(url, fetchImpl, signal);
1451
+ } catch (e) {
1452
+ throw e?.name === "TimeoutError" ? new Error("timeout") : e;
1453
+ }
1454
+ }
1455
+ async function request2(url, fetchImpl, signal) {
1420
1456
  const key2 = process.env.FH_ZYTE_API_KEY?.trim();
1421
1457
  if (!key2) throw new Error("not configured");
1422
1458
  const r = await fetchImpl("https://api.zyte.com/v1/extract", {
@@ -2570,7 +2606,17 @@ function writeDoiEntry(p, r, json2, converter, abstractFrom = "crossref", record
2570
2606
  }
2571
2607
 
2572
2608
  // src/walls.ts
2573
- var WALL2 = /^(challenge not cleared|empty response)/i;
2609
+ var TIMEOUT = "timeout\\b|The operation was aborted due to timeout|navigation: page\\.goto: Timeout \\d+ms";
2610
+ var WALL2 = new RegExp(`^(challenge not cleared|empty response|HTTP 520 Website Ban|robots\\.txt restricts|page refused: .*(robots\\.txt|captcha|protection page|: 403)|${TIMEOUT})`, "i");
2611
+ var ROBOTS = /^(robots\.txt restricts|page refused: .*robots\.txt)/i;
2612
+ var RULE = /^(HTTP 520 Website Ban|robots\.txt restricts|page refused: .*robots\.txt)/i;
2613
+ var pathKey = (url, stage2) => {
2614
+ try {
2615
+ return `${stage2} /${new URL(url).pathname.split("/").filter(Boolean).slice(0, 2).join("/")}`;
2616
+ } catch {
2617
+ return stage2;
2618
+ }
2619
+ };
2574
2620
  var WALL_STREAK = 2;
2575
2621
  var host = (url) => {
2576
2622
  try {
@@ -2592,8 +2638,8 @@ function walled(url, stage2, dir = FH_EVIDENCE_DIR) {
2592
2638
  const h = host(url);
2593
2639
  if (!h) return null;
2594
2640
  const all = read(dir, h);
2595
- const r = all[stage2] ?? all[legacy(stage2)];
2596
- return r && r.streak >= WALL_STREAK && daysSince(r.date) < settings().retry_after_days ? r : null;
2641
+ const live2 = (r) => r && (r.streak >= WALL_STREAK || RULE.test(r.reason)) && daysSince(r.date) < settings().retry_after_days ? r : null;
2642
+ return live2(all[stage2] ?? all[legacy(stage2)]) ?? live2(all[pathKey(url, stage2)]);
2597
2643
  }
2598
2644
  function recordStage(url, stage2, ok, reason = "", dir = FH_EVIDENCE_DIR) {
2599
2645
  const h = host(url);
@@ -2606,10 +2652,13 @@ function recordStage(url, stage2, ok, reason = "", dir = FH_EVIDENCE_DIR) {
2606
2652
  all[stage2] ??= all[lk];
2607
2653
  delete all[lk];
2608
2654
  }
2655
+ const pk = pathKey(url, stage2);
2609
2656
  if (ok) {
2610
- if (!all[stage2]) return;
2657
+ if (!all[stage2] && !all[pk]) return;
2611
2658
  delete all[stage2];
2612
- } else all[stage2] = { streak: (all[stage2]?.streak ?? 0) + 1, date: now(), reason: why };
2659
+ delete all[pk];
2660
+ } else if (ROBOTS.test(why)) all[pk] = { streak: (all[pk]?.streak ?? 0) + 1, date: now(), reason: why };
2661
+ else all[stage2] = { streak: (all[stage2]?.streak ?? 0) + 1, date: now(), reason: why };
2613
2662
  try {
2614
2663
  mkdirSync3(join5(dir, ".walls"), { recursive: true });
2615
2664
  writeAtomic(file(dir, h), JSON.stringify(all) + "\n");
@@ -5327,7 +5376,7 @@ function splitArticles(xml) {
5327
5376
  }
5328
5377
  var row2 = (pmid, s, level) => s ? [pmid, s.title ? s.title.replace(/\.$/, "") : s.title, s.first_author, s.year, reviewTypes(s.publication_types).join("; ") || null, s.retracted, level] : [pmid, null, null, null, null, null, level];
5329
5378
  async function fetchArticles(ids, libraryDir = FH_EVIDENCE_DIR, converter = "evidence-mcp", fetchImpl = fetchText) {
5330
- const result = { columns: COLUMNS3, rows: [], new: 0, cached: 0, not_found: 0, invalid: 0 };
5379
+ const result = { columns: COLUMNS3, rows: [], new: 0, cached: 0, not_found: 0, invalid: 0, asked: 0 };
5331
5380
  const order2 = [];
5332
5381
  const invalid = /* @__PURE__ */ new Map();
5333
5382
  for (const raw of ids.slice(0, MAX_PMIDS)) {
@@ -5351,6 +5400,7 @@ async function fetchArticles(ids, libraryDir = FH_EVIDENCE_DIR, converter = "evi
5351
5400
  const missing = order2.filter((k) => !invalid.has(k) && !status(k) && !known(k));
5352
5401
  let records = /* @__PURE__ */ new Map();
5353
5402
  if (missing.length) records = splitArticles(await fetchImpl(efetchBatchUrl(missing)));
5403
+ result.asked = missing.length;
5354
5404
  for (const k of order2) {
5355
5405
  if (invalid.has(k)) {
5356
5406
  result.rows.push(row2(k, null, "invalid"));
@@ -5412,7 +5462,7 @@ Tools
5412
5462
  - fh_clinicaltrials_search_studies(query | intervention | condition, status?, sort?, max_results?) \u2014 search ClinicalTrials.gov: the total and rows in columns order (NCT ID, title, status, phase, enrollment, dates, primary outcome, conditions, interventions, has_results). Cached a week.
5413
5463
  - fh_clinicaltrials_get_study_record(nct) \u2014 one trial as a review needs it (status, design, enrollment, dates, outcomes, eligibility, result publications, summary), from the stored record; added first when missing.
5414
5464
  - fh_clinicaltrials_get_study_results(nct, max_chars?) \u2014 a trial's posted results as Markdown, capped; the outcome titles listed for fh_library_read.
5415
- - fh_fetch_url(url, max_length?, start_index?, raw?, title_only?) \u2014 a web page as Markdown, same call and same answer as the standard fetch tool ("Contents of <url>:" and the page, cut at max_length with a note on how to continue). Prefer it for every URL: a cached page answers from disk, a walled or script-rendered page runs through the browser and unlocker stages in one call. PDFs as Markdown. title_only returns the title line alone \u2014 enough to verify a link, at a few tokens.
5465
+ - fh_fetch_url(url, max_length?, start_index?, raw?, title_only?) \u2014 a web page as Markdown, same call and same answer as the standard fetch tool ("Contents of <url>:" and the page, cut at max_length with a note on how to continue). Prefer it for every URL: a cached page answers from disk, a walled or script-rendered page runs through the browser and unlocker stages in one call. PDFs as Markdown; XML, JSON and other text as is. title_only returns the title line alone \u2014 enough to verify a link, at a few tokens.
5416
5466
 
5417
5467
  Hints
5418
5468
  - fh_library_read and fh_verify_claim store a missing record themselves; the fh_library_read answer then carries added: true. No fh_library_add necessary first.
@@ -5864,7 +5914,7 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
5864
5914
  const { cached, ...r } = await verifyCached(claim, id, cfg, cfg ? decider(cfg) : null, FH_EVIDENCE_DIR);
5865
5915
  if (!r.error && r.score !== null) bump("verify", cached);
5866
5916
  const secs = `${((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0")}s`;
5867
- log("verify", r.id, r.error ? `${modelFailure(r.error, cfg) ? "!! " : ""}${secs} ${"error".padEnd(20)} ${r.error} | ${claim}` : `${secs} verdict=${r.verdict.padEnd(12)} basis=${r.basis.padEnd(9)} score=${r.score === null ? "- " : r.score.toFixed(3)}${r.windows > 1 ? ` windows=${r.windows}` : ""}${cached ? " cached" : ""}${r.superseded ? " superseded" : ""}${r.glyphs_unresolved ? ` glyphs=${r.glyphs_unresolved}` : ""} | ${claim}`);
5917
+ log("verify", r.id, r.error ? `${modelFailure(r.error, cfg) ? "!! " : ""}${secs} ${"error".padEnd(20)} ${r.error} | ${claim}` : `${cached ? "" : `${secs} `}verdict=${r.verdict.padEnd(12)} basis=${r.basis.padEnd(9)} score=${r.score === null ? "- " : r.score.toFixed(3)}${r.windows > 1 ? ` windows=${r.windows}` : ""}${cached ? " cached" : ""}${r.superseded ? " superseded" : ""}${r.glyphs_unresolved ? ` glyphs=${r.glyphs_unresolved}` : ""} | ${claim}`);
5868
5918
  return { content: [{ type: "text", text: verdictAnswer(r) }] };
5869
5919
  }
5870
5920
  );
@@ -5896,7 +5946,7 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
5896
5946
  );
5897
5947
  server2.tool(
5898
5948
  "fh_fetch_url",
5899
- `Fetch a web page as Markdown: the standard fetch tool, cached and hardened. Use it for any URL instead of a plain fetch or a browser. A page fetched in the last ${settings().refresh_after_days} days is answered from disk in milliseconds; a page a plain fetch cannot get (403, rate limit, bot wall, script-rendered) is fetched through the configured browsers and unlockers in this one call. PDFs come back as Markdown. To verify a link, title_only returns just its title line. A PubMed, ClinicalTrials.gov, DailyMed or doi.org URL is answered from the library's record of it.`,
5949
+ `Fetch a web page as Markdown: the standard fetch tool, cached and hardened. Use it for any URL instead of a plain fetch or a browser. A page fetched in the last ${settings().refresh_after_days} days is answered from disk in milliseconds; a page a plain fetch cannot get (403, rate limit, bot wall, script-rendered) is fetched through the configured browsers and unlockers in this one call. PDFs come back as Markdown; XML, JSON and other text as is. To verify a link, title_only returns just its title line. A PubMed, ClinicalTrials.gov, DailyMed or doi.org URL is answered from the library's record of it.`,
5900
5950
  {
5901
5951
  url: z.string().describe("URL to fetch"),
5902
5952
  // Optional, not .default(5000): the log tells a model that set none from one that asked for 5000.
@@ -5966,7 +6016,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
5966
6016
  if (r.cached) bump("pubmed", true, r.cached);
5967
6017
  if (r.new) bump("pubmed", false, r.new);
5968
6018
  const secs = ((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0") + "s";
5969
- log("pubmed", `pmids:${r.rows.length}`, `articles ${secs} cached=${r.cached} new=${r.new}${r.not_found ? ` not_found=${r.not_found}` : ""}${r.invalid ? ` invalid=${r.invalid}` : ""}`);
6019
+ log("pubmed", `pmids:${r.rows.length}`, `articles ${r.asked ? `${secs} ` : ""}cached=${r.cached} new=${r.new}${r.not_found ? ` not_found=${r.not_found}` : ""}${r.invalid ? ` invalid=${r.invalid}` : ""}`);
5970
6020
  return { content: [{ type: "text", text: compact2({ columns: r.columns, rows: r.rows }) }] };
5971
6021
  }
5972
6022
  );
@@ -6023,12 +6073,13 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6023
6073
  if (p.error) return { error: p.error };
6024
6074
  if (p.type !== "nct") return { error: `not a trial ID: ${p.requested}` };
6025
6075
  const paths = entryPaths(FH_EVIDENCE_DIR, p.type, p.id);
6026
- if (!entryExists(paths)) {
6076
+ const added = !entryExists(paths);
6077
+ if (added) {
6027
6078
  const r = await addEntry(p.requested);
6028
6079
  const s = JSON.parse(r.content[0].text);
6029
6080
  if (s.error) return { error: s.error };
6030
6081
  }
6031
- return { paths, requested: p.requested };
6082
+ return { paths, requested: p.requested, added };
6032
6083
  };
6033
6084
  server2.tool(
6034
6085
  "fh_clinicaltrials_get_study_record",
@@ -6047,7 +6098,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6047
6098
  log("trials", e.requested, "record error: no stored record");
6048
6099
  return { content: [{ type: "text", text: compact2({ error: "no stored record" }) }], isError: true };
6049
6100
  }
6050
- log("trials", e.requested, `record ${((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0")}s ${r.status ?? ""}${r.has_results ? " results" : ""} | ${r.title}`);
6101
+ log("trials", e.requested, `record ${e.added ? `${((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0")}s ` : ""}${r.status ?? ""}${r.has_results ? " results" : ""} | ${r.title}`);
6051
6102
  return { content: [{ type: "text", text: leanJson(r) }] };
6052
6103
  }
6053
6104
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "evidence-mcp-dev",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Internal development build of evidence-mcp. Not for public use.",
5
5
  "type": "module",
6
6
  "bin": {