evidence-mcp-dev 1.0.9 → 1.0.11

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 +154 -48
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2749,11 +2749,11 @@ async function download(tier, p, candidates, ctx) {
2749
2749
  const isGone = (x) => x.ok ? null : x.reason.match(/\bHTTP (404|410)\b/)?.[0] ?? null;
2750
2750
  const one = await firstOk(first, isGone);
2751
2751
  if (one.won) return one.won;
2752
- const plain3 = one.results[0] ?? one.results.find(Boolean);
2753
- const target = !plain3.ok && plain3.url && plain3.url !== c.url ? { ...c, url: plain3.url } : c;
2752
+ const plain4 = one.results[0] ?? one.results.find(Boolean);
2753
+ const target = !plain4.ok && plain4.url && plain4.url !== c.url ? { ...c, url: plain4.url } : c;
2754
2754
  if (target !== c) ctx.onTry?.(`redirect ${c.url} \u2192 ${target.url}`);
2755
- const plainReason = why(reasonOf(plain3));
2756
- let r = one.results[1] ?? plain3;
2755
+ const plainReason = why(reasonOf(plain4));
2756
+ let r = one.results[1] ?? plain4;
2757
2757
  const UNLOCK = /^(HTTP 403|wall page)/;
2758
2758
  let browsed = false;
2759
2759
  if (!gone && !c.headers && !c.service && (climbsOn(plainReason) || climbsOn(bare(reasonOf(r))))) {
@@ -3246,7 +3246,11 @@ var VARIABLES = [
3246
3246
  "FH_REFRESH_AFTER_DAYS",
3247
3247
  "FH_SEARCH_CACHE_DAYS",
3248
3248
  "FH_NCBI_API_KEY",
3249
- "FH_EXA_API_KEY",
3249
+ "FH_WEB_SEARCH_EXA_API_KEY",
3250
+ "FH_WEB_SEARCH_SERPER_API_KEY",
3251
+ "FH_WEB_SEARCH_BRAVE_API_KEY",
3252
+ "FH_WEB_SEARCH_SNIPPETS",
3253
+ "FH_WEB_SEARCH_TIMEOUT_SECS",
3250
3254
  "FH_ZENROWS_API_KEY",
3251
3255
  "FH_ZYTE_API_KEY",
3252
3256
  "FH_BRIGHTDATA_API_KEY",
@@ -3426,8 +3430,8 @@ function resolve3(env) {
3426
3430
  const field2 = (p, f) => {
3427
3431
  const own = p ? `FH_VERIFY_${p.name.toUpperCase()}_${f}` : "";
3428
3432
  if (own && str(own, env)) return [str(own, env), own];
3429
- const plain3 = str(`FH_VERIFY_${f}`, env);
3430
- return [plain3, plain3 || !own ? `FH_VERIFY_${f}` : own];
3433
+ const plain4 = str(`FH_VERIFY_${f}`, env);
3434
+ return [plain4, plain4 || !own ? `FH_VERIFY_${f}` : own];
3431
3435
  };
3432
3436
  const filled = (p) => !!(str(`FH_VERIFY_${p.name.toUpperCase()}_URL`, env) || str(`FH_VERIFY_${p.name.toUpperCase()}_API_KEY`, env));
3433
3437
  const name = str("FH_VERIFY_PROVIDER", env).toLowerCase();
@@ -3855,11 +3859,26 @@ async function searchTrials(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liveF
3855
3859
  }
3856
3860
 
3857
3861
  // src/websearch.ts
3858
- var MAX_RESULTS2 = 25;
3859
- var DEFAULT_RESULTS2 = 10;
3860
- var COLUMNS2 = ["title", "url", "published", "author"];
3861
- var webSearchKey = (env = process.env) => env.FH_EXA_API_KEY?.trim() || null;
3862
- var webSearchConfigured = (env = process.env) => !!webSearchKey(env);
3862
+ var COLUMNS2 = ["title", "url", "published", "author", "snippet"];
3863
+ var snippetsOn = (env = process.env) => !/^(off|false|no|0)$/i.test((env.FH_WEB_SEARCH_SNIPPETS ?? "").trim());
3864
+ var SNIPPET_CHARS = 220;
3865
+ function cleanSnippet(t) {
3866
+ let s = (t ?? "").replace(/\s+/g, " ").trim();
3867
+ s = s.replace(/^(?:[#•*\-\s]*(?:last updated|updated|published|written by|reviewed by|by)\b[^.]*?(?:\d{4}|others)\s*)+/i, "").trim();
3868
+ s = s.replace(/^#+\s*/, "").replace(/^[·•\s]*(?:Cited by \d+|\d+ (?:days?|hours?) ago|[A-Z][a-z]{2} \d{1,2}, \d{4})\s*[—–-]\s*/i, "");
3869
+ if (!s) return null;
3870
+ if (s.length <= SNIPPET_CHARS) return s;
3871
+ const cut = s.slice(0, SNIPPET_CHARS);
3872
+ return cut.slice(0, Math.max(cut.lastIndexOf(" "), SNIPPET_CHARS - 40)).replace(/[,;:\s]+$/, "") + " \u2026";
3873
+ }
3874
+ var SEARCH_PROVIDERS = ["exa", "serper", "brave"];
3875
+ function webSearchConfig(env = process.env) {
3876
+ return SEARCH_PROVIDERS.flatMap((provider) => {
3877
+ const key2 = env[`FH_WEB_SEARCH_${provider.toUpperCase()}_API_KEY`]?.trim();
3878
+ return key2 ? [{ provider, key: key2 }] : [];
3879
+ });
3880
+ }
3881
+ var webSearchConfigured = (env = process.env) => webSearchConfig(env).length > 0;
3863
3882
  function siteDomain(site) {
3864
3883
  const s = site.trim().toLowerCase().replace(/^site:/, "");
3865
3884
  if (!s) return null;
@@ -3881,27 +3900,58 @@ function normalizeQuery2(q) {
3881
3900
  query = query.replace(/site:[^\s()]+/gi, " ").replace(/\(\s*(?:OR\s*)*\)/gi, " ").replace(/(?:^|\s)OR(?=\s*(?:$|\)))/g, " ").replace(/(?:^|\s)OR\s+(?=OR\b)/g, " ").replace(/\s+/g, " ").trim().replace(/^OR\s+|\s+OR$/g, "");
3882
3901
  }
3883
3902
  if (!query) return { error: "empty query" };
3884
- const out = { query, max_results: Math.min(MAX_RESULTS2, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS2))) };
3903
+ const out = { query };
3904
+ if (q.max_results && q.max_results >= 1) out.max_results = Math.floor(q.max_results);
3885
3905
  if (sites.length) out.sites = sites;
3886
3906
  return out;
3887
3907
  }
3888
- var searchKey2 = (q) => createHash3("sha1").update(JSON.stringify(["web", "exa", q.query.toLowerCase(), q.sites ?? [], q.max_results])).digest("hex").slice(0, 16);
3908
+ var searchKey2 = (q, provider = "exa", snippets = snippetsOn()) => createHash3("sha1").update(JSON.stringify(["web", provider, snippets ? "snippets" : "links", q.query.toLowerCase(), q.sites ?? []])).digest("hex").slice(0, 16);
3909
+ function isoDay(d) {
3910
+ const t = String(d ?? "").trim();
3911
+ if (!t || /\bago\b/i.test(t)) return null;
3912
+ if (/^\d{4}-\d\d-\d\d/.test(t)) return t.slice(0, 10);
3913
+ const day2 = new Date(t);
3914
+ return Number.isFinite(day2.getTime()) ? `${day2.getFullYear()}-${String(day2.getMonth() + 1).padStart(2, "0")}-${String(day2.getDate()).padStart(2, "0")}` : null;
3915
+ }
3916
+ var stripTracking = (u) => u.replace(/([?&])srsltid=[^&]*&?/, "$1").replace(/[?&]$/, "");
3917
+ var plain3 = (t) => (t ?? "").replace(/<[^>]+>/g, "").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#x27;|&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
3918
+ var withSites = (q) => !q.sites ? q.query : q.sites.length === 1 ? `${q.query} site:${q.sites[0]}` : `${q.query} (${q.sites.map((d) => `site:${d}`).join(" OR ")})`;
3889
3919
  function parseExa(json2) {
3890
3920
  const d = JSON.parse(json2);
3891
3921
  return (d.results ?? []).filter((x) => x.url).map((x) => [
3892
3922
  (x.title ?? "").replace(/\s+/g, " ").trim(),
3893
3923
  x.url,
3894
3924
  x.publishedDate ? x.publishedDate.slice(0, 10) : null,
3895
- x.author ? x.author.replace(/\s+/g, " ").trim() : null
3925
+ x.author ? x.author.replace(/\s+/g, " ").trim() : null,
3926
+ cleanSnippet(x.highlights?.[0])
3896
3927
  ]);
3897
3928
  }
3929
+ function parseSerper(json2) {
3930
+ const d = JSON.parse(json2);
3931
+ return (d.organic ?? []).filter((x) => x.link).map((x) => [plain3(x.title).replace(/\s+/g, " ").trim(), stripTracking(x.link), isoDay(x.date), null, cleanSnippet(plain3(x.snippet))]);
3932
+ }
3933
+ function parseBrave(json2) {
3934
+ const d = JSON.parse(json2);
3935
+ return (d.web?.results ?? []).filter((x) => x.url).map((x) => [plain3(x.title).replace(/\s+/g, " ").trim(), x.url, isoDay(x.page_age ?? x.age), null, cleanSnippet(plain3(x.description))]);
3936
+ }
3937
+ var searchTimeoutSecs = (env = process.env) => {
3938
+ const n = Number(env.FH_WEB_SEARCH_TIMEOUT_SECS);
3939
+ return Number.isFinite(n) && n > 0 ? n : 10;
3940
+ };
3898
3941
  var live = async (url, body, headers) => {
3899
- const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), signal: AbortSignal.timeout(3e4) });
3942
+ const signal = AbortSignal.timeout(searchTimeoutSecs() * 1e3);
3943
+ let r;
3944
+ try {
3945
+ r = await fetch(url, body === void 0 ? { headers: { accept: "application/json", ...headers }, signal } : { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), signal });
3946
+ } catch (e) {
3947
+ throw signal.aborted ? new Error(`timeout ${searchTimeoutSecs()}s`) : e;
3948
+ }
3900
3949
  const text4 = await r.text();
3901
3950
  if (!r.ok) {
3902
3951
  let why = "";
3903
3952
  try {
3904
- why = JSON.parse(text4).error ?? JSON.parse(text4).message ?? "";
3953
+ const j = JSON.parse(text4);
3954
+ why = (typeof j.error === "string" ? j.error : j.error?.detail) ?? j.message ?? "";
3905
3955
  } catch {
3906
3956
  why = text4.slice(0, 120);
3907
3957
  }
@@ -3909,31 +3959,86 @@ var live = async (url, body, headers) => {
3909
3959
  }
3910
3960
  return text4;
3911
3961
  };
3912
- async function webSearch(raw, libraryDir = FH_EVIDENCE_DIR, post2 = live, key2 = webSearchKey()) {
3913
- if (!key2) return { ok: false, error: "web search not configured" };
3914
- const q = normalizeQuery2(raw);
3915
- if ("error" in q) return { ok: false, error: q.error };
3916
- const file3 = searchFile(libraryDir, searchKey2(q));
3962
+ var SEARCH = {
3963
+ exa: async (q, key2, post2) => parseExa(await post2("https://api.exa.ai/search", {
3964
+ query: q.query,
3965
+ ...q.sites ? { includeDomains: q.sites } : {},
3966
+ ...snippetsOn() ? { contents: { highlights: { query: q.query, numSentences: 2, highlightsPerUrl: 1 } } } : {}
3967
+ }, { "x-api-key": key2 })),
3968
+ serper: async (q, key2, post2) => parseSerper(await post2("https://google.serper.dev/search", { q: withSites(q) }, { "X-API-KEY": key2 })),
3969
+ brave: async (q, key2, post2) => parseBrave(await post2(`https://api.search.brave.com/res/v1/web/search?${new URLSearchParams({ q: withSites(q) })}`, void 0, { "X-Subscription-Token": key2 }))
3970
+ };
3971
+ var inFlight = /* @__PURE__ */ new Map();
3972
+ function oneProvider(q, cfg, libraryDir, post2, onEvent) {
3973
+ const file3 = searchFile(libraryDir, searchKey2(q, cfg.provider));
3974
+ const running = inFlight.get(file3);
3975
+ if (running) return running;
3976
+ const p = askProvider(q, cfg, libraryDir, post2, onEvent).finally(() => inFlight.delete(file3));
3977
+ inFlight.set(file3, p);
3978
+ return p;
3979
+ }
3980
+ async function askProvider(q, cfg, libraryDir, post2, onEvent) {
3981
+ const file3 = searchFile(libraryDir, searchKey2(q, cfg.provider));
3917
3982
  if (existsSync8(file3)) {
3918
3983
  try {
3919
3984
  const r = JSON.parse(readFileSync6(file3, "utf8"));
3920
- if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: r, cached: true };
3985
+ if (daysSince(r.searched) < searchCacheDays()) return { rows: r.rows, cached: true };
3921
3986
  } catch {
3922
3987
  }
3923
3988
  }
3989
+ onEvent?.(`try ${cfg.provider}`);
3990
+ const t0 = Date.now();
3924
3991
  let rows;
3925
3992
  try {
3926
- rows = parseExa(await post2("https://api.exa.ai/search", { query: q.query, numResults: q.max_results, ...q.sites ? { includeDomains: q.sites } : {} }, { "x-api-key": key2 }));
3993
+ rows = (await SEARCH[cfg.provider](q, cfg.key, post2)).filter((r) => !q.sites || q.sites.some((d) => siteDomain(r[1])?.endsWith(d)));
3927
3994
  } catch (e) {
3928
- return { ok: false, error: `exa: ${e instanceof Error ? e.message : String(e)}` };
3995
+ onEvent?.(`failed ${cfg.provider}: ${e instanceof Error ? e.message : String(e)}`);
3996
+ throw e;
3929
3997
  }
3930
- const result = { source: "exa", query: q, total: rows.length, columns: COLUMNS2, rows, searched: today() };
3998
+ onEvent?.(`ok ${cfg.provider} ${((Date.now() - t0) / 1e3).toFixed(1)}s rows=${rows.length}`);
3999
+ const result = { source: cfg.provider, query: q, total: rows.length, columns: COLUMNS2, rows, searched: today() };
3931
4000
  try {
3932
4001
  mkdirSync7(dirname4(file3), { recursive: true });
3933
4002
  writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
3934
4003
  } catch {
3935
4004
  }
3936
- return { ok: true, result, cached: false };
4005
+ return { rows, cached: false };
4006
+ }
4007
+ var pageKey = (u) => u.replace(/^https?:\/\/(www\.)?/i, "").replace(/[?#].*$/, "").replace(/\/+$/, "").toLowerCase();
4008
+ function mergeRows(lists) {
4009
+ const pages = /* @__PURE__ */ new Map();
4010
+ for (const rows of lists) rows.forEach((r, i) => {
4011
+ const k = pageKey(r[1]);
4012
+ const p = pages.get(k);
4013
+ if (!p) {
4014
+ pages.set(k, { row: [...r], hits: 1, best: i });
4015
+ return;
4016
+ }
4017
+ p.hits++;
4018
+ p.best = Math.min(p.best, i);
4019
+ for (const f of [2, 3, 4]) p.row[f] ??= r[f];
4020
+ });
4021
+ return [...pages.values()].sort((a, b) => b.hits - a.hits || a.best - b.best).map((p) => p.row);
4022
+ }
4023
+ async function webSearch(raw, libraryDir = FH_EVIDENCE_DIR, post2 = live, cfgs = webSearchConfig(), onEvent) {
4024
+ if (!cfgs.length) return { ok: false, error: "web search not configured" };
4025
+ const q = normalizeQuery2(raw);
4026
+ if ("error" in q) return { ok: false, error: q.error };
4027
+ const answers = await Promise.allSettled(cfgs.map((c) => oneProvider(q, c, libraryDir, post2, onEvent)));
4028
+ const providers = {};
4029
+ const lists = [];
4030
+ let allCached = true;
4031
+ answers.forEach((a, i) => {
4032
+ const name = cfgs[i].provider;
4033
+ if (a.status === "fulfilled") {
4034
+ providers[name] = a.value.rows.length;
4035
+ lists.push(a.value.rows);
4036
+ allCached &&= a.value.cached;
4037
+ } else providers[name] = a.reason instanceof Error ? a.reason.message : String(a.reason);
4038
+ });
4039
+ if (!lists.length) return { ok: false, error: Object.entries(providers).map(([n, e]) => `${n}: ${e}`).join("; ") };
4040
+ const all = mergeRows(lists);
4041
+ return { ok: true, result: { total: all.length, columns: COLUMNS2, rows: all.slice(0, q.max_results), providers, query: q }, cached: allCached };
3937
4042
  }
3938
4043
 
3939
4044
  // src/info.ts
@@ -3968,7 +4073,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
3968
4073
  config: { ...settings(), problems: [...tiers.problems, ...verifyProblems()], sources: sources() },
3969
4074
  download: downloadInfo(),
3970
4075
  verify: verifyInfo(),
3971
- web_search: webSearchConfigured() ? "exa" : null,
4076
+ web_search: webSearchConfig().map((c) => c.provider),
3972
4077
  unlockers: unlockers().map((provider) => ({ provider })),
3973
4078
  stages: ownStages(),
3974
4079
  entries: 0,
@@ -4744,10 +4849,10 @@ var climb = async (given, onTry, onAlert) => {
4744
4849
  const isGone = (g) => g.ok ? null : goneReason(g.reason) ?? null;
4745
4850
  const one = await firstOk(first, isGone);
4746
4851
  if (one.won) return one.won;
4747
- const plain3 = one.results[0] ?? one.results.find(Boolean);
4748
- const firstReason = plain3.ok ? void 0 : plain3.reason;
4749
- const target = !plain3.ok && plain3.url && plain3.url !== url ? plain3.url : url;
4750
- let r = one.results[1] ?? plain3;
4852
+ const plain4 = one.results[0] ?? one.results.find(Boolean);
4853
+ const firstReason = plain4.ok ? void 0 : plain4.reason;
4854
+ const target = !plain4.ok && plain4.url && plain4.url !== url ? plain4.url : url;
4855
+ let r = one.results[1] ?? plain4;
4751
4856
  const plainVia = (g) => g.via === "fetch" || g.via.startsWith("fetch-proxy ");
4752
4857
  const met = (g, re) => re.test(g.ok ? "" : g.reason) || plainVia(g) && re.test(firstReason ?? "");
4753
4858
  const escalates = (g) => !g.ok && (!plainVia(g) || met(g, /^(HTTP 403|HTTP 429|wall page|script shell)/));
@@ -5249,8 +5354,8 @@ var reviewTypes = (types) => types.filter((t) => t !== "Journal Article" && !/^R
5249
5354
  import { createHash as createHash6 } from "crypto";
5250
5355
  import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync11 } from "fs";
5251
5356
  import { dirname as dirname7 } from "path";
5252
- var MAX_RESULTS3 = 100;
5253
- var DEFAULT_RESULTS3 = 20;
5357
+ var MAX_RESULTS2 = 100;
5358
+ var DEFAULT_RESULTS2 = 20;
5254
5359
  var COLUMNS3 = ["pmid", "title", "first_author", "year", "journal", "publication_types", "pmcid", "level"];
5255
5360
  var EUTILS = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils";
5256
5361
  var ident = (u) => {
@@ -5274,7 +5379,7 @@ function normalizeQuery3(q) {
5274
5379
  if (!["relevance", "newest"].includes(sort)) return { error: `sort must be relevance or newest, not "${String(q.sort)}"` };
5275
5380
  const yr = yearRange(q.years);
5276
5381
  if (yr && "error" in yr) return yr;
5277
- const out = { query, sort, max_results: Math.min(MAX_RESULTS3, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS3))) };
5382
+ const out = { query, sort, max_results: Math.min(MAX_RESULTS2, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS2))) };
5278
5383
  if (yr) out.years = `${yr.min === "1000" ? "" : yr.min}-${yr.max}`;
5279
5384
  return out;
5280
5385
  }
@@ -5368,8 +5473,8 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
5368
5473
  import { createHash as createHash7 } from "crypto";
5369
5474
  import { existsSync as existsSync14, mkdirSync as mkdirSync11, readFileSync as readFileSync12 } from "fs";
5370
5475
  import { dirname as dirname8 } from "path";
5371
- var MAX_RESULTS4 = 100;
5372
- var DEFAULT_RESULTS4 = 20;
5476
+ var MAX_RESULTS3 = 100;
5477
+ var DEFAULT_RESULTS3 = 20;
5373
5478
  var COLUMNS4 = ["set_id", "title", "labeler", "published", "version", "level"];
5374
5479
  var API3 = "https://dailymed.nlm.nih.gov/dailymed/services/v2/spls.json";
5375
5480
  var MONTHS2 = { Jan: "01", Feb: "02", Mar: "03", Apr: "04", May: "05", Jun: "06", Jul: "07", Aug: "08", Sep: "09", Oct: "10", Nov: "11", Dec: "12" };
@@ -5377,7 +5482,7 @@ function normalizeQuery4(q) {
5377
5482
  const drug_name = (q.drug_name ?? "").replace(/\s+/g, " ").trim();
5378
5483
  if (!drug_name) return { error: "empty drug_name" };
5379
5484
  const labeler = (q.labeler ?? "").replace(/\s+/g, " ").trim();
5380
- const out = { drug_name, max_results: Math.min(MAX_RESULTS4, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS4))) };
5485
+ const out = { drug_name, max_results: Math.min(MAX_RESULTS3, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS3))) };
5381
5486
  if (labeler) out.labeler = labeler;
