evidence-mcp-dev 1.0.6 → 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 +331 -217
  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",
@@ -3301,7 +3302,8 @@ var google = {
3301
3302
  // AQ.: the newer AI Studio keys
3302
3303
  modelPrefix: "gemini-",
3303
3304
  matches: (host3) => host3 === "generativelanguage.googleapis.com",
3304
- windowChars: () => 8e5,
3305
+ windowChars: () => 4e5,
3306
+ // as Perplexity hosted: 800,000-character windows went over a 262k-token limit there (dense papers, 1.7 characters a token)
3305
3307
  request: ({ base_url, api_key, model, state, questions }) => ({
3306
3308
  url: `${base_url}/v1beta/decisions`,
3307
3309
  headers: { "content-type": "application/json", ...api_key ? { "x-goog-api-key": api_key } : {} },
@@ -3384,11 +3386,14 @@ var perplexity = {
3384
3386
  keyPrefixes: ["pplx-"],
3385
3387
  modelPrefix: "pplx-",
3386
3388
  matches: (host3) => host3 === "api.perplexity.ai",
3387
- // Hosted takes 256k tokens in one request (a 50k-token paper in 2 s); the
3389
+ // Hosted takes 262,144 tokens in one request (a 50k-token paper in 2 s); the
3388
3390
  // Mac app is limited to 32k and slows steeply beyond 25k, so it windows.
3391
+ // Hosted windows of 400,000 characters: a paper's Markdown ran as dense as 1.7
3392
+ // characters a token (tables, numbers) — 800,000-character windows went over
3393
+ // the limit, 367 claims on live 2026-11-11–16 ("requires 470509 tokens").
3389
3394
  windowChars: (baseUrl) => {
3390
3395
  try {
3391
- return new URL(baseUrl).hostname === "api.perplexity.ai" ? 8e5 : 9e4;
3396
+ return new URL(baseUrl).hostname === "api.perplexity.ai" ? 4e5 : 9e4;
3392
3397
  } catch {
3393
3398
  return 9e4;
3394
3399
  }
@@ -3614,7 +3619,7 @@ function publish() {
3614
3619
  }
3615
3620
 
3616
3621
  // src/tools.ts
3617
- import { existsSync as existsSync15, readFileSync as readFileSync13 } from "fs";
3622
+ import { existsSync as existsSync16, readFileSync as readFileSync14 } from "fs";
3618
3623
  import { z } from "zod";
3619
3624
 
3620
3625
  // src/cascade.ts
@@ -3723,13 +3728,221 @@ function libraryIdForUrl(raw) {
3723
3728
  return null;
3724
3729
  }
3725
3730
 
3726
- // src/info.ts
3727
- 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";
3728
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";
3729
3942
  function* metaFiles(dir) {
3730
- if (!existsSync7(dir)) return;
3943
+ if (!existsSync9(dir)) return;
3731
3944
  for (const name of readdirSync4(dir)) {
3732
- const p = join8(dir, name);
3945
+ const p = join9(dir, name);
3733
3946
  if (statSync3(p).isDirectory()) yield* metaFiles(p);
3734
3947
  else if (name.endsWith("-meta.md")) yield p;
3735
3948
  }
@@ -3755,6 +3968,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
3755
3968
  config: { ...settings(), problems: [...tiers.problems, ...verifyProblems()], sources: sources() },
3756
3969
  download: downloadInfo(),
3757
3970
  verify: verifyInfo(),
3971
+ web_search: webSearchConfigured() ? "exa" : null,
3758
3972
  unlockers: unlockers().map((provider) => ({ provider })),
3759
3973
  stages: ownStages(),
3760
3974
  entries: 0,
@@ -3769,11 +3983,11 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
3769
3983
  concerns: 0,
3770
3984
  updates: 0
3771
3985
  };
3772
- for (const type of existsSync7(libraryDir) ? readdirSync4(libraryDir) : []) {
3773
- const typeDir = join8(libraryDir, type);
3986
+ for (const type of existsSync9(libraryDir) ? readdirSync4(libraryDir) : []) {
3987
+ const typeDir = join9(libraryDir, type);
3774
3988
  if (!statSync3(typeDir).isDirectory()) continue;
3775
3989
  for (const meta of metaFiles(typeDir)) {
3776
- const md = readFileSync5(meta, "utf8");
3990
+ const md = readFileSync7(meta, "utf8");
3777
3991
  const raw = field(md, "level") || "unknown";
3778
3992
  const level = raw === "abstract" && field(md, "has_abstract") === "no" ? "title" : raw;
3779
3993
  info.entries++;
@@ -3782,10 +3996,10 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
3782
3996
  const t = info.types[type] ??= { entries: 0, full_text: 0, abstract: 0, title: 0, retracted: 0 };
3783
3997
  t.entries++;
3784
3998
  if (level === "full_text" || level === "abstract" || level === "title") t[level]++;
3785
- const dir = dirname3(meta);
3999
+ const dir = dirname5(meta);
3786
4000
  for (const f of readdirSync4(dir)) {
3787
4001
  try {
3788
- const st = statSync3(join8(dir, f));
4002
+ const st = statSync3(join9(dir, f));
3789
4003
  if (st.isFile()) info.size_bytes += st.size;
3790
4004
  } catch {
3791
4005
  }
@@ -3812,7 +4026,7 @@ function noticeTypes(md, metaPath) {
3812
4026
  return out;
3813
4027
  }
3814
4028
  try {
3815
- const xml = readFileSync5(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
4029
+ const xml = readFileSync7(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
3816
4030
  for (const m of xml.matchAll(/<CommentsCorrections RefType="([A-Za-z]+)"/g)) if (XML_TYPES[m[1]]) out.add(XML_TYPES[m[1]]);
3817
4031
  } catch {
3818
4032
  }
@@ -4242,9 +4456,9 @@ function parseCsl(json2) {
4242
4456
  }
4243
4457
 
4244
4458
  // src/urlfetch.ts
4245
- import { createHash as createHash2 } from "crypto";
4246
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync6 } from "fs";
4247
- 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";
4248
4462
 
4249
4463
  // src/pagemeta.ts
4250
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)$/;
@@ -4380,12 +4594,12 @@ function normalizeUrl(raw) {
4380
4594
  }
4381
4595
  return u.toString();
4382
4596
  }
4383
- 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);
4384
4598
  function urlPaths(libraryDir, normalized2) {
4385
4599
  const hash = urlHash(normalized2);
4386
4600
  const entry = `url-${hash}`;
4387
- const entryDir = join9(libraryDir, "url", hash.slice(0, 2), hash.slice(0, 4), hash);
4388
- 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}`) };
4389
4603
  }
4390
4604
  function renderUrlMeta(m) {
4391
4605
  const lines = [
@@ -4407,8 +4621,8 @@ function renderUrlMeta(m) {
4407
4621
  return lines.map(([k, v]) => `${k}: ${v}`).join("\n") + "\n";
4408
4622
  }
4409
4623
  function readUrlMeta(p) {
4410
- if (!existsSync8(p.meta)) return null;
4411
- const md = readFileSync6(p.meta, "utf8");
4624
+ if (!existsSync10(p.meta)) return null;
4625
+ const md = readFileSync8(p.meta, "utf8");
4412
4626
  const f = (k) => {
4413
4627
  const m = new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md);
4414
4628
  return m ? m[1].trim() : "";
@@ -4443,7 +4657,7 @@ function readUrlMeta(p) {
4443
4657
  };
4444
4658
  }
4445
4659
  function writeUrlMeta(p, m) {
4446
- mkdirSync6(p.entryDir, { recursive: true });
4660
+ mkdirSync8(p.entryDir, { recursive: true });
4447
4661
  writeAtomic(p.meta, renderUrlMeta(m));
4448
4662
  }
4449
4663
  var SHELL_WORDS = 100;
@@ -4722,14 +4936,14 @@ function titleLine(m, md) {
4722
4936
  }
4723
4937
  function serve(requested, p, m, args, cached) {
4724
4938
  const maxLength = args.max_length ?? 5e3, startIndex = args.start_index ?? 0;
4725
- const read2 = (file3) => existsSync8(file3) ? readFileSync6(file3, "utf8") : "";
4939
+ const read2 = (file3) => existsSync10(file3) ? readFileSync8(file3, "utf8") : "";
4726
4940
  if (args.title_only) return { ok: true, text: `Contents of ${requested}:
4727
4941
  ${titleLine(m, read2(p.md))}`, cached, meta: m };
4728
4942
  const rawFile = m.files.find((f) => !f.endsWith("-meta.md") && !f.endsWith("-page.md"));
4729
4943
  let body, prefix = "";
4730
4944
  if (m.format === "markdown") body = read2(p.md);
4731
4945
  else if (m.format === "text" || args.raw) {
4732
- body = rawFile ? read2(join9(p.entryDir, rawFile)) : read2(p.md);
4946
+ body = rawFile ? read2(join10(p.entryDir, rawFile)) : read2(p.md);
4733
4947
  prefix = `Content type ${m.content_type || "(not declared)"} cannot be simplified to markdown, but here is the raw content:
4734
4948
  `;
4735
4949
  } else body = read2(p.md);
@@ -4747,9 +4961,9 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
4747
4961
  let stored = readUrlMeta(p);
4748
4962
  if (stored && fresh(stored) && stored.format === "html" && olderConverter(stored.converted_by, converter)) {
4749
4963
  const html = stored.files.find((f) => f.endsWith("-page.html"));
4750
- if (html && existsSync8(join9(p.entryDir, html))) {
4964
+ if (html && existsSync10(join10(p.entryDir, html))) {
4751
4965
  try {
4752
- 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);
4753
4967
  if (page.md !== null) {
4754
4968
  writeAtomic(p.md, page.md);
4755
4969
  writeUrlMeta(p, { ...stored, title: page.title, converted_by: converter, ...sourceFields(page) });
@@ -4771,7 +4985,7 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
4771
4985
  return;
4772
4986
  }
4773
4987
  const page = await convert(r.bytes, r.contentType, r.url);
4774
- mkdirSync6(p.entryDir, { recursive: true });
4988
+ mkdirSync8(p.entryDir, { recursive: true });
4775
4989
  const files = [`${p.entry}-meta.md`];
4776
4990
  if (page.md !== null) {
4777
4991
  writeAtomic(p.md, page.md);
@@ -4792,12 +5006,12 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
4792
5006
  }
4793
5007
 
4794
5008
  // src/verify/cache.ts
4795
- import { createHash as createHash3 } from "crypto";
4796
- import { existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync8 } from "fs";
4797
- 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";
4798
5012
 
4799
5013
  // src/verify/verify.ts
4800
- import { existsSync as existsSync9, readFileSync as readFileSync7 } from "fs";
5014
+ import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
4801
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.";
4802
5016
  function cleanMarkdown(md) {
4803
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");
@@ -4901,10 +5115,10 @@ async function readPaper(raw, libraryDir = FH_EVIDENCE_DIR) {
4901
5115
  if (p.error) return { id: p.requested, error: p.error };
4902
5116
  const paths = entryPaths(libraryDir, p.type, p.id);
4903
5117
  if (!entryExists(paths)) return { id: p.requested, error: "not in library" };
4904
- const full = existsSync9(paths.fulltextMd);
4905
- 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") };
4906
5120
  const meta = readMeta(paths);
4907
- 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") };
4908
5122
  }
4909
5123
  async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
4910
5124
  const out = { claim, id, verdict: "error", reason: null, score: null, basis: null, windows: 0, glyphs_unresolved: 0, superseded: null, model: cfg?.model ?? null };
@@ -4944,7 +5158,7 @@ async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
4944
5158
  }
4945
5159
 
4946
5160
  // src/verify/cache.ts
4947
- var sha = (s) => createHash3("sha1").update(s).digest("hex");
5161
+ var sha = (s) => createHash5("sha1").update(s).digest("hex");
4948
5162
  var normalizeClaim = (claim) => claim.replace(/\s+/g, " ").trim();
4949
5163
  function foldClaim(claim) {
4950
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();
@@ -4955,11 +5169,11 @@ ${id}
4955
5169
  ${model}
4956
5170
  ${threshold}
4957
5171
  ${text4}`).slice(0, 16);
4958
- 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`);
4959
5173
  function readVerdict(file3) {
4960
- if (!existsSync10(file3)) return null;
5174
+ if (!existsSync12(file3)) return null;
4961
5175
  try {
4962
- return JSON.parse(readFileSync8(file3, "utf8"));
5176
+ return JSON.parse(readFileSync10(file3, "utf8"));
4963
5177
  } catch {
4964
5178
  return null;
4965
5179
  }
@@ -4969,7 +5183,7 @@ function lookup2(file3, maxDays) {
4969
5183
  return c && daysSince(c.date) < maxDays ? c : null;
4970
5184
  }
4971
5185
  function remember(file3, c) {
4972
- mkdirSync7(dirname4(file3), { recursive: true });
5186
+ mkdirSync9(dirname6(file3), { recursive: true });
4973
5187
  writeAtomic(file3, JSON.stringify(c, null, 2) + "\n");
4974
5188
  }
4975
5189
  async function verifyCached(claim, id, cfg, decide, libraryDir = FH_EVIDENCE_DIR, read2 = readPaper) {
@@ -5031,134 +5245,13 @@ function searchAnswer(r) {
5031
5245
  }
5032
5246
  var reviewTypes = (types) => types.filter((t) => t !== "Journal Article" && !/^Research Support\b/.test(t));
5033
5247
 
5034
- // src/trials.ts
5035
- import { createHash as createHash4 } from "crypto";
5036
- import { existsSync as existsSync11, mkdirSync as mkdirSync8, readFileSync as readFileSync9 } from "fs";
5037
- import { dirname as dirname5, join as join11 } from "path";
5038
- var searchCacheDays = () => settings().search_cache_days;
5039
- var API2 = "https://clinicaltrials.gov/api/v2/studies";
5040
- var FIELDS = ["NCTId", "BriefTitle", "OverallStatus", "WhyStopped", "Phase", "StudyType", "EnrollmentCount", "EnrollmentType", "StartDate", "PrimaryCompletionDate", "CompletionDate", "LastUpdatePostDate", "PrimaryOutcomeMeasure", "PrimaryOutcomeTimeFrame", "Condition", "InterventionName", "LeadSponsorName", "HasResults"];
5041
- var ONGOING = ["RECRUITING", "NOT_YET_RECRUITING", "ACTIVE_NOT_RECRUITING", "ENROLLING_BY_INVITATION"];
5042
- var MAX_RESULTS = 100;
5043
- var DEFAULT_RESULTS = 20;
5044
- var SORTS = { relevance: null, newest: "LastUpdatePostDate:desc", largest: "EnrollmentCount:desc", completion: "CompletionDate:desc" };
5045
- var COLUMNS = [
5046
- "nct",
5047
- "title",
5048
- "status",
5049
- // "Terminated — slow accrual": a trial past its completion date is not "ongoing" (ER.md 28.7)
5050
- "phase",
5051
- "enrollment",
5052
- // "48" actual, "~100" estimated — participant count (28.5)
5053
- "start",
5054
- "primary_completion",
5055
- "primary_outcome",
5056
- // the first primary outcome with its time frame, cut at 80 characters — the primary endpoint (28.5)
5057
- "conditions",
5058
- "interventions",
5059
- // "IVF; Infertility, Female" — one string each
5060
- "has_results"
5061
- // posted results: get_study_results (28.8)
5062
- ];
5063
- var clean = (s) => (s ?? "").replace(/\s+/g, " ").trim();
5064
- function normalizeQuery(q) {
5065
- 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))) };
5066
- if (clean(q.query)) out.query = clean(q.query);
5067
- if (clean(q.intervention)) out.intervention = clean(q.intervention);
5068
- if (clean(q.condition)) out.condition = clean(q.condition);
5069
- if (!out.query && !out.intervention && !out.condition) return { error: "empty search: give query, intervention or condition" };
5070
- if (!["ongoing", "completed", "all"].includes(out.status)) return { error: `status must be ongoing, completed or all, not "${String(q.status)}"` };
5071
- if (!(out.sort in SORTS)) return { error: `sort must be relevance, newest, largest or completion, not "${String(q.sort)}"` };
5072
- return out;
5073
- }
5074
- 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);
5075
- var searchFile = (libraryDir, key2) => join11(libraryDir, "search", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
5076
- function searchUrl(q) {
5077
- const p = new URLSearchParams();
5078
- if (q.query) p.set("query.term", q.query);
5079
- if (q.intervention) p.set("query.intr", q.intervention);
5080
- if (q.condition) p.set("query.cond", q.condition);
5081
- if (q.status === "ongoing") p.set("filter.overallStatus", ONGOING.join(","));
5082
- if (q.status === "completed") p.set("filter.overallStatus", "COMPLETED");
5083
- if (SORTS[q.sort]) p.set("sort", SORTS[q.sort]);
5084
- p.set("fields", FIELDS.join(","));
5085
- p.set("pageSize", String(q.max_results));
5086
- p.set("countTotal", "true");
5087
- return `${API2}?${p.toString()}`;
5088
- }
5089
- 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" };
5090
- var PHASE2 = { EARLY_PHASE1: "Early Phase 1", PHASE1: "Phase 1", PHASE2: "Phase 2", PHASE3: "Phase 3", PHASE4: "Phase 4", NA: "Not applicable" };
5091
- var joined = (xs) => xs.length ? xs.map((x) => x.replace(/\s+/g, " ").trim()).filter(Boolean).join("; ") || null : null;
5092
- function parseRows(json2) {
5093
- const d = JSON.parse(json2);
5094
- const rows = [];
5095
- for (const s of Array.isArray(d.studies) ? d.studies : []) {
5096
- const p = s.protocolSection ?? {};
5097
- const id = p.identificationModule ?? {}, st = p.statusModule ?? {}, des = p.designModule ?? {};
5098
- const phases = Array.isArray(des.phases) ? des.phases : [];
5099
- const nct = String(id.nctId ?? "");
5100
- const en = des.enrollmentInfo ?? {};
5101
- const outcomes = Array.isArray(p.outcomesModule?.primaryOutcomes) ? p.outcomesModule.primaryOutcomes : [];
5102
- const first = outcomes[0];
5103
- const cut = (t, n) => t.length > n ? t.slice(0, n - 1).trimEnd() + "\u2026" : t;
5104
- 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;
5105
- const status = (STATUS2[st.overallStatus] ?? String(st.overallStatus ?? "")) + (st.whyStopped ? ` \u2014 ${String(st.whyStopped).replace(/\s+/g, " ").trim()}` : "");
5106
- rows.push([
5107
- nct,
5108
- String(id.briefTitle ?? ""),
5109
- status,
5110
- phases.length ? phases.map((x) => PHASE2[x] ?? x).join(" / ") : null,
5111
- typeof en.count === "number" ? `${String(en.type).toUpperCase() === "ESTIMATED" ? "~" : ""}${en.count}` : null,
5112
- st.startDateStruct?.date ?? null,
5113
- st.primaryCompletionDateStruct?.date ?? null,
5114
- primary,
5115
- joined(Array.isArray(p.conditionsModule?.conditions) ? p.conditionsModule.conditions.map(String) : []),
5116
- joined(Array.isArray(p.armsInterventionsModule?.interventions) ? p.armsInterventionsModule.interventions.map((i) => String(i?.name ?? "")).filter(Boolean) : []),
5117
- s.hasResults === true
5118
- ]);
5119
- }
5120
- return { total: typeof d.totalCount === "number" ? d.totalCount : rows.length, rows };
5121
- }
5122
- var liveFetch = (url) => fetchText(url, { "User-Agent": LIBRARY_UA, Accept: "application/json" });
5123
- async function searchTrials(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liveFetch) {
5124
- const q = normalizeQuery(raw);
5125
- if ("error" in q) return { ok: false, error: q.error };
5126
- const file3 = searchFile(libraryDir, searchKey(q));
5127
- if (existsSync11(file3)) {
5128
- try {
5129
- const r = JSON.parse(readFileSync9(file3, "utf8"));
5130
- if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: r, cached: true };
5131
- } catch {
5132
- }
5133
- }
5134
- let json2;
5135
- try {
5136
- json2 = await fetchImpl(searchUrl(q));
5137
- } catch (e) {
5138
- return { ok: false, error: `clinicaltrials.gov: ${e instanceof Error ? e.message : String(e)}` };
5139
- }
5140
- let parsed;
5141
- try {
5142
- parsed = parseRows(json2);
5143
- } catch {
5144
- return { ok: false, error: "clinicaltrials.gov: not a studies answer" };
5145
- }
5146
- const result = { source: "clinicaltrials", query: q, total: parsed.total, columns: COLUMNS, rows: parsed.rows, searched: today() };
5147
- try {
5148
- mkdirSync8(dirname5(file3), { recursive: true });
5149
- writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
5150
- } catch {
5151
- }
5152
- return { ok: true, result, cached: false };
5153
- }
5154
-
5155
5248
  // src/pubmedsearch.ts
5156
- import { createHash as createHash5 } from "crypto";
5157
- import { existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync10 } from "fs";
5158
- import { dirname as dirname6 } from "path";
5159
- var MAX_RESULTS2 = 100;
5160
- var DEFAULT_RESULTS2 = 20;
5161
- 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"];
5162
5255
  var EUTILS = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils";
5163
5256
  var ident = (u) => {
5164
5257
  if (process.env.FH_NCBI_API_KEY) u.searchParams.set("api_key", process.env.FH_NCBI_API_KEY);
@@ -5174,18 +5267,18 @@ function yearRange(years) {
5174
5267
  const min = m[1] ?? "1000", max = m[3] ?? (m[2] ? String((/* @__PURE__ */ new Date()).getFullYear()) : m[1]);
5175
5268
  return { min, max };
5176
5269
  }
5177
- function normalizeQuery2(q) {
5270
+ function normalizeQuery3(q) {
5178
5271
  const query = (q.query ?? "").replace(/\s+/g, " ").trim();
5179
5272
  if (!query) return { error: "empty query" };
5180
5273
  const sort = q.sort ?? "relevance";
5181
5274
  if (!["relevance", "newest"].includes(sort)) return { error: `sort must be relevance or newest, not "${String(q.sort)}"` };
5182
5275
  const yr = yearRange(q.years);
5183
5276
  if (yr && "error" in yr) return yr;
5184
- 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))) };
5185
5278
  if (yr) out.years = `${yr.min === "1000" ? "" : yr.min}-${yr.max}`;
5186
5279
  return out;
5187
5280
  }
5188
- 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);
5189
5282
  function esearchUrl(q) {
5190
5283
  const u = new URL(`${EUTILS}/esearch.fcgi`);
5191
5284
  u.searchParams.set("db", "pubmed");
@@ -5232,14 +5325,14 @@ function levelOf(id, libraryDir) {
5232
5325
  const paths = entryPaths(libraryDir, "pmid", id);
5233
5326
  return entryExists(paths) ? String(readStatus(paths, emptyStatus(`pmid:${id}`, "pmid", id, libraryDir)).level) : null;
5234
5327
  }
5235
- var live = (url) => fetchText(url, { "User-Agent": "evidence-mcp", Accept: "application/json" });
5236
- async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live) {
5237
- 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);
5238
5331
  if ("error" in q) return { ok: false, error: q.error };
5239
- const file3 = searchFile(libraryDir, searchKey2(q));
5240
- if (existsSync12(file3)) {
5332
+ const file3 = searchFile(libraryDir, searchKey3(q));
5333
+ if (existsSync13(file3)) {
5241
5334
  try {
5242
- const r = JSON.parse(readFileSync10(file3, "utf8"));
5335
+ const r = JSON.parse(readFileSync11(file3, "utf8"));
5243
5336
  if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: { ...r, rows: r.rows.map((row3) => {
5244
5337
  const c = [...row3];
5245
5338
  c[7] = levelOf(String(row3[0]), libraryDir);
@@ -5262,9 +5355,9 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
5262
5355
  return { ok: false, error: `pubmed: ${e instanceof Error ? e.message : String(e)}` };
5263
5356
  }
5264
5357
  }
5265
- 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() };
5266
5359
  try {
5267
- mkdirSync9(dirname6(file3), { recursive: true });
5360
+ mkdirSync10(dirname7(file3), { recursive: true });
5268
5361
  writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
5269
5362
  } catch {
5270
5363
  }
@@ -5272,23 +5365,23 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
5272
5365
  }
5273
5366
 
5274
5367
  // src/dailymedsearch.ts
5275
- import { createHash as createHash6 } from "crypto";
5276
- import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync11 } from "fs";
5277
- import { dirname as dirname7 } from "path";
5278
- var MAX_RESULTS3 = 100;
5279
- var DEFAULT_RESULTS3 = 20;
5280
- 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"];
5281
5374
  var API3 = "https://dailymed.nlm.nih.gov/dailymed/services/v2/spls.json";
5282
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" };
5283
- function normalizeQuery3(q) {
5376
+ function normalizeQuery4(q) {
5284
5377
  const drug_name = (q.drug_name ?? "").replace(/\s+/g, " ").trim();
5285
5378
  if (!drug_name) return { error: "empty drug_name" };
5286
5379
  const labeler = (q.labeler ?? "").replace(/\s+/g, " ").trim();
5287
- 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))) };
5288
5381
  if (labeler) out.labeler = labeler;
5289
5382
  return out;
5290
5383
  }
5291
- 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);
5292
5385
  function searchUrl2(q) {
5293
5386
  const u = new URL(API3);
5294
5387
  u.searchParams.set("drug_name", q.drug_name);
@@ -5318,14 +5411,14 @@ function parseSearch(json2, libraryDir) {
5318
5411
  }
5319
5412
  return { total: Number(d.metadata?.total_elements ?? rows.length) || rows.length, rows };
5320
5413
  }
5321
- var live2 = (url) => fetchText(url, { "User-Agent": LIBRARY_UA, Accept: "application/json" });
5322
- async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live2) {
5323
- 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);
5324
5417
  if ("error" in q) return { ok: false, error: q.error };
5325
- const file3 = searchFile(libraryDir, searchKey3(q));
5326
- if (existsSync13(file3)) {
5418
+ const file3 = searchFile(libraryDir, searchKey4(q));
5419
+ if (existsSync14(file3)) {
5327
5420
  try {
5328
- const r = JSON.parse(readFileSync11(file3, "utf8"));
5421
+ const r = JSON.parse(readFileSync12(file3, "utf8"));
5329
5422
  if (daysSince(r.searched) < searchCacheDays()) return { ok: true, result: { ...r, rows: r.rows.map((row3) => {
5330
5423
  const c = [...row3];
5331
5424
  c[5] = levelOf2(row3[0], libraryDir);
@@ -5340,9 +5433,9 @@ async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live2
5340
5433
  } catch (e) {
5341
5434
  return { ok: false, error: `dailymed: ${e instanceof Error ? e.message : String(e)}` };
5342
5435
  }
5343
- 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() };
5344
5437
  try {
5345
- mkdirSync10(dirname7(file3), { recursive: true });
5438
+ mkdirSync11(dirname8(file3), { recursive: true });
5346
5439
  writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
5347
5440
  } catch {
5348
5441
  }
@@ -5466,13 +5559,13 @@ function resultsText(nct, md, maxChars) {
5466
5559
  }
5467
5560
 
5468
5561
  // src/missing.ts
5469
- 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";
5470
5563
  import { join as join12 } from "path";
5471
5564
  var missingFile = (p) => join12(p.entryDir, `${p.entry}-missing.md`);
5472
5565
  function readMissing(p) {
5473
5566
  const f = missingFile(p);
5474
- if (!existsSync14(f)) return null;
5475
- const md = readFileSync12(f, "utf8");
5567
+ if (!existsSync15(f)) return null;
5568
+ const md = readFileSync13(f, "utf8");
5476
5569
  const get4 = (k) => /^$/.test(k) ? "" : (new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md)?.[1] ?? "").trim();
5477
5570
  const checked = get4("checked"), reason = get4("reason");
5478
5571
  return checked ? { checked, reason: reason || "not found" } : null;
@@ -5483,7 +5576,7 @@ function freshMissing(p, retryDays) {
5483
5576
  }
5484
5577
  function rememberMissing(p, reason) {
5485
5578
  const m = { checked: now(), reason };
5486
- mkdirSync11(p.entryDir, { recursive: true });
5579
+ mkdirSync12(p.entryDir, { recursive: true });
5487
5580
  writeAtomic(missingFile(p), `checked: ${m.checked}
5488
5581
  reason: ${m.reason}
5489
5582
  `);
@@ -5493,7 +5586,7 @@ var missingNote = (m, retryDays) => `${m.reason} (checked ${m.checked.slice(0, 1
5493
5586
 
5494
5587
  // src/pubmedbatch.ts
5495
5588
  var MAX_PMIDS = 200;
5496
- var COLUMNS4 = ["pmid", "title", "first_author", "year", "publication_types", "retracted", "level"];
5589
+ var COLUMNS5 = ["pmid", "title", "first_author", "year", "publication_types", "retracted", "level"];
5497
5590
  var EFETCH2 = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi";
5498
5591
  function efetchBatchUrl(pmids) {
5499
5592
  const u = new URL(EFETCH2);
@@ -5517,7 +5610,7 @@ function splitArticles(xml) {
5517
5610
  }
5518
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];
5519
5612
  async function fetchArticles(ids, libraryDir = FH_EVIDENCE_DIR, converter = "evidence-mcp", fetchImpl = fetchText) {
5520
- 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 };
5521
5614
  const order2 = [];
5522
5615
  const invalid = /* @__PURE__ */ new Map();
5523
5616
  for (const raw of ids.slice(0, MAX_PMIDS)) {
@@ -5579,7 +5672,7 @@ async function fetchArticles(ids, libraryDir = FH_EVIDENCE_DIR, converter = "evi
5579
5672
  // src/tools.ts
5580
5673
  var pkg = (() => {
5581
5674
  try {
5582
- 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"));
5583
5676
  } catch {
5584
5677
  return { name: "evidence-mcp", version: "0.0.0" };
5585
5678
  }
@@ -5602,7 +5695,7 @@ Tools
5602
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.
5603
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.
5604
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.
5605
- - 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.
5606
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.
5607
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.
5608
5701
 
@@ -5975,8 +6068,8 @@ function registerTools(server2) {
5975
6068
  }
5976
6069
  added = true;
5977
6070
  }
5978
- const full = existsSync15(paths.fulltextMd);
5979
- 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");
5980
6073
  const text4 = full ? "full_text" : "abstract";
5981
6074
  const base = added ? { requested: parsed.requested, entry: paths.entry, text: text4, added: true } : { requested: parsed.requested, entry: paths.entry, text: text4 };
5982
6075
  const headings2 = () => outline(md, text4).sections;
@@ -5996,8 +6089,8 @@ function registerTools(server2) {
5996
6089
  const cap = max_chars ?? 6e3;
5997
6090
  let sec = readSection(md, section2, cap);
5998
6091
  let via = "";
5999
- if (!sec && /abstract/i.test(section2) && full && existsSync15(paths.md)) {
6000
- 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);
6001
6094
  via = " (from the abstract file)";
6002
6095
  }
6003
6096
  if (!sec && /declaration/i.test(section2)) {
@@ -6126,8 +6219,8 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
6126
6219
  return { content: [{ type: "text", text: `Failed to fetch ${url}: ${added.error}` }], isError: true };
6127
6220
  }
6128
6221
  }
6129
- const file3 = pid.type === "pmid" ? paths.md : existsSync15(paths.fulltextMd) ? paths.fulltextMd : paths.md;
6130
- 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") : "";
6131
6224
  const text4 = title_only ? `Contents of ${url}:
6132
6225
  ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "", max_length, start_index);
6133
6226
  bump("fetch", had);
@@ -6165,10 +6258,10 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6165
6258
  );
6166
6259
  server2.tool(
6167
6260
  "fh_pubmed_search_articles",
6168
- `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.`,
6169
6262
  {
6170
6263
  query: z.string().describe('PubMed query, full syntax: "tadalafil AND (systematic review[pt] OR meta-analysis[pt])".'),
6171
- 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)."),
6172
6265
  sort: z.enum(["relevance", "newest"]).default("relevance").describe("relevance (PubMed's ranking) or newest (publication date, latest first)."),
6173
6266
  years: z.string().optional().describe('Publication years: "2020-2026", "2022-", "-2019" or "2022".')
6174
6267
  },
@@ -6211,13 +6304,34 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6211
6304
  return { content: [{ type: "text", text: searchAnswer(r.result) }] };
6212
6305
  }
6213
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
+ );
6214
6328
  server2.tool(
6215
6329
  "fh_dailymed_search_labels",
6216
- `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.`,
6217
6331
  {
6218
6332
  drug_name: z.string().describe('Generic or brand name: "telmisartan", "Micardis".'),
6219
6333
  labeler: z.string().optional().describe(`Part of the company's name, to narrow to its labels: "Boehringer".`),
6220
- 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).")
6221
6335
  },
6222
6336
  async (args) => {
6223
6337
  const t0 = Date.now();
@@ -6258,7 +6372,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6258
6372
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
6259
6373
  }
6260
6374
  const raw = e.paths.fulltextRaw("json");
6261
- const r = existsSync15(raw) ? recordSummary(readFileSync13(raw, "utf8")) : null;
6375
+ const r = existsSync16(raw) ? recordSummary(readFileSync14(raw, "utf8")) : null;
6262
6376
  if (!r) {
6263
6377
  log("trials", e.requested, "record error: no stored record");
6264
6378
  return { content: [{ type: "text", text: compact2({ error: "no stored record" }) }], isError: true };
@@ -6277,7 +6391,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
6277
6391
  log("trials", nct, `results error: ${e.error}`);
6278
6392
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
6279
6393
  }
6280
- const md = existsSync15(e.paths.fulltextMd) ? readFileSync13(e.paths.fulltextMd, "utf8") : "";
6394
+ const md = existsSync16(e.paths.fulltextMd) ? readFileSync14(e.paths.fulltextMd, "utf8") : "";
6281
6395
  const r = resultsText(e.requested.replace(/^nct:/, "NCT"), md, max_chars);
6282
6396
  log("trials", e.requested, `results ${r.has_results ? `${r.outcomes.length} outcomes${r.truncated ? " truncated" : ""}` : "none"}`);
6283
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.6",
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": {