evidence-mcp-dev 1.0.7 → 1.0.8

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 +324 -214
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2638,8 +2638,8 @@ function walled(url, stage2, dir = FH_EVIDENCE_DIR) {
2638
2638
  const h = host(url);
2639
2639
  if (!h) return null;
2640
2640
  const all = read(dir, h);
2641
- const live3 = (r) => r && (r.streak >= WALL_STREAK || RULE.test(r.reason)) && daysSince(r.date) < settings().retry_after_days ? r : null;
2642
- return live3(all[stage2] ?? all[legacy(stage2)]) ?? live3(all[pathKey(url, stage2)]);
2641
+ const live4 = (r) => r && (r.streak >= WALL_STREAK || RULE.test(r.reason)) && daysSince(r.date) < settings().retry_after_days ? r : null;
2642
+ return live4(all[stage2] ?? all[legacy(stage2)]) ?? live4(all[pathKey(url, stage2)]);
2643
2643
  }
2644
2644
  function recordStage(url, stage2, ok, reason = "", dir = FH_EVIDENCE_DIR) {
2645
2645
  const h = host(url);
@@ -3246,6 +3246,7 @@ 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
3250
  "FH_ZENROWS_API_KEY",
3250
3251
  "FH_ZYTE_API_KEY",
3251
3252
  "FH_BRIGHTDATA_API_KEY",
@@ -3618,7 +3619,7 @@ function publish() {
3618
3619
  }
3619
3620
 
3620
3621
  // src/tools.ts
3621
- import { existsSync as existsSync15, readFileSync as readFileSync13 } from "fs";
3622
+ import { existsSync as existsSync16, readFileSync as readFileSync14 } from "fs";
3622
3623
  import { z } from "zod";
3623
3624
 
3624
3625
  // src/cascade.ts
@@ -3727,13 +3728,221 @@ function libraryIdForUrl(raw) {
3727
3728
  return null;
3728
3729
  }
3729
3730
 
3730
- // src/info.ts
3731
- import { existsSync as existsSync7, readdirSync as readdirSync4, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
3731
+ // src/websearch.ts
3732
+ import { createHash as createHash3 } from "crypto";
3733
+ import { existsSync as existsSync8, mkdirSync as mkdirSync7, readFileSync as readFileSync6 } from "fs";
3734
+ import { dirname as dirname4 } from "path";
3735
+
3736
+ // src/trials.ts
3737
+ import { createHash as createHash2 } from "crypto";
3738
+ import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync5 } from "fs";
3732
3739
  import { dirname as dirname3, join as join8 } from "path";
3740
+ var searchCacheDays = () => settings().search_cache_days;
3741
+ var API2 = "https://clinicaltrials.gov/api/v2/studies";
3742
+ var FIELDS = ["NCTId", "BriefTitle", "OverallStatus", "WhyStopped", "Phase", "StudyType", "EnrollmentCount", "EnrollmentType", "StartDate", "PrimaryCompletionDate", "CompletionDate", "LastUpdatePostDate", "PrimaryOutcomeMeasure", "PrimaryOutcomeTimeFrame", "Condition", "InterventionName", "LeadSponsorName", "HasResults"];
3743
+ var ONGOING = ["RECRUITING", "NOT_YET_RECRUITING", "ACTIVE_NOT_RECRUITING", "ENROLLING_BY_INVITATION"];
3744
+ var MAX_RESULTS = 100;
3745
+ var DEFAULT_RESULTS = 20;
3746
+ var SORTS = { relevance: null, newest: "LastUpdatePostDate:desc", largest: "EnrollmentCount:desc", completion: "CompletionDate:desc" };
3747
+ var COLUMNS = [
3748
+ "nct",
3749
+ "title",
3750
+ "status",
3751
+ // "Terminated — slow accrual": a trial past its completion date is not "ongoing" (ER.md 28.7)
3752
+ "phase",
3753
+ "enrollment",
3754
+ // "48" actual, "~100" estimated — participant count (28.5)
3755
+ "start",
3756
+ "primary_completion",
3757
+ "primary_outcome",
3758
+ // the first primary outcome with its time frame, cut at 80 characters — the primary endpoint (28.5)
3759
+ "conditions",
3760
+ "interventions",
3761
+ // "IVF; Infertility, Female" — one string each
3762
+ "has_results"
3763
+ // posted results: get_study_results (28.8)
3764
+ ];
3765
+ var clean = (s) => (s ?? "").replace(/\s+/g, " ").trim();
3766
+ function normalizeQuery(q) {
3767
+ const out = { status: q.status ?? "all", sort: q.sort ?? "relevance", max_results: Math.min(MAX_RESULTS, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS))) };
3768
+ if (clean(q.query)) out.query = clean(q.query);
3769
+ if (clean(q.intervention)) out.intervention = clean(q.intervention);
3770
+ if (clean(q.condition)) out.condition = clean(q.condition);
3771
+ if (!out.query && !out.intervention && !out.condition) return { error: "empty search: give query, intervention or condition" };
3772
+ if (!["ongoing", "completed", "all"].includes(out.status)) return { error: `status must be ongoing, completed or all, not "${String(q.status)}"` };
3773
+ if (!(out.sort in SORTS)) return { error: `sort must be relevance, newest, largest or completion, not "${String(q.sort)}"` };
3774
+ return out;
3775
+ }
3776
+ var searchKey = (q) => createHash2("sha1").update(JSON.stringify(["clinicaltrials", q.query ?? "", q.intervention ?? "", q.condition ?? "", q.status, q.sort, q.max_results])).digest("hex").slice(0, 16);
3777
+ var searchFile = (libraryDir, key2) => join8(libraryDir, "search", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
3778
+ function searchUrl(q) {
3779
+ const p = new URLSearchParams();
3780
+ if (q.query) p.set("query.term", q.query);
3781
+ if (q.intervention) p.set("query.intr", q.intervention);
3782
+ if (q.condition) p.set("query.cond", q.condition);
3783
+ if (q.status === "ongoing") p.set("filter.overallStatus", ONGOING.join(","));
3784
+ if (q.status === "completed") p.set("filter.overallStatus", "COMPLETED");
3785
+ if (SORTS[q.sort]) p.set("sort", SORTS[q.sort]);
3786
+ p.set("fields", FIELDS.join(","));
3787
+ p.set("pageSize", String(q.max_results));
3788
+ p.set("countTotal", "true");
3789
+ return `${API2}?${p.toString()}`;
3790
+ }
3791
+ var STATUS2 = { NOT_YET_RECRUITING: "Not yet recruiting", RECRUITING: "Recruiting", ENROLLING_BY_INVITATION: "Enrolling by invitation", ACTIVE_NOT_RECRUITING: "Active, not recruiting", SUSPENDED: "Suspended", TERMINATED: "Terminated", COMPLETED: "Completed", WITHDRAWN: "Withdrawn", UNKNOWN: "Unknown status", AVAILABLE: "Available", NO_LONGER_AVAILABLE: "No longer available", TEMPORARILY_NOT_AVAILABLE: "Temporarily not available", APPROVED_FOR_MARKETING: "Approved for marketing", WITHHELD: "Withheld" };
3792
+ var PHASE2 = { EARLY_PHASE1: "Early Phase 1", PHASE1: "Phase 1", PHASE2: "Phase 2", PHASE3: "Phase 3", PHASE4: "Phase 4", NA: "Not applicable" };
3793
+ var joined = (xs) => xs.length ? xs.map((x) => x.replace(/\s+/g, " ").trim()).filter(Boolean).join("; ") || null : null;
3794
+ function parseRows(json2) {
3795
+ const d = JSON.parse(json2);
3796
+ const rows = [];
3797
+ for (const s of Array.isArray(d.studies) ? d.studies : []) {
3798
+ const p = s.protocolSection ?? {};
3799
+ const id = p.identificationModule ?? {}, st = p.statusModule ?? {}, des = p.designModule ?? {};
3800
+ const phases = Array.isArray(des.phases) ? des.phases : [];
3801
+ const nct = String(id.nctId ?? "");
3802
+ const en = des.enrollmentInfo ?? {};
3803
+ const outcomes = Array.isArray(p.outcomesModule?.primaryOutcomes) ? p.outcomesModule.primaryOutcomes : [];
3804
+ const first = outcomes[0];
3805
+ const cut = (t, n) => t.length > n ? t.slice(0, n - 1).trimEnd() + "\u2026" : t;
3806
+ const primary = first?.measure ? cut(`${String(first.measure).replace(/\s+/g, " ").trim()}${first.timeFrame ? ` (${String(first.timeFrame).replace(/\s+/g, " ").trim()})` : ""}`, 80) + (outcomes.length > 1 ? ` +${outcomes.length - 1}` : "") : null;
3807
+ const status = (STATUS2[st.overallStatus] ?? String(st.overallStatus ?? "")) + (st.whyStopped ? ` \u2014 ${String(st.whyStopped).replace(/\s+/g, " ").trim()}` : "");
3808
+ rows.push([
3809
+ nct,
3810
+ String(id.briefTitle ?? ""),
3811
+ status,
3812
+ phases.length ? phases.map((x) => PHASE2[x] ?? x).join(" / ") : null,
3813
+ typeof en.count === "number" ? `${String(en.type).toUpperCase() === "ESTIMATED" ? "~" : ""}${en.count}` : null,
3814
+ st.startDateStruct?.date ?? null,
3815
+ st.primaryCompletionDateStruct?.date ?? null,
3816
+ primary,
3817
+ joined(Array.isArray(p.conditionsModule?.conditions) ? p.conditionsModule.conditions.map(String) : []),
3818
+ joined(Array.isArray(p.armsInterventionsModule?.interventions) ? p.armsInterventionsModule.interventions.map((i) => String(i?.name ?? "")).filter(Boolean) : []),
3819
+ s.hasResults === true
3820
+ ]);
3821
+ }
3822
+ return { total: typeof d.totalCount === "number" ? d.totalCount : rows.length, rows };
3823
+ }
3824
+ var liveFetch = (url) => fetchText(url, { "User-Agent": LIBRARY_UA, Accept: "application/json" });
3825
+ async function searchTrials(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liveFetch) {
3826
+ const q = normalizeQuery(raw);
3827
+ if ("error" in q) return { ok: false, error: q.error };
3828
+ const file3 = searchFile(libraryDir, searchKey(q));
3829
+ if (existsSync7(file3)) {
3830
+ try {
3831
+ const r = JSON.parse(readFileSync5(file3, "utf8"));
3832
+ if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: r, cached: true };
3833
+ } catch {
3834
+ }
3835
+ }
3836
+ let json2;
3837
+ try {
3838
+ json2 = await fetchImpl(searchUrl(q));
3839
+ } catch (e) {
3840
+ return { ok: false, error: `clinicaltrials.gov: ${e instanceof Error ? e.message : String(e)}` };
3841
+ }
3842
+ let parsed;
3843
+ try {
3844
+ parsed = parseRows(json2);
3845
+ } catch {
3846
+ return { ok: false, error: "clinicaltrials.gov: not a studies answer" };
3847
+ }
3848
+ const result = { source: "clinicaltrials", query: q, total: parsed.total, columns: COLUMNS, rows: parsed.rows, searched: today() };
3849
+ try {
3850
+ mkdirSync6(dirname3(file3), { recursive: true });
3851
+ writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
3852
+ } catch {
3853
+ }
3854
+ return { ok: true, result, cached: false };
3855
+ }
3856
+
3857
+ // 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);
3863
+ function siteDomain(site) {
3864
+ const s = site.trim().toLowerCase().replace(/^site:/, "");
3865
+ if (!s) return null;
3866
+ try {
3867
+ return new URL(/^https?:\/\//.test(s) ? s : `https://${s}`).hostname.replace(/^www\./, "") || null;
3868
+ } catch {
3869
+ return null;
3870
+ }
3871
+ }
3872
+ function normalizeQuery2(q) {
3873
+ let query = (q.query ?? "").replace(/\s+/g, " ").trim();
3874
+ const sites = [];
3875
+ for (const m of query.matchAll(/(?:^|[\s(])site:([^\s()]+)/gi)) {
3876
+ const d = siteDomain(m[1]);
3877
+ if (!d) return { error: `site: needs a domain like "nih.gov", not "${m[1]}"` };
3878
+ if (!sites.includes(d)) sites.push(d);
3879
+ }
3880
+ if (sites.length) {
3881
+ 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
+ }
3883
+ 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))) };
3885
+ if (sites.length) out.sites = sites;
3886
+ return out;
3887
+ }
3888
+ var searchKey2 = (q) => createHash3("sha1").update(JSON.stringify(["web", "exa", q.query.toLowerCase(), q.sites ?? [], q.max_results])).digest("hex").slice(0, 16);
3889
+ function parseExa(json2) {
3890
+ const d = JSON.parse(json2);
3891
+ return (d.results ?? []).filter((x) => x.url).map((x) => [
3892
+ (x.title ?? "").replace(/\s+/g, " ").trim(),
3893
+ x.url,
3894
+ x.publishedDate ? x.publishedDate.slice(0, 10) : null,
3895
+ x.author ? x.author.replace(/\s+/g, " ").trim() : null
3896
+ ]);
3897
+ }
3898
+ 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) });
3900
+ const text4 = await r.text();
3901
+ if (!r.ok) {
3902
+ let why = "";
3903
+ try {
3904
+ why = JSON.parse(text4).error ?? JSON.parse(text4).message ?? "";
3905
+ } catch {
3906
+ why = text4.slice(0, 120);
3907
+ }
3908
+ throw new Error(`HTTP ${r.status}${why ? `: ${why}` : ""}`);
3909
+ }
3910
+ return text4;
3911
+ };
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));
3917
+ if (existsSync8(file3)) {
3918
+ try {
3919
+ const r = JSON.parse(readFileSync6(file3, "utf8"));
3920
+ if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: r, cached: true };
3921
+ } catch {
3922
+ }
3923
+ }
3924
+ let rows;
3925
+ 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 }));
3927
+ } catch (e) {
3928
+ return { ok: false, error: `exa: ${e instanceof Error ? e.message : String(e)}` };
3929
+ }
3930
+ const result = { source: "exa", query: q, total: rows.length, columns: COLUMNS2, rows, searched: today() };
3931
+ try {
3932
+ mkdirSync7(dirname4(file3), { recursive: true });
3933
+ writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
3934
+ } catch {
3935
+ }
3936
+ return { ok: true, result, cached: false };
3937
+ }
3938
+
3939
+ // src/info.ts
3940
+ import { existsSync as existsSync9, readdirSync as readdirSync4, readFileSync as readFileSync7, statSync as statSync3 } from "fs";
3941
+ import { dirname as dirname5, join as join9 } from "path";
3733
3942
  function* metaFiles(dir) {
3734
- if (!existsSync7(dir)) return;
3943
+ if (!existsSync9(dir)) return;
3735
3944
  for (const name of readdirSync4(dir)) {
3736
- const p = join8(dir, name);
3945
+ const p = join9(dir, name);
3737
3946
  if (statSync3(p).isDirectory()) yield* metaFiles(p);
3738
3947
  else if (name.endsWith("-meta.md")) yield p;
3739
3948
  }
@@ -3759,6 +3968,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
3759
3968
  config: { ...settings(), problems: [...tiers.problems, ...verifyProblems()], sources: sources() },
3760
3969
  download: downloadInfo(),
3761
3970
  verify: verifyInfo(),
3971
+ web_search: webSearchConfigured() ? "exa" : null,
3762
3972
  unlockers: unlockers().map((provider) => ({ provider })),
3763
3973
  stages: ownStages(),
3764
3974
  entries: 0,
@@ -3773,11 +3983,11 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
3773
3983
  concerns: 0,
3774
3984
  updates: 0
3775
3985
  };