5382
5487
  return out;
5383
5488
  }
@@ -5695,7 +5800,7 @@ Tools
5695
5800
  - fh_pubmed_search_articles(query, max_results?, sort?, years?) \u2014 search PubMed in its own syntax: the total and rows in columns order (PMID, title, first author, year, journal, publication types, PMCID, library level); faster and far smaller than asking PubMed. Cached a week.
5696
5801
  - 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.
5697
5802
  - fh_dailymed_search_labels(drug_name, labeler?, max_results?) \u2014 find FDA drug labels by generic or brand name: the total and rows in columns order (set ID, title, labeler, published, version, level), newest first; labeler narrows to one company. Use it rather than DailyMed's search page, which shows no set IDs as Markdown. Cached a week.
5698
- ${webSearchConfigured() ? "- fh_web_search(query, max_results?) \u2014 search the web; use it instead of the built-in web search. Links (title, URL, date, author), not page text, so a fraction of the context; read a result with fh_fetch_url. site: in the query restricts it to a site, as with any search engine. Cached locally for a week.\n" : ""}- 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.
5803
+ ${webSearchConfigured() ? "- fh_web_search(query, max_results?) \u2014 search the web; use it instead of the built-in web search. Links (title, URL, date, author) with a short passage from each page, not the page text, so a fraction of the context; read a result with fh_fetch_url. site: in the query restricts it to a site, as with any search engine. For more results, search again with other words. Cached locally for a week.\n" : ""}- 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.
5699
5804
  - 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.
