evidence-mcp-dev 1.0.10 → 1.0.12
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.
- package/dist/index.js +149 -61
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2749,11 +2749,11 @@ async function download(tier, p, candidates, ctx) {
|
|
|
2749
2749
|
const isGone = (x) => x.ok ? null : x.reason.match(/\bHTTP (404|410)\b/)?.[0] ?? null;
|
|
2750
2750
|
const one = await firstOk(first, isGone);
|
|
2751
2751
|
if (one.won) return one.won;
|
|
2752
|
-
const
|
|
2753
|
-
const target = !
|
|
2752
|
+
const plain4 = one.results[0] ?? one.results.find(Boolean);
|
|
2753
|
+
const target = !plain4.ok && plain4.url && plain4.url !== c.url ? { ...c, url: plain4.url } : c;
|
|
2754
2754
|
if (target !== c) ctx.onTry?.(`redirect ${c.url} \u2192 ${target.url}`);
|
|
2755
|
-
const plainReason = why(reasonOf(
|
|
2756
|
-
let r = one.results[1] ??
|
|
2755
|
+
const plainReason = why(reasonOf(plain4));
|
|
2756
|
+
let r = one.results[1] ?? plain4;
|
|
2757
2757
|
const UNLOCK = /^(HTTP 403|wall page)/;
|
|
2758
2758
|
let browsed = false;
|
|
2759
2759
|
if (!gone && !c.headers && !c.service && (climbsOn(plainReason) || climbsOn(bare(reasonOf(r))))) {
|
|
@@ -3246,8 +3246,11 @@ var VARIABLES = [
|
|
|
3246
3246
|
"FH_REFRESH_AFTER_DAYS",
|
|
3247
3247
|
"FH_SEARCH_CACHE_DAYS",
|
|
3248
3248
|
"FH_NCBI_API_KEY",
|
|
3249
|
-
"
|
|
3249
|
+
"FH_WEB_SEARCH_EXA_API_KEY",
|
|
3250
|
+
"FH_WEB_SEARCH_SERPER_API_KEY",
|
|
3251
|
+
"FH_WEB_SEARCH_BRAVE_API_KEY",
|
|
3250
3252
|
"FH_WEB_SEARCH_SNIPPETS",
|
|
3253
|
+
"FH_WEB_SEARCH_TIMEOUT_SECS",
|
|
3251
3254
|
"FH_ZENROWS_API_KEY",
|
|
3252
3255
|
"FH_ZYTE_API_KEY",
|
|
3253
3256
|
"FH_BRIGHTDATA_API_KEY",
|
|
@@ -3427,8 +3430,8 @@ function resolve3(env) {
|
|
|
3427
3430
|
const field2 = (p, f) => {
|
|
3428
3431
|
const own = p ? `FH_VERIFY_${p.name.toUpperCase()}_${f}` : "";
|
|
3429
3432
|
if (own && str(own, env)) return [str(own, env), own];
|
|
3430
|
-
const
|
|
3431
|
-
return [
|
|
3433
|
+
const plain4 = str(`FH_VERIFY_${f}`, env);
|
|
3434
|
+
return [plain4, plain4 || !own ? `FH_VERIFY_${f}` : own];
|
|
3432
3435
|
};
|
|
3433
3436
|
const filled = (p) => !!(str(`FH_VERIFY_${p.name.toUpperCase()}_URL`, env) || str(`FH_VERIFY_${p.name.toUpperCase()}_API_KEY`, env));
|
|
3434
3437
|
const name = str("FH_VERIFY_PROVIDER", env).toLowerCase();
|
|
@@ -3825,7 +3828,7 @@ function parseRows(json2) {
|
|
|
3825
3828
|
var liveFetch = (url) => fetchText(url, { "User-Agent": LIBRARY_UA, Accept: "application/json" });
|
|
3826
3829
|
async function searchTrials(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liveFetch) {
|
|
3827
3830
|
const q = normalizeQuery(raw);
|
|
3828
|
-
if ("error" in q) return { ok: false, error: q.error };
|
|
3831
|
+
if ("error" in q) return { ok: false, error: q.error, input: true };
|
|
3829
3832
|
const file3 = searchFile(libraryDir, searchKey(q));
|
|
3830
3833
|
if (existsSync7(file3)) {
|
|
3831
3834
|
try {
|
|
@@ -3856,25 +3859,26 @@ async function searchTrials(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liveF
|
|
|
3856
3859
|
}
|
|
3857
3860
|
|
|
3858
3861
|
// src/websearch.ts
|
|
3859
|
-
var MAX_RESULTS2 = 25;
|
|
3860
|
-
var DEFAULT_RESULTS2 = 10;
|
|
3861
3862
|
var COLUMNS2 = ["title", "url", "published", "author", "snippet"];
|
|
3862
|
-
var
|
|
3863
|
-
const v = (env.FH_WEB_SEARCH_SNIPPETS ?? "").trim().toLowerCase();
|
|
3864
|
-
return v === "summary" || v === "off" ? v : "highlights";
|
|
3865
|
-
};
|
|
3863
|
+
var snippetsOn = (env = process.env) => !/^(off|false|no|0)$/i.test((env.FH_WEB_SEARCH_SNIPPETS ?? "").trim());
|
|
3866
3864
|
var SNIPPET_CHARS = 220;
|
|
3867
3865
|
function cleanSnippet(t) {
|
|
3868
3866
|
let s = (t ?? "").replace(/\s+/g, " ").trim();
|
|
3869
3867
|
s = s.replace(/^(?:[#•*\-\s]*(?:last updated|updated|published|written by|reviewed by|by)\b[^.]*?(?:\d{4}|others)\s*)+/i, "").trim();
|
|
3870
|
-
s = s.replace(/^#+\s*/, "");
|
|
3868
|
+
s = s.replace(/^#+\s*/, "").replace(/^[·•\s]*(?:Cited by \d+|\d+ (?:days?|hours?) ago|[A-Z][a-z]{2} \d{1,2}, \d{4})\s*[—–-]\s*/i, "");
|
|
3871
3869
|
if (!s) return null;
|
|
3872
3870
|
if (s.length <= SNIPPET_CHARS) return s;
|
|
3873
3871
|
const cut = s.slice(0, SNIPPET_CHARS);
|
|
3874
3872
|
return cut.slice(0, Math.max(cut.lastIndexOf(" "), SNIPPET_CHARS - 40)).replace(/[,;:\s]+$/, "") + " \u2026";
|
|
3875
3873
|
}
|
|
3876
|
-
var
|
|
3877
|
-
|
|
3874
|
+
var SEARCH_PROVIDERS = ["exa", "serper", "brave"];
|
|
3875
|
+
function webSearchConfig(env = process.env) {
|
|
3876
|
+
return SEARCH_PROVIDERS.flatMap((provider) => {
|
|
3877
|
+
const key2 = env[`FH_WEB_SEARCH_${provider.toUpperCase()}_API_KEY`]?.trim();
|
|
3878
|
+
return key2 ? [{ provider, key: key2 }] : [];
|
|
3879
|
+
});
|
|
3880
|
+
}
|
|
3881
|
+
var webSearchConfigured = (env = process.env) => webSearchConfig(env).length > 0;
|
|
3878
3882
|
function siteDomain(site) {
|
|
3879
3883
|
const s = site.trim().toLowerCase().replace(/^site:/, "");
|
|
3880
3884
|
if (!s) return null;
|
|
@@ -3896,11 +3900,22 @@ function normalizeQuery2(q) {
|
|
|
3896
3900
|
query = query.replace(/site:[^\s()]+/gi, " ").replace(/\(\s*(?:OR\s*)*\)/gi, " ").replace(/(?:^|\s)OR(?=\s*(?:$|\)))/g, " ").replace(/(?:^|\s)OR\s+(?=OR\b)/g, " ").replace(/\s+/g, " ").trim().replace(/^OR\s+|\s+OR$/g, "");
|
|
3897
3901
|
}
|
|
3898
3902
|
if (!query) return { error: "empty query" };
|
|
3899
|
-
const out = { query
|
|
3903
|
+
const out = { query };
|
|
3904
|
+
if (q.max_results && q.max_results >= 1) out.max_results = Math.floor(q.max_results);
|
|
3900
3905
|
if (sites.length) out.sites = sites;
|
|
3901
3906
|
return out;
|
|
3902
3907
|
}
|
|
3903
|
-
var searchKey2 = (q,
|
|
3908
|
+
var searchKey2 = (q, provider = "exa", snippets = snippetsOn()) => createHash3("sha1").update(JSON.stringify(["web", provider, snippets ? "snippets" : "links", q.query.toLowerCase(), q.sites ?? []])).digest("hex").slice(0, 16);
|
|
3909
|
+
function isoDay(d) {
|
|
3910
|
+
const t = String(d ?? "").trim();
|
|
3911
|
+
if (!t || /\bago\b/i.test(t)) return null;
|
|
3912
|
+
if (/^\d{4}-\d\d-\d\d/.test(t)) return t.slice(0, 10);
|
|
3913
|
+
const day2 = new Date(t);
|
|
3914
|
+
return Number.isFinite(day2.getTime()) ? `${day2.getFullYear()}-${String(day2.getMonth() + 1).padStart(2, "0")}-${String(day2.getDate()).padStart(2, "0")}` : null;
|
|
3915
|
+
}
|
|
3916
|
+
var stripTracking = (u) => u.replace(/([?&])srsltid=[^&]*&?/, "$1").replace(/[?&]$/, "");
|
|
3917
|
+
var plain3 = (t) => (t ?? "").replace(/<[^>]+>/g, "").replace(/&/g, "&").replace(/"/g, '"').replace(/'|'/g, "'").replace(/</g, "<").replace(/>/g, ">");
|
|
3918
|
+
var withSites = (q) => !q.sites ? q.query : q.sites.length === 1 ? `${q.query} site:${q.sites[0]}` : `${q.query} (${q.sites.map((d) => `site:${d}`).join(" OR ")})`;
|
|
3904
3919
|
function parseExa(json2) {
|
|
3905
3920
|
const d = JSON.parse(json2);
|
|
3906
3921
|
return (d.results ?? []).filter((x) => x.url).map((x) => [
|
|
@@ -3908,16 +3923,35 @@ function parseExa(json2) {
|
|
|
3908
3923
|
x.url,
|
|
3909
3924
|
x.publishedDate ? x.publishedDate.slice(0, 10) : null,
|
|
3910
3925
|
x.author ? x.author.replace(/\s+/g, " ").trim() : null,
|
|
3911
|
-
cleanSnippet(x.
|
|
3926
|
+
cleanSnippet(x.highlights?.[0])
|
|
3912
3927
|
]);
|
|
3913
3928
|
}
|
|
3929
|
+
function parseSerper(json2) {
|
|
3930
|
+
const d = JSON.parse(json2);
|
|
3931
|
+
return (d.organic ?? []).filter((x) => x.link).map((x) => [plain3(x.title).replace(/\s+/g, " ").trim(), stripTracking(x.link), isoDay(x.date), null, cleanSnippet(plain3(x.snippet))]);
|
|
3932
|
+
}
|
|
3933
|
+
function parseBrave(json2) {
|
|
3934
|
+
const d = JSON.parse(json2);
|
|
3935
|
+
return (d.web?.results ?? []).filter((x) => x.url).map((x) => [plain3(x.title).replace(/\s+/g, " ").trim(), x.url, isoDay(x.page_age ?? x.age), null, cleanSnippet(plain3(x.description))]);
|
|
3936
|
+
}
|
|
3937
|
+
var searchTimeoutSecs = (env = process.env) => {
|
|
3938
|
+
const n = Number(env.FH_WEB_SEARCH_TIMEOUT_SECS);
|
|
3939
|
+
return Number.isFinite(n) && n > 0 ? n : 10;
|
|
3940
|
+
};
|
|
3914
3941
|
var live = async (url, body, headers) => {
|
|
3915
|
-
const
|
|
3942
|
+
const signal = AbortSignal.timeout(searchTimeoutSecs() * 1e3);
|
|
3943
|
+
let r;
|
|
3944
|
+
try {
|
|
3945
|
+
r = await fetch(url, body === void 0 ? { headers: { accept: "application/json", ...headers }, signal } : { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), signal });
|
|
3946
|
+
} catch (e) {
|
|
3947
|
+
throw signal.aborted ? new Error(`timeout ${searchTimeoutSecs()}s`) : e;
|
|
3948
|
+
}
|
|
3916
3949
|
const text4 = await r.text();
|
|
3917
3950
|
if (!r.ok) {
|
|
3918
3951
|
let why = "";
|
|
3919
3952
|
try {
|
|
3920
|
-
|
|
3953
|
+
const j = JSON.parse(text4);
|
|
3954
|
+
why = (typeof j.error === "string" ? j.error : j.error?.detail) ?? j.message ?? "";
|
|
3921
3955
|
} catch {
|
|
3922
3956
|
why = text4.slice(0, 120);
|
|
3923
3957
|
}
|
|
@@ -3925,33 +3959,86 @@ var live = async (url, body, headers) => {
|
|
|
3925
3959
|
}
|
|
3926
3960
|
return text4;
|
|
3927
3961
|
};
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3962
|
+
var SEARCH = {
|
|
3963
|
+
exa: async (q, key2, post2) => parseExa(await post2("https://api.exa.ai/search", {
|
|
3964
|
+
query: q.query,
|
|
3965
|
+
...q.sites ? { includeDomains: q.sites } : {},
|
|
3966
|
+
...snippetsOn() ? { contents: { highlights: { query: q.query, numSentences: 2, highlightsPerUrl: 1 } } } : {}
|
|
3967
|
+
}, { "x-api-key": key2 })),
|
|
3968
|
+
serper: async (q, key2, post2) => parseSerper(await post2("https://google.serper.dev/search", { q: withSites(q) }, { "X-API-KEY": key2 })),
|
|
3969
|
+
brave: async (q, key2, post2) => parseBrave(await post2(`https://api.search.brave.com/res/v1/web/search?${new URLSearchParams({ q: withSites(q) })}`, void 0, { "X-Subscription-Token": key2 }))
|
|
3970
|
+
};
|
|
3971
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
3972
|
+
function oneProvider(q, cfg, libraryDir, post2, onEvent) {
|
|
3973
|
+
const file3 = searchFile(libraryDir, searchKey2(q, cfg.provider));
|
|
3974
|
+
const running = inFlight.get(file3);
|
|
3975
|
+
if (running) return running;
|
|
3976
|
+
const p = askProvider(q, cfg, libraryDir, post2, onEvent).finally(() => inFlight.delete(file3));
|
|
3977
|
+
inFlight.set(file3, p);
|
|
3978
|
+
return p;
|
|
3979
|
+
}
|
|
3980
|
+
async function askProvider(q, cfg, libraryDir, post2, onEvent) {
|
|
3981
|
+
const file3 = searchFile(libraryDir, searchKey2(q, cfg.provider));
|
|
3933
3982
|
if (existsSync8(file3)) {
|
|
3934
3983
|
try {
|
|
3935
3984
|
const r = JSON.parse(readFileSync6(file3, "utf8"));
|
|
3936
|
-
if (daysSince(r.searched) < searchCacheDays()) return {
|
|
3985
|
+
if (daysSince(r.searched) < searchCacheDays()) return { rows: r.rows, cached: true };
|
|
3937
3986
|
} catch {
|
|
3938
3987
|
}
|
|
3939
3988
|
}
|
|
3989
|
+
onEvent?.(`try ${cfg.provider}`);
|
|
3990
|
+
const t0 = Date.now();
|
|
3940
3991
|
let rows;
|
|
3941
3992
|
try {
|
|
3942
|
-
|
|
3943
|
-
const contents = mode === "highlights" ? { highlights: { query: q.query, numSentences: 2, highlightsPerUrl: 1 } } : mode === "summary" ? { summary: { query: `In one sentence, what does this page say about ${q.query}?` } } : void 0;
|
|
3944
|
-
rows = parseExa(await post2("https://api.exa.ai/search", { query: q.query, numResults: q.max_results, ...q.sites ? { includeDomains: q.sites } : {}, ...contents ? { contents } : {} }, { "x-api-key": key2 }));
|
|
3993
|
+
rows = (await SEARCH[cfg.provider](q, cfg.key, post2)).filter((r) => !q.sites || q.sites.some((d) => siteDomain(r[1])?.endsWith(d)));
|
|
3945
3994
|
} catch (e) {
|
|
3946
|
-
|
|
3995
|
+
onEvent?.(`failed ${cfg.provider}: ${e instanceof Error ? e.message : String(e)}`);
|
|
3996
|
+
throw e;
|
|
3947
3997
|
}
|
|
3948
|
-
|
|
3998
|
+
onEvent?.(`ok ${cfg.provider} ${((Date.now() - t0) / 1e3).toFixed(1)}s rows=${rows.length}`);
|
|
3999
|
+
const result = { source: cfg.provider, query: q, total: rows.length, columns: COLUMNS2, rows, searched: today() };
|
|
3949
4000
|
try {
|
|
3950
4001
|
mkdirSync7(dirname4(file3), { recursive: true });
|
|
3951
4002
|
writeAtomic(file3, JSON.stringify(result, null, 2) + "\n");
|
|
3952
4003
|
} catch {
|
|
3953
4004
|
}
|
|
3954
|
-
return {
|
|
4005
|
+
return { rows, cached: false };
|
|
4006
|
+
}
|
|
4007
|
+
var pageKey = (u) => u.replace(/^https?:\/\/(www\.)?/i, "").replace(/[?#].*$/, "").replace(/\/+$/, "").toLowerCase();
|
|
4008
|
+
function mergeRows(lists) {
|
|
4009
|
+
const pages = /* @__PURE__ */ new Map();
|
|
4010
|
+
for (const rows of lists) rows.forEach((r, i) => {
|
|
4011
|
+
const k = pageKey(r[1]);
|
|
4012
|
+
const p = pages.get(k);
|
|
4013
|
+
if (!p) {
|
|
4014
|
+
pages.set(k, { row: [...r], hits: 1, best: i });
|
|
4015
|
+
return;
|
|
4016
|
+
}
|
|
4017
|
+
p.hits++;
|
|
4018
|
+
p.best = Math.min(p.best, i);
|
|
4019
|
+
for (const f of [2, 3, 4]) p.row[f] ??= r[f];
|
|
4020
|
+
});
|
|
4021
|
+
return [...pages.values()].sort((a, b) => b.hits - a.hits || a.best - b.best).map((p) => p.row);
|
|
4022
|
+
}
|
|
4023
|
+
async function webSearch(raw, libraryDir = FH_EVIDENCE_DIR, post2 = live, cfgs = webSearchConfig(), onEvent) {
|
|
4024
|
+
if (!cfgs.length) return { ok: false, error: "web search not configured" };
|
|
4025
|
+
const q = normalizeQuery2(raw);
|
|
4026
|
+
if ("error" in q) return { ok: false, error: q.error, input: true };
|
|
4027
|
+
const answers = await Promise.allSettled(cfgs.map((c) => oneProvider(q, c, libraryDir, post2, onEvent)));
|
|
4028
|
+
const providers = {};
|
|
4029
|
+
const lists = [];
|
|
4030
|
+
let allCached = true;
|
|
4031
|
+
answers.forEach((a, i) => {
|
|
4032
|
+
const name = cfgs[i].provider;
|
|
4033
|
+
if (a.status === "fulfilled") {
|
|
4034
|
+
providers[name] = a.value.rows.length;
|
|
4035
|
+
lists.push(a.value.rows);
|
|
4036
|
+
allCached &&= a.value.cached;
|
|
4037
|
+
} else providers[name] = a.reason instanceof Error ? a.reason.message : String(a.reason);
|
|
4038
|
+
});
|
|
4039
|
+
if (!lists.length) return { ok: false, error: Object.entries(providers).map(([n, e]) => `${n}: ${e}`).join("; ") };
|
|
4040
|
+
const all = mergeRows(lists);
|
|
4041
|
+
return { ok: true, result: { total: all.length, columns: COLUMNS2, rows: all.slice(0, q.max_results), providers, query: q }, cached: allCached };
|
|
3955
4042
|
}
|
|
3956
4043
|
|
|
3957
4044
|
// src/info.ts
|
|
@@ -3986,7 +4073,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
|
3986
4073
|
config: { ...settings(), problems: [...tiers.problems, ...verifyProblems()], sources: sources() },
|
|
3987
4074
|
download: downloadInfo(),
|
|
3988
4075
|
verify: verifyInfo(),
|
|
3989
|
-
web_search:
|
|
4076
|
+
web_search: webSearchConfig().map((c) => c.provider),
|
|
3990
4077
|
unlockers: unlockers().map((provider) => ({ provider })),
|
|
3991
4078
|
stages: ownStages(),
|
|
3992
4079
|
entries: 0,
|
|
@@ -4762,10 +4849,10 @@ var climb = async (given, onTry, onAlert) => {
|
|
|
4762
4849
|
const isGone = (g) => g.ok ? null : goneReason(g.reason) ?? null;
|
|
4763
4850
|
const one = await firstOk(first, isGone);
|
|
4764
4851
|
if (one.won) return one.won;
|
|
4765
|
-
const
|
|
4766
|
-
const firstReason =
|
|
4767
|
-
const target = !
|
|
4768
|
-
let r = one.results[1] ??
|
|
4852
|
+
const plain4 = one.results[0] ?? one.results.find(Boolean);
|
|
4853
|
+
const firstReason = plain4.ok ? void 0 : plain4.reason;
|
|
4854
|
+
const target = !plain4.ok && plain4.url && plain4.url !== url ? plain4.url : url;
|
|
4855
|
+
let r = one.results[1] ?? plain4;
|
|
4769
4856
|
const plainVia = (g) => g.via === "fetch" || g.via.startsWith("fetch-proxy ");
|
|
4770
4857
|
const met = (g, re) => re.test(g.ok ? "" : g.reason) || plainVia(g) && re.test(firstReason ?? "");
|
|
4771
4858
|
const escalates = (g) => !g.ok && (!plainVia(g) || met(g, /^(HTTP 403|HTTP 429|wall page|script shell)/));
|
|
@@ -5267,8 +5354,8 @@ var reviewTypes = (types) => types.filter((t) => t !== "Journal Article" && !/^R
|
|
|
5267
5354
|
import { createHash as createHash6 } from "crypto";
|
|
5268
5355
|
import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync11 } from "fs";
|
|
5269
5356
|
import { dirname as dirname7 } from "path";
|
|
5270
|
-
var
|
|
5271
|
-
var
|
|
5357
|
+
var MAX_RESULTS2 = 100;
|
|
5358
|
+
var DEFAULT_RESULTS2 = 20;
|
|
5272
5359
|
var COLUMNS3 = ["pmid", "title", "first_author", "year", "journal", "publication_types", "pmcid", "level"];
|
|
5273
5360
|
var EUTILS = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils";
|
|
5274
5361
|
var ident = (u) => {
|
|
@@ -5292,7 +5379,7 @@ function normalizeQuery3(q) {
|
|
|
5292
5379
|
if (!["relevance", "newest"].includes(sort)) return { error: `sort must be relevance or newest, not "${String(q.sort)}"` };
|
|
5293
5380
|
const yr = yearRange(q.years);
|
|
5294
5381
|
if (yr && "error" in yr) return yr;
|
|
5295
|
-
const out = { query, sort, max_results: Math.min(
|
|
5382
|
+
const out = { query, sort, max_results: Math.min(MAX_RESULTS2, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS2))) };
|
|
5296
5383
|
if (yr) out.years = `${yr.min === "1000" ? "" : yr.min}-${yr.max}`;
|
|
5297
5384
|
return out;
|
|
5298
5385
|
}
|
|
@@ -5346,7 +5433,7 @@ function levelOf(id, libraryDir) {
|
|
|
5346
5433
|
var live2 = (url) => fetchText(url, { "User-Agent": "evidence-mcp", Accept: "application/json" });
|
|
5347
5434
|
async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live2) {
|
|
5348
5435
|
const q = normalizeQuery3(raw);
|
|
5349
|
-
if ("error" in q) return { ok: false, error: q.error };
|
|
5436
|
+
if ("error" in q) return { ok: false, error: q.error, input: true };
|
|
5350
5437
|
const file3 = searchFile(libraryDir, searchKey3(q));
|
|
5351
5438
|
if (existsSync13(file3)) {
|
|
5352
5439
|
try {
|
|
@@ -5386,8 +5473,8 @@ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = liv
|
|
|
5386
5473
|
import { createHash as createHash7 } from "crypto";
|
|
5387
5474
|
import { existsSync as existsSync14, mkdirSync as mkdirSync11, readFileSync as readFileSync12 } from "fs";
|
|
5388
5475
|
import { dirname as dirname8 } from "path";
|
|
5389
|
-
var
|
|
5390
|
-
var
|
|
5476
|
+
var MAX_RESULTS3 = 100;
|
|
5477
|
+
var DEFAULT_RESULTS3 = 20;
|
|
5391
5478
|
var COLUMNS4 = ["set_id", "title", "labeler", "published", "version", "level"];
|
|
5392
5479
|
var API3 = "https://dailymed.nlm.nih.gov/dailymed/services/v2/spls.json";
|
|
5393
5480
|
var MONTHS2 = { Jan: "01", Feb: "02", Mar: "03", Apr: "04", May: "05", Jun: "06", Jul: "07", Aug: "08", Sep: "09", Oct: "10", Nov: "11", Dec: "12" };
|
|
@@ -5395,7 +5482,7 @@ function normalizeQuery4(q) {
|
|
|
5395
5482
|
const drug_name = (q.drug_name ?? "").replace(/\s+/g, " ").trim();
|
|
5396
5483
|
if (!drug_name) return { error: "empty drug_name" };
|
|
5397
5484
|
const labeler = (q.labeler ?? "").replace(/\s+/g, " ").trim();
|
|
5398
|
-
const out = { drug_name, max_results: Math.min(
|
|
5485
|
+
const out = { drug_name, max_results: Math.min(MAX_RESULTS3, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS3))) };
|
|
5399
5486
|
if (labeler) out.labeler = labeler;
|
|
5400
5487
|
return out;
|
|
5401
5488
|
}
|
|
@@ -5432,7 +5519,7 @@ function parseSearch(json2, libraryDir) {
|
|
|
5432
5519
|
var live3 = (url) => fetchText(url, { "User-Agent": LIBRARY_UA, Accept: "application/json" });
|
|
5433
5520
|
async function searchLabels(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live3) {
|
|
5434
5521
|
const q = normalizeQuery4(raw);
|
|
5435
|
-
if ("error" in q) return { ok: false, error: q.error };
|
|
5522
|
+
if ("error" in q) return { ok: false, error: q.error, input: true };
|
|
5436
5523
|
const file3 = searchFile(libraryDir, searchKey4(q));
|
|
5437
5524
|
if (existsSync14(file3)) {
|
|
5438
5525
|
try {
|
|
@@ -5713,7 +5800,7 @@ Tools
|
|
|
5713
5800
|
- fh_pubmed_search_articles(query, max_results?, sort?, years?) \u2014 search PubMed in its own syntax: the total and rows in columns order (PMID, title, first author, year, journal, publication types, PMCID, library level); faster and far smaller than asking PubMed. Cached a week.
|
|
5714
5801
|
- fh_clinicaltrials_search_studies(query | intervention | condition, status?, sort?, max_results?) \u2014 search ClinicalTrials.gov: the total and rows in columns order (NCT ID, title, status, phase, enrollment, dates, primary outcome, conditions, interventions, has_results). Cached a week.
|
|
5715
5802
|
- fh_dailymed_search_labels(drug_name, labeler?, max_results?) \u2014 find FDA drug labels by generic or brand name: the total and rows in columns order (set ID, title, labeler, published, version, level), newest first; labeler narrows to one company. Use it rather than DailyMed's search page, which shows no set IDs as Markdown. Cached a week.
|
|
5716
|
-
${webSearchConfigured() ? "- fh_web_search(query, max_results?) \u2014 search the web; use it instead of the built-in web search. Links (title, URL, date, author) with a short passage from each page, not the page text, so a fraction of the context; read a result with fh_fetch_url. site: in the query restricts it to a site, as with any search engine. Cached locally for a week.\n" : ""}- fh_clinicaltrials_get_study_record(nct) \u2014 one trial as a review needs it (status, design, enrollment, dates, outcomes, eligibility, result publications, summary), from the stored record; added first when missing.
|
|
5803
|
+
${webSearchConfigured() ? "- fh_web_search(query, max_results?) \u2014 search the web; use it instead of the built-in web search. Links (title, URL, date, author) with a short passage from each page, not the page text, so a fraction of the context; read a result with fh_fetch_url. site: in the query restricts it to a site, as with any search engine. For more results, search again with other words. Cached locally for a week.\n" : ""}- fh_clinicaltrials_get_study_record(nct) \u2014 one trial as a review needs it (status, design, enrollment, dates, outcomes, eligibility, result publications, summary), from the stored record; added first when missing.
|
|
5717
5804
|
- fh_clinicaltrials_get_study_results(nct, max_chars?) \u2014 a trial's posted results as Markdown, capped; the outcome titles listed for fh_library_read.
|
|
5718
5805
|
- fh_fetch_url(url, max_length?, start_index?, raw?, title_only?) \u2014 a web page as Markdown, same call and same answer as the standard fetch tool ("Contents of <url>:" and the page, cut at max_length with a note on how to continue). Prefer it for every URL: a cached page answers from disk, a walled or script-rendered page runs through the browser and unlocker stages in one call. PDFs as Markdown; XML, JSON and other text as is. title_only returns the title line alone \u2014 enough to verify a link, at a few tokens.
|
|
5719
5806
|
|
|
@@ -6276,10 +6363,10 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
|
|
|
6276
6363
|
);
|
|
6277
6364
|
server2.tool(
|
|
6278
6365
|
"fh_pubmed_search_articles",
|
|
6279
|
-
`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 ${
|
|
6366
|
+
`Search PubMed with its own query syntax (AND / OR, field tags like [pt], [ti], [mesh]); sort relevance | newest; years "2020-2026". Faster and far smaller than asking PubMed: the total and up to ${MAX_RESULTS2} rows as arrays in columns order \u2014 PMID, title, first author, year, journal, publication types, PMCID when free full text exists, and the library level when the paper is already stored. The same search is answered from disk for ${searchCacheDays()} days. For a batch of PMIDs: fh_pubmed_fetch_articles; for abstract or full text: fh_library_read.`,
|
|
6280
6367
|
{
|
|
6281
6368
|
query: z.string().describe('PubMed query, full syntax: "tadalafil AND (systematic review[pt] OR meta-analysis[pt])".'),
|
|
6282
|
-
max_results: z.number().int().min(1).max(
|
|
6369
|
+
max_results: z.number().int().min(1).max(MAX_RESULTS2).default(20).describe("Rows to return (1\u2013100)."),
|
|
6283
6370
|
sort: z.enum(["relevance", "newest"]).default("relevance").describe("relevance (PubMed's ranking) or newest (publication date, latest first)."),
|
|
6284
6371
|
years: z.string().optional().describe('Publication years: "2020-2026", "2022-", "-2019" or "2022".')
|
|
6285
6372
|
},
|
|
@@ -6288,7 +6375,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
|
|
|
6288
6375
|
const r = await searchArticles(args, FH_EVIDENCE_DIR);
|
|
6289
6376
|
const secs = ((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0") + "s";
|
|
6290
6377
|
if (!r.ok) {
|
|
6291
|
-
log("search", "pubmed",
|
|
6378
|
+
log("search", "pubmed", `${r.input ? "error" : `failed ${secs}`} ${r.error} | ${args.query}`);
|
|
6292
6379
|
return { content: [{ type: "text", text: compact2({ error: r.error }) }], isError: true };
|
|
6293
6380
|
}
|
|
6294
6381
|
bump("search", r.cached);
|
|
@@ -6313,7 +6400,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
|
|
|
6313
6400
|
const r = await searchTrials(args, FH_EVIDENCE_DIR);
|
|
6314
6401
|
const secs = ((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0") + "s";
|
|
6315
6402
|
if (!r.ok) {
|
|
6316
|
-
log("search", "nct",
|
|
6403
|
+
log("search", "nct", `${r.input ? "error" : `failed ${secs}`} ${r.error}${((t) => t ? ` | ${t}` : "")([args.query, args.intervention, args.condition].map((v) => v?.trim()).filter(Boolean).join(" "))}`);
|
|
6317
6404
|
return { content: [{ type: "text", text: compact2({ error: r.error }) }], isError: true };
|
|
6318
6405
|
}
|
|
6319
6406
|
bump("search", r.cached);
|
|
@@ -6324,39 +6411,40 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
|
|
|
6324
6411
|
);
|
|
6325
6412
|
if (webSearchConfigured()) server2.tool(
|
|
6326
6413
|
"fh_web_search",
|
|
6327
|
-
`Search the web \u2014 use it instead of the built-in web search. It returns links (title, URL, date, author) with a short passage from each page, not the page text, so it costs a fraction of the context; read a result with fh_fetch_url. It finds more, especially within one site: restrict it with site: in the query, as with any search engine ("metformin site:nih.gov", several with "(site:nih.gov OR site:who.int)"), a restriction the built-in search often ignores. Searches are cached locally for ${searchCacheDays()} days; a repeated search is answered in milliseconds.`,
|
|
6414
|
+
`Search the web \u2014 use it instead of the built-in web search. It returns links (title, URL, date, author) with a short passage from each page, not the page text, so it costs a fraction of the context; read a result with fh_fetch_url. It finds more, especially within one site: restrict it with site: in the query, as with any search engine ("metformin site:nih.gov", several with "(site:nih.gov OR site:who.int)"), a restriction the built-in search often ignores. Each search returns all it finds; for more, search again with other words. Searches are cached locally for ${searchCacheDays()} days; a repeated search is answered in milliseconds.`,
|
|
6328
6415
|
{
|
|
6329
6416
|
query: z.string().describe('The query, site: terms included: "metformin site:nih.gov", "statin muscle pain".'),
|
|
6330
|
-
max_results: z.number().int().min(1).
|
|
6417
|
+
max_results: z.number().int().min(1).optional().describe("At most this many rows; unset: all the search finds.")
|
|
6331
6418
|
},
|
|
6332
6419
|
async (args) => {
|
|
6333
6420
|
const t0 = Date.now();
|
|
6334
|
-
const r = await webSearch(args, FH_EVIDENCE_DIR);
|
|
6421
|
+
const r = await webSearch(args, FH_EVIDENCE_DIR, void 0, void 0, (line) => log("search", "web", `${line} | ${args.query}`));
|
|
6335
6422
|
const secs = ((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0") + "s";
|
|
6336
6423
|
if (!r.ok) {
|
|
6337
|
-
log("search", "web",
|
|
6424
|
+
log("search", "web", `${r.input ? "error" : `failed ${secs}`} ${r.error} | ${args.query}`);
|
|
6338
6425
|
return { content: [{ type: "text", text: compact2({ error: r.error }) }], isError: true };
|
|
6339
6426
|
}
|
|
6340
6427
|
bump("search", r.cached);
|
|
6341
6428
|
const q = r.result.query;
|
|
6342
|
-
|
|
6343
|
-
|
|
6429
|
+
const per = Object.entries(r.result.providers).map(([n, v]) => `${n}=${typeof v === "number" ? v : "failed"}`).join(" ");
|
|
6430
|
+
log("search", "web", `ok ${r.cached ? "cached" : secs} rows=${r.result.rows.length}${r.result.rows.length < r.result.total ? ` of ${r.result.total}` : ""} ${per} | ${q.query}${q.sites ? " " + q.sites.map((d) => `site:${d}`).join(" ") : ""}`);
|
|
6431
|
+
return { content: [{ type: "text", text: searchAnswer({ total: r.result.total, columns: r.result.columns, rows: r.result.rows }) }] };
|
|
6344
6432
|
}
|
|
6345
6433
|
);
|
|
6346
6434
|
server2.tool(
|
|
6347
6435
|
"fh_dailymed_search_labels",
|
|
6348
|
-
`Find FDA drug labels on DailyMed by drug name, generic or brand: the total and up to ${
|
|
6436
|
+
`Find FDA drug labels on DailyMed by drug name, generic or brand: the total and up to ${MAX_RESULTS3} rows as arrays in columns order \u2014 set ID, title (drug and form), labeler (the company), published date, version, and the library level when the label is already stored. Newest first. A generic name lists every maker's label; labeler narrows to one company ("Boehringer" for Micardis's maker), a brand name to its own labels. Pass the set ID as "dailymed:<set ID>" to fh_library_read or fh_library_add. Use this, not DailyMed's search page: fetched as Markdown the page shows no set IDs, raw it is some 150,000 characters. The same search is answered from disk for ${searchCacheDays()} days.`,
|
|
6349
6437
|
{
|
|
6350
6438
|
drug_name: z.string().describe('Generic or brand name: "telmisartan", "Micardis".'),
|
|
6351
6439
|
labeler: z.string().optional().describe(`Part of the company's name, to narrow to its labels: "Boehringer".`),
|
|
6352
|
-
max_results: z.number().int().min(1).max(
|
|
6440
|
+
max_results: z.number().int().min(1).max(MAX_RESULTS3).default(20).describe("Rows to return (1\u2013100).")
|
|
6353
6441
|
},
|
|
6354
6442
|
async (args) => {
|
|
6355
6443
|
const t0 = Date.now();
|
|
6356
6444
|
const r = await searchLabels(args, FH_EVIDENCE_DIR);
|
|
6357
6445
|
const secs = ((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0") + "s";
|
|
6358
6446
|
if (!r.ok) {
|
|
6359
|
-
log("search", "dailymed",
|
|
6447
|
+
log("search", "dailymed", `${r.input ? "error" : `failed ${secs}`} ${r.error}${args.drug_name?.trim() ? ` | ${args.drug_name.trim()}` : ""}`);
|
|
6360
6448
|
return { content: [{ type: "text", text: compact2({ error: r.error }) }], isError: true };
|
|
6361
6449
|
}
|
|
6362
6450
|
bump("search", r.cached);
|