3776
- for (const type of existsSync7(libraryDir) ? readdirSync4(libraryDir) : []) {
3777
- const typeDir = join8(libraryDir, type);
3986
+ for (const type of existsSync9(libraryDir) ? readdirSync4(libraryDir) : []) {
3987
+ const typeDir = join9(libraryDir, type);
3778
3988
  if (!statSync3(typeDir).isDirectory()) continue;
3779
3989
  for (const meta of metaFiles(typeDir)) {
3780
- const md = readFileSync5(meta, "utf8");
3990
+ const md = readFileSync7(meta, "utf8");
3781
3991
  const raw = field(md, "level") || "unknown";
3782
3992
  const level = raw === "abstract" && field(md, "has_abstract") === "no" ? "title" : raw;
3783
3993
  info.entries++;
@@ -3786,10 +3996,10 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
3786
3996
  const t = info.types[type] ??= { entries: 0, full_text: 0, abstract: 0, title: 0, retracted: 0 };
3787
3997
  t.entries++;
3788
3998
  if (level === "full_text" || level === "abstract" || level === "title") t[level]++;
3789
- const dir = dirname3(meta);
3999
+ const dir = dirname5(meta);
3790
4000
  for (const f of readdirSync4(dir)) {
3791
4001
  try {
3792
- const st = statSync3(join8(dir, f));
4002
+ const st = statSync3(join9(dir, f));
3793
4003
  if (st.isFile()) info.size_bytes += st.size;
3794
4004
  } catch {
3795
4005
  }
@@ -3816,7 +4026,7 @@ function noticeTypes(md, metaPath) {
3816
4026
  return out;
3817
4027
  }
3818
4028
  try {
3819
- const xml = readFileSync5(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
4029
+ const xml = readFileSync7(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
3820
4030
  for (const m of xml.matchAll(/<CommentsCorrections RefType="([A-Za-z]+)"/g)) if (XML_TYPES[m[1]]) out.add(XML_TYPES[m[1]]);
3821
4031
  } catch {
3822
4032
  }
@@ -4246,9 +4456,9 @@ function parseCsl(json2) {
4246
4456
  }
4247
4457
 
4248
4458
  // src/urlfetch.ts
4249
- import { createHash as createHash2 } from "crypto";
4250
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync6 } from "fs";
4251
- import { join as join9 } from "path";
4459
+ import { createHash as createHash4 } from "crypto";
4460
+ import { existsSync as existsSync10, mkdirSync as mkdirSync8, readFileSync as readFileSync8 } from "fs";
4461
+ import { join as join10 } from "path";
4252
4462
 
4253
4463
  // src/pagemeta.ts
4254
4464
  var CONTENT = /^(Article|NewsArticle|BlogPosting|ScholarlyArticle|MedicalScholarlyArticle|Report|MedicalWebPage|FAQPage|QAPage|Product|Drug|DietarySupplement|MedicalCondition|MedicalStudy|Dataset|Guideline|MedicalGuideline|HowTo|Recipe|PodcastEpisode|VideoObject|SearchResultsPage|CollectionPage|ProfilePage|WebPage)$/;
@@ -4384,12 +4594,12 @@ function normalizeUrl(raw) {
4384
4594
  }
4385
4595
  return u.toString();
4386
4596
  }
4387
- var urlHash = (normalized2) => createHash2("sha1").update(normalized2).digest("hex").slice(0, 16);
4597
+ var urlHash = (normalized2) => createHash4("sha1").update(normalized2).digest("hex").slice(0, 16);
4388
4598
  function urlPaths(libraryDir, normalized2) {
4389
4599
  const hash = urlHash(normalized2);
4390
4600
  const entry = `url-${hash}`;
4391
- const entryDir = join9(libraryDir, "url", hash.slice(0, 2), hash.slice(0, 4), hash);
4392
- return { hash, entry, entryDir, meta: join9(entryDir, `${entry}-meta.md`), md: join9(entryDir, `${entry}-page.md`), raw: (ext) => join9(entryDir, `${entry}-page.${ext}`) };
4601
+ const entryDir = join10(libraryDir, "url", hash.slice(0, 2), hash.slice(0, 4), hash);
4602
+ return { hash, entry, entryDir, meta: join10(entryDir, `${entry}-meta.md`), md: join10(entryDir, `${entry}-page.md`), raw: (ext) => join10(entryDir, `${entry}-page.${ext}`) };
4393
4603
  }
4394
4604
  function renderUrlMeta(m) {
4395
4605
  const lines = [
@@ -4411,8 +4621,8 @@ function renderUrlMeta(m) {
4411
4621
  return lines.map(([k, v]) => `${k}: ${v}`).join("\n") + "\n";
4412
4622
  }
4413
4623
  function readUrlMeta(p) {
4414
- if (!existsSync8(p.meta)) return null;
4415
- const md = readFileSync6(p.meta, "utf8");
4624
+ if (!existsSync10(p.meta)) return null;
4625
+ const md = readFileSync8(p.meta, "utf8");
4416
4626
  const f = (k) => {
4417
4627
  const m = new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md);
4418
4628
  return m ? m[1].trim() : "";
@@ -4447,7 +4657,7 @@ function readUrlMeta(p) {
4447
4657
  };
4448
4658
  }
4449
4659
  function writeUrlMeta(p, m) {
4450
- mkdirSync6(p.entryDir, { recursive: true });
4660
+ mkdirSync8(p.entryDir, { recursive: true });
4451
4661
  writeAtomic(p.meta, renderUrlMeta(m));
4452
4662
  }
4453
4663
  var SHELL_WORDS = 100;
@@ -4726,14 +4936,14 @@ function titleLine(m, md) {
4726
4936
  }
4727
4937
  function serve(requested, p, m, args, cached) {
4728
4938
  const maxLength = args.max_length ?? 5e3, startIndex = args.start_index ?? 0;
4729
- const read2 = (file3) => existsSync8(file3) ? readFileSync6(file3, "utf8") : "";
4939
+ const read2 = (file3) => existsSync10(file3) ? readFileSync8(file3, "utf8") : "";
4730
4940
  if (args.title_only) return { ok: true, text: `Contents of ${requested}:
4731
4941
  ${titleLine(m, read2(p.md))}`, cached, meta: m };
4732
4942
  const rawFile = m.files.find((f) => !f.endsWith("-meta.md") && !f.endsWith("-page.md"));
4733
4943
  let body, prefix = "";
4734
4944
  if (m.format === "markdown") body = read2(p.md);
4735
4945
  else if (m.format === "text" || args.raw) {
4736
- body = rawFile ? read2(join9(p.entryDir, rawFile)) : read2(p.md);
4946
+ body = rawFile ? read2(join10(p.entryDir, rawFile)) : read2(p.md);
4737
4947
  prefix = `Content type ${m.content_type || "(not declared)"} cannot be simplified to markdown, but here is the raw content:
4738
4948
  `;
4739
4949
  } else body = read2(p.md);
@@ -4751,9 +4961,9 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
4751
4961
  let stored = readUrlMeta(p);
4752
4962
  if (stored && fresh(stored) && stored.format === "html" && olderConverter(stored.converted_by, converter)) {
4753
4963
  const html = stored.files.find((f) => f.endsWith("-page.html"));
4754
- if (html && existsSync8(join9(p.entryDir, html))) {
4964
+ if (html && existsSync10(join10(p.entryDir, html))) {
4755
4965
  try {
4756
- const page = await convert(readFileSync6(join9(p.entryDir, html)), stored.content_type || "text/html", stored.final_url || stored.url);
4966
+ const page = await convert(readFileSync8(join10(p.entryDir, html)), stored.content_type || "text/html", stored.final_url || stored.url);
4757
4967
  if (page.md !== null) {
4758
4968
  writeAtomic(p.md, page.md);
4759
4969
  writeUrlMeta(p, { ...stored, title: page.title, converted_by: converter, ...sourceFields(page) });
@@ -4775,7 +4985,7 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
4775
4985
  return;
4776
4986
  }
4777
4987
  const page = await convert(r.bytes, r.contentType, r.url);
4778
- mkdirSync6(p.entryDir, { recursive: true });
4988
+ mkdirSync8(p.entryDir, { recursive: true });
4779
4989
  const files = [`${p.entry}-meta.md`];
4780
4990
  if (page.md !== null) {
4781
4991
  writeAtomic(p.md, page.md);
@@ -4796,12 +5006,12 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
4796
5006
  }
4797
5007
 
4798
5008
  // src/verify/cache.ts
4799
- import { createHash as createHash3 } from "crypto";
4800
- import { existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync8 } from "fs";
4801
- import { dirname as dirname4, join as join10 } from "path";
5009
+ import { createHash as createHash5 } from "crypto";
5010
+ import { existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync10 } from "fs";
5011
+ import { dirname as dirname6, join as join11 } from "path";
4802
5012
 
4803
5013
  // src/verify/verify.ts
4804
- import { existsSync as existsSync9, readFileSync as readFileSync7 } from "fs";
5014
+ import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
4805
5015
  var QUESTION = "Does the paper state this, in substance? Ignore section labels and definitions of terms in parentheses. Every fact and number of the statement must be stated in the paper or follow from its numbers; a rounded number counts. If any part of the statement is absent from the paper or contradicted by it, answer false.";
4806
5016
  function cleanMarkdown(md) {
4807
5017
  return paperYearOnly(dropReferences(md)).replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\]\([^)]*\)/g, "]").replace(/^\s*#+\s*(see more about|more for you|back to top)\b.*$/gim, "").replace(/\n{3,}/g, "\n\n");
@@ -4905,10 +5115,10 @@ async function readPaper(raw, libraryDir = FH_EVIDENCE_DIR) {
4905
5115
  if (p.error) return { id: p.requested, error: p.error };
4906
5116
  const paths = entryPaths(libraryDir, p.type, p.id);
4907
5117
  if (!entryExists(paths)) return { id: p.requested, error: "not in library" };
4908
- const full = existsSync9(paths.fulltextMd);
4909
- if (full) return { id: p.requested, basis: "full_text", text: readFileSync7(paths.fulltextMd, "utf8") };
5118
+ const full = existsSync11(paths.fulltextMd);
5119
+ if (full) return { id: p.requested, basis: "full_text", text: readFileSync9(paths.fulltextMd, "utf8") };
4910
5120
  const meta = readMeta(paths);
4911
- return { id: p.requested, basis: meta.has_abstract ? "abstract" : "title", text: readFileSync7(paths.md, "utf8") };
5121
+ return { id: p.requested, basis: meta.has_abstract ? "abstract" : "title", text: readFileSync9(paths.md, "utf8") };
4912
5122
  }
4913
5123
  async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
4914
5124
  const out = { claim, id, verdict: "error", reason: null, score: null, basis: null, windows: 0, glyphs_unresolved: 0, superseded: null, model: cfg?.model ?? null };
@@ -4948,7 +5158,7 @@ async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
4948
5158
  }
4949
5159
 
4950
5160
  // src/verify/cache.ts
4951
- var sha = (s) => createHash3("sha1").update(s).digest("hex");
5161
+ var sha = (s) => createHash5("sha1").update(s).digest("hex");
4952
5162
  var normalizeClaim = (claim) => claim.replace(/\s+/g, " ").trim();
4953
5163
  function foldClaim(claim) {
4954
5164
  return claim.normalize("NFKC").toLowerCase().replace(/[\u2018\u2019\u201a\u201b\u2032]/g, "'").replace(/[\u201c\u201d\u201e\u201f\u2033]/g, '"').replace(/[\u2010-\u2015\u2212]/g, "-").replace(/\+\/-|\+-/g, "\xB1").replace(/\s+/g, " ").trim().replace(/[.;:,]+$/, "").trim();
@@ -4959,11 +5169,11 @@ ${id}
4959
5169
  ${model}
4960
5170
  ${threshold}
4961
5171
  ${text4}`).slice(0, 16);
4962
- var verdictFile = (libraryDir, key2) => join10(libraryDir, "verify", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
5172
+ var verdictFile = (libraryDir, key2) => join11(libraryDir, "verify", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
4963
5173
  function readVerdict(file3) {
4964
- if (!existsSync10(file3)) return null;
5174
+ if (!existsSync12(file3)) return null;
4965
5175
  try {
4966
- return JSON.parse(readFileSync8(file3, "utf8"));
5176
+ return JSON.parse(readFileSync10(file3, "utf8"));
4967
5177
  } catch {
4968
5178
  return null;
4969
5179
  }
@@ -4973,7 +5183,7 @@ function lookup2(file3, maxDays) {
4973
5183
  return c && daysSince(c.date) < maxDays ? c : null;
4974
5184
  }
4975
5185
  function remember(file3, c) {
4976
- mkdirSync7(dirname4(file3), { recursive: true });
5186
+ mkdirSync9(dirname6(file3), { recursive: true });
4977
5187
  writeAtomic(file3, JSON.stringify(c, null, 2) + "\n");
4978
5188
  }
4979
5189
  async function verifyCached(claim, id, cfg, decide, libraryDir = FH_EVIDENCE_DIR, read2 = readPaper) {
@@ -5035,134 +5245,13 @@ function searchAnswer(r) {
5035
5245
  }
5036
5246
  var reviewTypes = (types) => types.filter((t) => t !== "Journal Article" && !/^Research Support\b/.test(t));
5037
5247
 
5038
- // src/trials.ts
5039
- import { createHash as createHash4 } from "crypto";
5040
- import { existsSync as existsSync11, mkdirSync as mkdirSync8, readFileSync as readFileSync9 } from "fs";
5041
- import { dirname as dirname5, join as join11 } from "path";
5042
- var searchCacheDays = () => settings().search_cache_days;
5043
- var API2 = "https://clinicaltrials.gov/api/v2/studies";
5044
- var FIELDS = ["NCTId", "BriefTitle", "OverallStatus", "WhyStopped", "Phase", "StudyType", "EnrollmentCount", "EnrollmentType", "StartDate", "PrimaryCompletionDate", "CompletionDate", "LastUpdatePostDate", "PrimaryOutcomeMeasure", "PrimaryOutcomeTimeFrame", "Condition", "InterventionName", "LeadSponsorName", "HasResults"];
5045
- var ONGOING = ["RECRUITING", "NOT_YET_RECRUITING", "ACTIVE_NOT_RECRUITING", "ENROLLING_BY_INVITATION"];
5046
- var MAX_RESULTS = 100;
5047
- var DEFAULT_RESULTS = 20;
5048
- var SORTS = { relevance: null, newest: "LastUpdatePostDate:desc", largest: "EnrollmentCount:desc", completion: "CompletionDate:desc" };
5049
- var COLUMNS = [
5050
- "nct",
5051
- "title",
5052
- "status",
5053
- // "Terminated — slow accrual": a trial past its completion date is not "ongoing" (ER.md 28.7)
5054
- "phase",
5055
- "enrollment",
5056
- // "48" actual, "~100" estimated — participant count (28.5)
5057
- "start",
5058
- "primary_completion",
5059
- "primary_outcome",
5060
- // the first primary outcome with its time frame, cut at 80 characters — the primary endpoint (28.5)
5061
- "conditions",
5062
- "interventions",
5063
- // "IVF; Infertility, Female" — one string each
5064
- "has_results"
5065
- // posted results: get_study_results (28.8)
5066
- ];
5067
- var clean = (s) => (s ?? "").replace(/\s+/g, " ").trim();
5068
- function normalizeQuery(q) {
5069
- const out = { status: q.status ?? "all", sort: q.sort ?? "relevance", max_results: Math.min(MAX_RESULTS, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS))) };
5070
- if (clean(q.query)) out.query = clean(q.query);
5071
- if (clean(q.intervention)) out.intervention = clean(q.intervention);
5072
- if (clean(q.condition)) out.condition = clean(q.condition);
5073
- if (!out.query && !out.intervention && !out.condition) return { error: "empty search: give query, intervention or condition" };
5074
- if (!["ongoing", "completed", "all"].includes(out.status)) return { error: `status must be ongoing, completed or all, not "${String(q.status)}"` };
5075
- if (!(out.sort in SORTS)) return { error: `sort must be relevance, newest, largest or completion, not "${String(q.sort)}"` };
5076
- return out;
5077
- }
5078
- var searchKey = (q) => createHash4("sha1").update(JSON.stringify(["clinicaltrials", q.query ?? "", q.intervention ?? "", q.condition ?? "", q.status, q.sort, q.max_results])).digest("hex").slice(0, 16);
5079
- var searchFile = (libraryDir, key2) => join11(libraryDir, "search", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
5080
- function searchUrl(q) {
5081
- const p = new URLSearchParams();
5082
- if (q.query) p.set("query.term", q.query);
5083
- if (q.intervention) p.set("query.intr", q.intervention);
5084
- if (q.condition) p.set("query.cond", q.condition);
5085
- if (q.status === "ongoing") p.set("filter.overallStatus", ONGOING.join(","));
5086
- if (q.status === "completed") p.set("filter.overallStatus", "COMPLETED");
5087
- if (SORTS[q.sort]) p.set("sort", SORTS[q.sort]);
5088
- p.set("fields", FIELDS.join(","));
5089
- p.set("pageSize", String(q.max_results));
5090
- p.set("countTotal", "true");
5091
- return `${API2}?${p.toString()}`;
5092
- }
5093
- var STATUS2 = { NOT_YET_RECRUITING: "Not yet recruiting", RECRUITING: "Recruiting", ENROLLING_BY_INVITATION: "Enrolling by invitation", ACTIVE_NOT_RECRUITING: "Active, not recruiting", SUSPENDED: "Suspended", TERMINATED: "Terminated", COMPLETED: "Completed", WITHDRAWN: "Withdrawn", UNKNOWN: "Unknown status", AVAILABLE: "Available", NO_LONGER_AVAILABLE: "No longer available", TEMPORARILY_NOT_AVAILABLE: "Temporarily not available", APPROVED_FOR_MARKETING: "Approved for marketing", WITHHELD: "Withheld" };
5094
- var PHASE2 = { EARLY_PHASE1: "Early Phase 1", PHASE1: "Phase 1", PHASE2: "Phase 2", PHASE3: "Phase 3", PHASE4: "Phase 4", NA: "Not applicable" };
5095
- var joined = (xs) => xs.length ? xs.map((x) => x.replace(/\s+/g, " ").trim()).filter(Boolean).join("; ") || null : null;
5096
- function parseRows(json2) {
5097
- const d = JSON.parse(json2);
5098
- const rows = [];
5099
- for (const s of Array.isArray(d.studies) ? d.studies : []) {
5100
- const p = s.protocolSection ?? {};
5101
- const id = p.identificationModule ?? {}, st = p.statusModule ?? {}, des = p.designModule ?? {};
5102
- const phases = Array.isArray(des.phases) ? des.phases : [];
5103
- const nct = String(id.nctId ?? "");
5104
- const en = des.enrollmentInfo ?? {};
5105
- const outcomes = Array.isArray(p.outcomesModule?.primaryOutcomes) ? p.outcomesModule.primaryOutcomes : [];
5106
- const first = outcomes[0];
5107
- const cut = (t, n) => t.length > n ? t.slice(0, n - 1).trimEnd() + "\u2026" : t;
5108
- const primary = first?.measure ? cut(`${String(first.measure).replace(/\s+/g, " ").trim()}${first.timeFrame ? ` (${String(first.timeFrame).replace(/\s+/g, " ").trim()})` : ""}`, 80) + (outcomes.length > 1 ? ` +${outcomes.length - 1}` : "") : null;
5109
- const status = (STATUS2[st.overallStatus] ?? String(st.overallStatus ?? "")) + (st.whyStopped ? ` \u2014 ${String(st.whyStopped).replace(/\s+/g, " ").trim()}` : "");
5110
- rows.push([
5111
- nct,
5112
- String(id.briefTitle ?? ""),
5113
- status,
5114
- phases.length ? phases.map((x) => PHASE2[x] ?? x).join(" / ") : null,
5115
- typeof en.count === "number" ? `${String(en.type).toUpperCase() === "ESTIMATED" ? "~" : ""}${en.count}` : null,
5116
- st.startDateStruct?.date ?? null,
5117
- st.primaryCompletionDateStruct?.date ?? null,
5118
- primary,
5119
- joined(Array.isArray(p.conditionsModule?.conditions) ? p.conditionsModule.conditions.map(String) : []),
5120
- joined(Array.isArray(p.armsInterventionsModule?.interventions) ? p.armsInterventionsModule.interventions.map((i) => String(i?.name ?? "")).filter(Boolean) : []),
5121
- s.hasResults === true
5122
- ]);
5123
- }
5124
- return { total: typeof d.totalCount === "number" ? d.totalCount : rows.length, rows };
5125
- }
5126
- var liveFetch = (url) => fetchText(url, { "User-Agent": LIBRARY_UA, Accept: "application/json" });
5127
- async function searchTrials(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liveFetch) {
5128
- const q = normalizeQuery(raw);
5129
- if ("error" in q) return { ok: false, error: q.error };
5130
- const file3 = searchFile(libraryDir, searchKey(q));
5131
- if (existsSync11(file3)) {
5132
- try {
5133
- const r = JSON.parse(readFileSync9(file3, "utf8"));
5134
- if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: r, cached: true };
5135
- } catch {
5136
- }
5137
- }
5138
- let json2;
5139
- try {
5140
- json2 = await fetchImpl(searchUrl(q));
5141
- } catch (e) {
5142
- return { ok: false, error: `clinicaltrials.gov: ${e instanceof Error ? e.message : String(e)}` };
5143
- }
5144
- let parsed;
5145
- try {
5146
- parsed = parseRows(json2);
5147
- } catch {
5148
- return { ok: false, error: "clinicaltrials.gov: not a studies answer" };
5149
- }
5150
- const result = { source: "clinicaltrials", query: q, total: parsed.total, columns: COLUMNS, rows: parsed.rows, searched: today() };
5151
- try {
5152
- mkdirSync8(dirname5(file3), { recursive: true });
5153
- writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
5154
- } catch {
5155
- }
5156
- return { ok: true, result, cached: false };
5157
- }
5158
-
5159
5248
  // src/pubmedsearch.ts
5160
- import { createHash as createHash5 } from "crypto";
5161
- import { existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync10 } from "fs";
5162
- import { dirname as dirname6 } from "path";
5163
- var MAX_RESULTS2 = 100;
5164
- var DEFAULT_RESULTS2 = 20;
5165
- var COLUMNS2 = ["pmid", "title", "first_author", "year", "journal", "publication_types", "pmcid", "level"];
5249
+ import { createHash as createHash6 } from "crypto";
5250
+ import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync11 } from "fs";
5251
+ import { dirname as dirname7 } from "path";
5252
+ var MAX_RESULTS3 = 100;
5253
+ var DEFAULT_RESULTS3 = 20;
5254
+ var COLUMNS3 = ["pmid", "title", "first_author", "year", "journal", "publication_types", "pmcid", "level"];
5166
5255
  var EUTILS = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils";
5167
5256
  var ident = (u) => {
5168
5257
  if (process.env.FH_NCBI_API_KEY) u.searchParams.set("api_key", process.env.FH_NCBI_API_KEY);
@@ -5178,18 +5267,18 @@ function yearRange(years) {
5178
5267
  const min = m[1] ?? "1000", max = m[3] ?? (m[2] ? String((/* @__PURE__ */ new Date()).getFullYear()) : m[1]);
5179
5268
  return { min, max };
5180
5269
  }
5181
- function normalizeQuery2(q) {
5270
+ function normalizeQuery3(q) {
5182
5271
  const query = (q.query ?? "").replace(/\s+/g, " ").trim();
5183
5272
  if (!query) return { error: "empty query" };
5184
5273
  const sort = q.sort ?? "relevance";
5185
5274
  if (!["relevance", "newest"].includes(sort)) return { error: `sort must be relevance or newest, not "${String(q.sort)}"` };
5186
5275
  const yr = yearRange(q.years);
5187
5276
  if (yr && "error" in yr) return yr;
5188
- const out = { query, sort, max_results: Math.min(MAX_RESULTS2, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS2))) };
5277
+ const out = { query, sort, max_results: Math.min(MAX_RESULTS3, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS3))) };
5189
5278
  if (yr) out.years = `${yr.min === "1000" ? "" : yr.min}-${yr.max}`;
5190
5279
  return out;
5191
5280
  }
5192
- var searchKey2 = (q) => createHash5("sha1").update(JSON.stringify(["pubmed", q.query, q.sort, q.years ?? "", q.max_results])).digest("hex").slice(0, 16);
5281
+ var searchKey3 = (q) => createHash6("sha1").update(JSON.stringify(["pubmed", q.query, q.sort, q.years ?? "", q.max_results])).digest("hex").slice(0, 16);
5193
5282
  function esearchUrl(q) {
5194
5283
  const u = new URL(`${EUTILS}/esearch.fcgi`);
5195
5284
  u.searchParams.set("db", "pubmed");
@@ -5236,14 +5325,14 @@ function levelOf(id, libraryDir) {
5236
5325
  const paths = entryPaths(libraryDir, "pmid", id);
5237
5326
  return entryExists(paths) ? String(readStatus(paths, emptyStatus(`pmid:${id}`, "pmid", id, libraryDir)).level) : null;
5238
5327
  }
5239
- var live = (url) => fetchText(url, { "User-Agent": "evidence-mcp", Accept: "application/json" });
5240
- async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live) {
5241
- const q = normalizeQuery2(raw);
5328
+ var live2 = (url) => fetchText(url, { "User-Agent": "evidence-mcp", Accept: "application/json" });
5329
+ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live2) {
5330
+ const q = normalizeQuery3(raw);
5242
5331
  if ("error" in q) return { ok: false, error: q.error };
5243
- const file3 = searchFile(libraryDir, searchKey2(q));
5244
- if (existsSync12(file3)) {
5332
+ const file3 = searchFile(libraryDir, searchKey3(q));
5333
+ if (existsSync13(file3)) {
5245
5334
  try {
5246
- const r = JSON.parse(readFileSync10(file3, "utf8"));
5335
+ const r = JSON.parse(readFileSync11(file3, "utf8"));
5247
5336
  if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: { ...r, rows: r.rows.map((row3) => {
5248
5337
  const c = [...row3];
5249
5338
  c[7] = levelOf(String(row3[0]), libraryDir);
@@ -5266,9 +5355,9 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
5266
5355
  return { ok: false, error: `pubmed: ${e instanceof Error ? e.message : String(e)}` };
5267
5356
  }
5268
5357
  }
5269
- const result = { source: "pubmed", query: q, total, columns: COLUMNS2, rows, searched: today() };
5358
+ const result = { source: "pubmed", query: q, total, columns: COLUMNS3, rows, searched: today() };
5270
5359
  try {
5271
- mkdirSync9(dirname6(file3), { recursive: true });
5360
+ mkdirSync10(dirname7(file3), { recursive: true });
5272
5361
  writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
5273
5362
  } catch {
5274
5363
  }
@@ -5276,23 +5365,23 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
5276
5365
  }
5277
5366
 
5278
5367
  // src/dailymedsearch.ts
5279
- import { createHash as createHash6 } from "crypto";
5280
- import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync11 } from "fs";
5281
- import { dirname as dirname7 } from "path";
5282
- var MAX_RESULTS3 = 100;
5283
- var DEFAULT_RESULTS3 = 20;
5284
- var COLUMNS3 = ["set_id", "title", "labeler", "published", "version", "level"];
5368
+ import { createHash as createHash7 } from "crypto";
5369
+ import { existsSync as existsSync14, mkdirSync as mkdirSync11, readFileSync as readFileSync12 } from "fs";
5370
+ import { dirname as dirname8 } from "path";
5371
+ var MAX_RESULTS4 = 100;
5372
+ var DEFAULT_RESULTS4 = 20;
5373
+ var COLUMNS4 = ["set_id", "title", "labeler", "published", "version", "level"];
5285
5374
  var API3 = "https://dailymed.nlm.nih.gov/dailymed/services/v2/spls.json";
5286
5375
  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" };
5287
- function normalizeQuery3(q) {
5376
+ function normalizeQuery4(q) {
5288
5377
  const drug_name = (q.drug_name ?? "").replace(/\s+/g, " ").trim();
5289
5378
  if (!drug_name) return { error: "empty drug_name" };
5290
5379
  const labeler = (q.labeler ?? "").replace(/\s+/g, " ").trim();
5291
- const out = { drug_name, max_results: Math.min(MAX_RESULTS3, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS3))) };
5380
+ const out = { drug_name, max_results: Math.min(MAX_RESULTS4, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS4))) };
5292
5381
  if (labeler) out.labeler = labeler;
5293
5382
  return out;
5294
5383
  }
5295
- var searchKey3 = (q) => createHash6("sha1").update(JSON.stringify(["dailymed", q.drug_name.toLowerCase(), (q.labeler ?? "").toLowerCase(), q.max_results])).digest("hex").slice(0, 16);
5384
+ var searchKey4 = (q) => createHash7("sha1").update(JSON.stringify(["dailymed", q.drug_name.toLowerCase(), (q.labeler ?? "").toLowerCase(), q.max_results])).digest("hex").slice(0, 16);
5296
5385
  function searchUrl2(q) {
5297
5386
  const u = new URL(API3);
5298
5387
  u.searchParams.set("drug_name", q.drug_name);
@@ -5322,14 +5411,14 @@ function parseSearch(json2, libraryDir) {
5322
5411
  }
5323
5412
  return { total: Number(d.metadata?.total_elements ?? rows.length) || rows.length, rows };
5324
5413
  }
5325
- var live2 = (url) => fetchText(url, { "User-Agent": LIBRARY_UA, Accept: "application/json" });
5326
- async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live2) {
5327
- const q = normalizeQuery3(raw);
5414
+ var live3 = (url) => fetchText(url, { "User-Agent": LIBRARY_UA, Accept: "application/json" });
5415
+ async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live3) {
5416
+ const q = normalizeQuery4(raw);
5328
5417
  if ("error" in q) return { ok: false, error: q.error };
5329
- const file3 = searchFile(libraryDir, searchKey3(q));
5330
- if (existsSync13(file3)) {
5418
+ const file3 = searchFile(libraryDir, searchKey4(q));
5419
+ if (existsSync14(file3)) {
5331
5420
  try {
5332
- const r = JSON.parse(readFileSync11(file3, "utf8"));
5421
+ const r = JSON.parse(readFileSync12(file3, "utf8"));
5333
5422
  if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: { ...r, rows: r.rows.map((row3) => {
5334
5423
  const c = [...row3];
5335
5424
  c[5] = levelOf2(row3[0], libraryDir);
@@ -5344,9 +5433,9 @@ async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live2
5344
5433
  } catch (e) {
5345
5434
  return { ok: false, error: `dailymed: ${e instanceof Error ? e.message : String(e)}` };
5346
5435
  }
5347
- const result = { source: "dailymed", query: q, total: parsed.total, columns: COLUMNS3, rows: parsed.rows, searched: today() };
5436
+ const result = { source: "dailymed", query: q, total: parsed.total, columns: COLUMNS4, rows: parsed.rows, searched: today() };
5348
5437
  try {
5349
- mkdirSync10(dirname7(file3), { recursive: true });
5438
+ mkdirSync11(dirname8(file3), { recursive: true });
5350
5439
  writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
5351
5440
  } catch {
5352
5441
  }
@@ -5470,13 +5559,13 @@ function resultsText(nct, md, maxChars) {
5470
5559
  }
5471
5560
 
5472
5561
  // src/missing.ts
5473
- import { existsSync as existsSync14, mkdirSync as mkdirSync11, readFileSync as readFileSync12 } from "fs";
5562
+ import { existsSync as existsSync15, mkdirSync as mkdirSync12, readFileSync as readFileSync13 } from "fs";
5474
5563
  import { join as join12 } from "path";
5475
5564
  var missingFile = (p) => join12(p.entryDir, `${p.entry}-missing.md`);
5476
5565
  function readMissing(p) {
5477
5566
  const f = missingFile(p);
5478
- if (!existsSync14(f)) return null;
5479
- const md = readFileSync12(f, "utf8");
5567
+ if (!existsSync15(f)) return null;
5568
+ const md = readFileSync13(f, "utf8");
5480
5569
  const get4 = (k) => /^$/.test(k) ? "" : (new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md)?.[1] ?? "").trim();
5481
5570
  const checked = get4("checked"), reason = get4("reason");
5482
5571
  return checked ? { checked, reason: reason || "not found" } : null;
@@ -5487,7 +5576,7 @@ function freshMissing(p, retryDays) {
5487
5576
  }
5488
5577
  function rememberMissing(p, reason) {
5489
5578
  const m = { checked: now(), reason };
5490
- mkdirSync11(p.entryDir, { recursive: true });
5579
+ mkdirSync12(p.entryDir, { recursive: true });
5491
5580
  writeAtomic(missingFile(p), `checked: ${m.checked}
5492
5581
  reason: ${m.reason}
5493
5582
  `);
@@ -5497,7 +5586,7 @@ var missingNote = (m, retryDays) => `${m.reason} (checked ${m.checked.slice(0, 1
5497
5586
 
5498
5587
  // src/pubmedbatch.ts
5499
5588
  var MAX_PMIDS = 200;
5500
- var COLUMNS4 = ["pmid", "title", "first_author", "year", "publication_types", "retracted", "level"];
5589
+ var COLUMNS5 = ["pmid", "title", "first_author", "year", "publication_types", "retracted", "level"];
5501
5590
  var EFETCH2 = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi";
5502
5591
  function efetchBatchUrl(pmids) {
5503
5592
  const u = new URL(EFETCH2);
@@ -5521,7 +5610,7 @@ function splitArticles(xml) {
5521
5610
  }
5522
5611
  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];
5523
5612
  async function fetchArticles(ids, libraryDir = FH_EVIDENCE_DIR, converter = "evidence-mcp", fetchImpl = fetchText) {
5524
- const result = { columns: COLUMNS4, rows: [], new: 0, cached: 0, not_found: 0, invalid: 0, asked: 0 };
5613
+ const result = { columns: COLUMNS5, rows: [], new: 0, cached: 0, not_found: 0, invalid: 0, asked: 0 };
5525
5614
  const order2 = [];
5526
5615
  const invalid = /* @__PURE__ */ new Map();
5527
5616
  for (const raw of ids.slice(0, MAX_PMIDS)) {
@@ -5583,7 +5672,7 @@ async function fetchArticles(ids, libraryDir = FH_EVIDENCE_DIR, converter = "evi
5583
5672
  // src/tools.ts
5584
5673
  var pkg = (() => {
5585
5674
  try {
5586
- return JSON.parse(readFileSync13(new URL("../package.json", import.meta.url), "utf8"));
5675
+ return JSON.parse(readFileSync14(new URL("../package.json", import.meta.url), "utf8"));
5587
5676
  } catch {
5588
5677
  return { name: "evidence-mcp", version: "0.0.0" };
5589
5678
  }
@@ -5606,7 +5695,7 @@ Tools
5606
5695
  - 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.
5607
5696
  - 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.
5608
5697
  - 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.
5609
- - 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.
5698
+ ${webSearchConfigured() ? "- fh_web_search(query, max_results?) \u2014 a web search, the query as for the built-in web search, site: restricting it to a domain (a journal, a health agency, a society, a clinic's or an author's website): rows of title, URL, published, author; read a page with fh_fetch_url. Use it for every web search instead of the built-in web search, and instead of a site's own search page. Cached 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.
5610
5699
  - 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.
5611
5700
  - 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.
5612
5701
 
@@ -5979,8 +6068,8 @@ function registerTools(server2) {
5979
6068
  }
5980
6069
  added = true;
5981
6070
  }
5982
- const full = existsSync15(paths.fulltextMd);
5983
- const md = readFileSync13(full ? paths.fulltextMd : paths.md, "utf8");
6071
+ const full = existsSync16(paths.fulltextMd);
6072
+ const md = readFileSync14(full ? paths.fulltextMd : paths.md, "utf8");
5984
6073
  const text4 = full ? "full_text" : "abstract";
5985
6074
  const base = added ? { requested: parsed.requested, entry: paths.entry, text: text4, added: true } : { requested: parsed.requested, entry: paths.entry, text: text4 };
5986
6075
  const headings2 = () => outline(md, text4).sections;
@@ -6000,8 +6089,8 @@ function registerTools(server2) {
6000
6089
  const cap = max_chars ?? 6e3;
6001
6090
  let sec = readSection(md, section2, cap);
6002
6091
  let via = "";
6003
- if (!sec && /abstract/i.test(section2) && full && existsSync15(paths.md)) {
6004
- sec = readSection(readFileSync13(paths.md, "utf8"), "abstract", cap);
6092
+ if (!sec && /abstract/i.test(section2) && full && existsSync16(paths.md)) {
6093
+ sec = readSection(readFileSync14(paths.md, "utf8"), "abstract", cap);
6005
6094
  via = " (from the abstract file)";
6006
6095
  }
6007
6096
  if (!sec && /declaration/i.test(section2)) {
@@ -6130,8 +6219,8 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
6130
6219
  return { content: [{ type: "text", text: `Failed to fetch ${url}: ${added.error}` }], isError: true };
6131
6220
  }
6132
6221
  }
6133
- const file3 = pid.type === "pmid" ? paths.md : existsSync15(paths.fulltextMd) ? paths.fulltextMd : paths.md;
6134
- const md = existsSync15(file3) ? readFileSync13(file3, "utf8") : "";
6222
+ const file3 = pid.type === "pmid" ? paths.md : existsSync16(paths.fulltextMd) ? paths.fulltextMd : paths.md;
6223
+ const md = existsSync16(file3) ? readFileSync14(file3, "utf8") : "";
6135
6224
  const text4 = title_only ? `Contents of ${url}:
6136
6225
  ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "", max_length, start_index);
6137
6226
  bump("fetch", had);
@@ -6169,10 +6258,10 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6169
6258
  );
6170
6259
  server2.tool(
6171
6260
  "fh_pubmed_search_articles",
6172
- `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.`,
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.`,
6173
6262
  {
6174
6263
  query: z.string().describe('PubMed query, full syntax: "tadalafil AND (systematic review[pt] OR meta-analysis[pt])".'),
6175
- max_results: z.number().int().min(1).max(MAX_RESULTS2).default(20).describe("Rows to return (1\u2013100)."),
6264
+ max_results: z.number().int().min(1).max(MAX_RESULTS3).default(20).describe("Rows to return (1\u2013100)."),
6176
6265
  sort: z.enum(["relevance", "newest"]).default("relevance").describe("relevance (PubMed's ranking) or newest (publication date, latest first)."),
6177
6266
  years: z.string().optional().describe('Publication years: "2020-2026", "2022-", "-2019" or "2022".')
6178
6267
  },
@@ -6215,13 +6304,34 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6215
6304
  return { content: [{ type: "text", text: searchAnswer(r.result) }] };
6216
6305
  }
6217
6306
  );
6307
+ if (webSearchConfigured()) server2.tool(
6308
+ "fh_web_search",
6309
+ `Search the web with the same query you would give the built-in web search: "metformin site:nih.gov" restricts it to one domain \u2014 a journal, a health agency, a society, a clinic's or an author's website \u2014 and "statins (site:nih.gov OR site:who.int)" to several. The rows as arrays in columns order \u2014 title, URL, published date, author \u2014 up to ${MAX_RESULTS2}; read a page with fh_fetch_url. Use this for every web search instead of the built-in web search, and instead of loading a site's own search page: the answer is small rows, the same search is answered from disk, a site: restriction holds (the built-in search often ignores it), and many sites' own search pages are script-rendered and come back empty. Cached for ${searchCacheDays()} days.`,
6310
+ {
6311
+ 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).")
6313
+ },
6314
+ async (args) => {
6315
+ const t0 = Date.now();
6316
+ const r = await webSearch(args, FH_EVIDENCE_DIR);
6317
+ const secs = ((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0") + "s";
6318
+ if (!r.ok) {
6319
+ log("search", "web", `error: ${r.error}`);
6320
+ return { content: [{ type: "text", text: compact2({ error: r.error }) }], isError: true };
6321
+ }
6322
+ bump("search", r.cached);
6323
+ 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) }] };
6326
+ }
6327
+ );
6218
6328
  server2.tool(
6219
6329
  "fh_dailymed_search_labels",
6220
- `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.`,
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.`,
6221
6331
  {
6222
6332
  drug_name: z.string().describe('Generic or brand name: "telmisartan", "Micardis".'),
6223
6333
  labeler: z.string().optional().describe(`Part of the company's name, to narrow to its labels: "Boehringer".`),
6224
- max_results: z.number().int().min(1).max(MAX_RESULTS3).default(20).describe("Rows to return (1\u2013100).")
6334
+ max_results: z.number().int().min(1).max(MAX_RESULTS4).default(20).describe("Rows to return (1\u2013100).")
6225
6335
  },
6226
6336
  async (args) => {
6227
6337
  const t0 = Date.now();
@@ -6262,7 +6372,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6262
6372
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
6263
6373
  }
6264
6374
  const raw = e.paths.fulltextRaw("json");
6265
- const r = existsSync15(raw) ? recordSummary(readFileSync13(raw, "utf8")) : null;
6375
+ const r = existsSync16(raw) ? recordSummary(readFileSync14(raw, "utf8")) : null;
6266
6376
  if (!r) {
6267
6377
  log("trials", e.requested, "record error: no stored record");
6268
6378
  return { content: [{ type: "text", text: compact2({ error: "no stored record" }) }], isError: true };
@@ -6281,7 +6391,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6281
6391
  log("trials", nct, `results error: ${e.error}`);
6282
6392
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
6283
6393
  }
6284
- const md = existsSync15(e.paths.fulltextMd) ? readFileSync13(e.paths.fulltextMd, "utf8") : "";
6394
+ const md = existsSync16(e.paths.fulltextMd) ? readFileSync14(e.paths.fulltextMd, "utf8") : "";
6285
6395
  const r = resultsText(e.requested.replace(/^nct:/, "NCT"), md, max_chars);
6286
6396
  log("trials", e.requested, `results ${r.has_results ? `${r.outcomes.length} outcomes${r.truncated ? " truncated" : ""}` : "none"}`);
6287
6397
  return { content: [{ type: "text", text: leanJson(r) }] };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "evidence-mcp-dev",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "Internal development build of evidence-mcp. Not for public use.",
5
5
  "type": "module",
6
6
  "bin": {