5700
5805
  - 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.
5701
5806
 
@@ -6258,10 +6363,10 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6258
6363
  );
6259
6364
  server2.tool(
6260
6365
  "fh_pubmed_search_articles",
6261
- `Search PubMed with its own query syntax (AND / OR, field tags like [pt], [ti], [mesh]); sort relevance | newest; years "2020-2026". Faster and far smaller than asking PubMed: the total and up to ${MAX_RESULTS3} rows as arrays in columns order \u2014 PMID, title, first author, year, journal, publication types, PMCID when free full text exists, and the library level when the paper is already stored. The same search is answered from disk for ${searchCacheDays()} days. For a batch of PMIDs: fh_pubmed_fetch_articles; for abstract or full text: fh_library_read.`,
6366
+ `Search PubMed with its own query syntax (AND / OR, field tags like [pt], [ti], [mesh]); sort relevance | newest; years "2020-2026". Faster and far smaller than asking PubMed: the total and up to ${MAX_RESULTS2} rows as arrays in columns order \u2014 PMID, title, first author, year, journal, publication types, PMCID when free full text exists, and the library level when the paper is already stored. The same search is answered from disk for ${searchCacheDays()} days. For a batch of PMIDs: fh_pubmed_fetch_articles; for abstract or full text: fh_library_read.`,
6262
6367
  {
6263
6368
  query: z.string().describe('PubMed query, full syntax: "tadalafil AND (systematic review[pt] OR meta-analysis[pt])".'),
6264
- max_results: z.number().int().min(1).max(MAX_RESULTS3).default(20).describe("Rows to return (1\u2013100)."),
6369
+ max_results: z.number().int().min(1).max(MAX_RESULTS2).default(20).describe("Rows to return (1\u2013100)."),
6265
6370
  sort: z.enum(["relevance", "newest"]).default("relevance").describe("relevance (PubMed's ranking) or newest (publication date, latest first)."),
6266
6371
  years: z.string().optional().describe('Publication years: "2020-2026", "2022-", "-2019" or "2022".')
6267
6372
  },
@@ -6306,14 +6411,14 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6306
6411
  );
6307
6412
  if (webSearchConfigured()) server2.tool(
6308
6413
  "fh_web_search",
6309
- `Search the web \u2014 use it instead of the built-in web search. It returns links (title, URL, date, author), not page text, so it costs a fraction of the context; read a result with fh_fetch_url. It finds more, especially within one site: restrict it with site: in the query, as with any search engine ("metformin site:nih.gov", several with "(site:nih.gov OR site:who.int)"), a restriction the built-in search often ignores. Searches are cached locally for ${searchCacheDays()} days; a repeated search is answered in milliseconds.`,
6414
+ `Search the web \u2014 use it instead of the built-in web search. It returns links (title, URL, date, author) with a short passage from each page, not the page text, so it costs a fraction of the context; read a result with fh_fetch_url. It finds more, especially within one site: restrict it with site: in the query, as with any search engine ("metformin site:nih.gov", several with "(site:nih.gov OR site:who.int)"), a restriction the built-in search often ignores. Each search returns all it finds; for more, search again with other words. Searches are cached locally for ${searchCacheDays()} days; a repeated search is answered in milliseconds.`,
6310
6415
  {
6311
6416
  query: z.string().describe('The query, site: terms included: "metformin site:nih.gov", "statin muscle pain".'),
6312
- max_results: z.number().int().min(1).max(MAX_RESULTS2).default(10).describe("Rows to return (1\u201325).")
6417
+ max_results: z.number().int().min(1).optional().describe("At most this many rows; unset: all the search finds.")
6313
6418
  },
6314
6419
  async (args) => {
6315
6420
  const t0 = Date.now();
6316
- const r = await webSearch(args, FH_EVIDENCE_DIR);
6421
+ const r = await webSearch(args, FH_EVIDENCE_DIR, void 0, void 0, (line) => log("search", "web", `${line} | ${args.query}`));
6317
6422
  const secs = ((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0") + "s";
6318
6423
  if (!r.ok) {
6319
6424
  log("search", "web", `error: ${r.error}`);
@@ -6321,17 +6426,18 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6321
6426
  }
6322
6427
  bump("search", r.cached);
6323
6428
  const q = r.result.query;
6324
- log("search", "web", `ok ${r.cached ? "cached" : secs} rows=${r.result.rows.length} | ${q.query}${q.sites ? " " + q.sites.map((d) => `site:${d}`).join(" ") : ""}`);
6325
- return { content: [{ type: "text", text: searchAnswer(r.result) }] };
6429
+ const per = Object.entries(r.result.providers).map(([n, v]) => `${n}=${typeof v === "number" ? v : "failed"}`).join(" ");
6430
+ log("search", "web", `ok ${r.cached ? "cached" : secs} rows=${r.result.rows.length}${r.result.rows.length < r.result.total ? ` of ${r.result.total}` : ""} ${per} | ${q.query}${q.sites ? " " + q.sites.map((d) => `site:${d}`).join(" ") : ""}`);
6431
+ return { content: [{ type: "text", text: searchAnswer({ total: r.result.total, columns: r.result.columns, rows: r.result.rows }) }] };
6326
6432
  }
6327
6433
  );
6328
6434
  server2.tool(
6329
6435
  "fh_dailymed_search_labels",
6330
- `Find FDA drug labels on DailyMed by drug name, generic or brand: the total and up to ${MAX_RESULTS4} rows as arrays in columns order \u2014 set ID, title (drug and form), labeler (the company), published date, version, and the library level when the label is already stored. Newest first. A generic name lists every maker's label; labeler narrows to one company ("Boehringer" for Micardis's maker), a brand name to its own labels. Pass the set ID as "dailymed:<set ID>" to fh_library_read or fh_library_add. Use this, not DailyMed's search page: fetched as Markdown the page shows no set IDs, raw it is some 150,000 characters. The same search is answered from disk for ${searchCacheDays()} days.`,
6436
+ `Find FDA drug labels on DailyMed by drug name, generic or brand: the total and up to ${MAX_RESULTS3} rows as arrays in columns order \u2014 set ID, title (drug and form), labeler (the company), published date, version, and the library level when the label is already stored. Newest first. A generic name lists every maker's label; labeler narrows to one company ("Boehringer" for Micardis's maker), a brand name to its own labels. Pass the set ID as "dailymed:<set ID>" to fh_library_read or fh_library_add. Use this, not DailyMed's search page: fetched as Markdown the page shows no set IDs, raw it is some 150,000 characters. The same search is answered from disk for ${searchCacheDays()} days.`,
6331
6437
  {
6332
6438
  drug_name: z.string().describe('Generic or brand name: "telmisartan", "Micardis".'),
6333
6439
  labeler: z.string().optional().describe(`Part of the company's name, to narrow to its labels: "Boehringer".`),
6334
- max_results: z.number().int().min(1).max(MAX_RESULTS4).default(20).describe("Rows to return (1\u2013100).")
6440
+ max_results: z.number().int().min(1).max(MAX_RESULTS3).default(20).describe("Rows to return (1\u2013100).")
6335
6441
  },
6336
6442
  async (args) => {
6337
6443
  const t0 = Date.now();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "evidence-mcp-dev",
3
- "version": "1.0.9",
3
+ "version": "1.0.11",
4
4
  "description": "Internal development build of evidence-mcp. Not for public use.",
5
5
  "type": "module",
6
6
  "bin": {