evidence-mcp-dev 1.0.20 → 1.0.22
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 +143 -99
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2644,8 +2644,8 @@ function walled(url, stage2, dir = FH_EVIDENCE_DIR) {
|
|
|
2644
2644
|
const h = host(url);
|
|
2645
2645
|
if (!h) return null;
|
|
2646
2646
|
const all = read(dir, h);
|
|
2647
|
-
const
|
|
2648
|
-
return
|
|
2647
|
+
const live7 = (r) => r && (r.streak >= WALL_STREAK || RULE.test(r.reason)) && daysSince(r.date) < settings().retry_after_days ? r : null;
|
|
2648
|
+
return live7(all[stage2] ?? all[legacy(stage2)]) ?? live7(all[pathKey(url, stage2)]);
|
|
2649
2649
|
}
|
|
2650
2650
|
function recordStage(url, stage2, ok, reason = "", dir = FH_EVIDENCE_DIR) {
|
|
2651
2651
|
const h = host(url);
|
|
@@ -3217,6 +3217,7 @@ var VARIABLES = [
|
|
|
3217
3217
|
"FH_EVIDENCE_DIR",
|
|
3218
3218
|
"FH_LOG_KEEP_DAYS",
|
|
3219
3219
|
"FH_ENV",
|
|
3220
|
+
"FH_SOURCES",
|
|
3220
3221
|
"FH_TIERS",
|
|
3221
3222
|
"FH_CONTACT_EMAIL",
|
|
3222
3223
|
"FH_ELSEVIER_API_KEY",
|
|
@@ -3266,17 +3267,17 @@ var VARIABLES = [
|
|
|
3266
3267
|
"FH_BRIGHTDATA_ZONE",
|
|
3267
3268
|
"FH_EVID_ENABLED",
|
|
3268
3269
|
"FH_EVID_MAX_MB",
|
|
3269
|
-
"
|
|
3270
|
-
"
|
|
3271
|
-
"
|
|
3272
|
-
"
|
|
3273
|
-
"
|
|
3274
|
-
"
|
|
3275
|
-
"
|
|
3276
|
-
"
|
|
3270
|
+
"FH_EVIDENCE_MAP_ENABLED",
|
|
3271
|
+
"FH_EVIDENCE_MAP_MAX_QUERIES",
|
|
3272
|
+
"FH_EVIDENCE_MAP_MAX_RESULTS_PER_QUERY",
|
|
3273
|
+
"FH_EVIDENCE_MAP_SCREEN_PROVIDER",
|
|
3274
|
+
"FH_EVIDENCE_MAP_SCREEN_URL",
|
|
3275
|
+
"FH_EVIDENCE_MAP_SCREEN_API_KEY",
|
|
3276
|
+
"FH_EVIDENCE_MAP_SCREEN_MODEL",
|
|
3277
|
+
"FH_EVIDENCE_MAP_SCREEN_PARALLEL"
|
|
3277
3278
|
];
|
|
3278
3279
|
var on = (v) => /^(true|1|yes|on)$/i.test(v?.trim() ?? "");
|
|
3279
|
-
var hidden = (v, env) => v.startsWith("FH_WEB_SEARCH_") && !on(env.FH_WEB_SEARCH_ENABLED) || v === "FH_CITATIONS_ENABLED" && !on(env.FH_CITATIONS_ENABLED) || v.startsWith("FH_EVID_") && !on(env.FH_EVID_ENABLED) || v.startsWith("
|
|
3280
|
+
var hidden = (v, env) => v.startsWith("FH_WEB_SEARCH_") && !on(env.FH_WEB_SEARCH_ENABLED) || v === "FH_CITATIONS_ENABLED" && !on(env.FH_CITATIONS_ENABLED) || v.startsWith("FH_EVID_") && !on(env.FH_EVID_ENABLED) || v.startsWith("FH_EVIDENCE_MAP_") && !on(env.FH_EVIDENCE_MAP_ENABLED);
|
|
3280
3281
|
var sources = (env = process.env) => Object.fromEntries(VARIABLES.filter((v) => !hidden(v, env)).map((v) => [v, sourceOf(v, env)]));
|
|
3281
3282
|
function settings(env = process.env) {
|
|
3282
3283
|
return {
|
|
@@ -3303,7 +3304,8 @@ function resolveTiers(env = process.env) {
|
|
|
3303
3304
|
for (const t of BUILTIN) available.set(t.name, t.make({ tokens: tokens2, api_key: str("FH_CORE_API_KEY", env) || void 0 }));
|
|
3304
3305
|
const proxyUrl = str("FH_PROXY_URL", env);
|
|
3305
3306
|
if (proxyUrl) available.set("proxy", urlTier("proxy", proxyUrl, proxyHeaders(str("FH_PROXY_HEADERS", env))));
|
|
3306
|
-
const
|
|
3307
|
+
const key2 = str("FH_SOURCES", env) || !str("FH_TIERS", env) ? "FH_SOURCES" : "FH_TIERS";
|
|
3308
|
+
const listed = str(key2, env);
|
|
3307
3309
|
const order2 = listed ? listed.split(",").map((s) => s.trim()).filter(Boolean) : [...available.keys()];
|
|
3308
3310
|
const tiers = [], seen2 = /* @__PURE__ */ new Set();
|
|
3309
3311
|
for (const name of order2) {
|
|
@@ -3311,11 +3313,11 @@ function resolveTiers(env = process.env) {
|
|
|
3311
3313
|
seen2.add(name);
|
|
3312
3314
|
const t = available.get(name);
|
|
3313
3315
|
if (t) tiers.push(t);
|
|
3314
|
-
else if (name === "proxy") problems.push(
|
|
3315
|
-
else problems.push(
|
|
3316
|
+
else if (name === "proxy") problems.push(`${key2}: "proxy" listed, but FH_PROXY_URL is unset`);
|
|
3317
|
+
else problems.push(`${key2}: unknown source "${name}" (built-in: ${BUILTIN.map((t2) => t2.name).join(", ")}; proxy when FH_PROXY_URL is set)`);
|
|
3316
3318
|
}
|
|
3317
3319
|
const all = [...tiers.map((t) => ({ name: t.name, enabled: true })), ...[...available.keys()].filter((n) => !seen2.has(n)).map((name) => ({ name, enabled: false }))];
|
|
3318
|
-
return { tiers, all, source: sourceOf(
|
|
3320
|
+
return { tiers, all, source: sourceOf(key2, env), problems };
|
|
3319
3321
|
}
|
|
3320
3322
|
|
|
3321
3323
|
// src/verify/google.ts
|
|
@@ -5264,7 +5266,7 @@ async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
|
|
|
5264
5266
|
if (!cfg || !decide) return { ...out, error: "no decision model configured: set FH_VERIFY_PROVIDER and its API key in .env" };
|
|
5265
5267
|
out.basis = paper.basis;
|
|
5266
5268
|
out.glyphs_unresolved = countUnresolved(paper.text);
|
|
5267
|
-
if (paper.basis === "title") return { ...out, verdict: "
|
|
5269
|
+
if (paper.basis === "title") return { ...out, verdict: "not_supported", reason: NOTHING_TO_VERIFY };
|
|
5268
5270
|
const ws = windows(paper.text, cfg.window_chars);
|
|
5269
5271
|
out.windows = ws.length;
|
|
5270
5272
|
try {
|
|
@@ -5282,8 +5284,8 @@ async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
|
|
|
5282
5284
|
} catch (e) {
|
|
5283
5285
|
return { ...out, error: e instanceof Error ? e.message : String(e) };
|
|
5284
5286
|
}
|
|
5285
|
-
if (out.score >= cfg.threshold) return { ...out, verdict: "
|
|
5286
|
-
return paper.basis === "full_text" ? { ...out, verdict: "
|
|
5287
|
+
if (out.score >= cfg.threshold) return { ...out, verdict: "supported" };
|
|
5288
|
+
return paper.basis === "full_text" ? { ...out, verdict: "not_supported" } : { ...out, verdict: "unverifiable", reason: "only the abstract is stored and it does not state the claim; the full text may" };
|
|
5287
5289
|
}
|
|
5288
5290
|
|
|
5289
5291
|
// src/verify/cache.ts
|
|
@@ -5302,7 +5304,11 @@ var verdictFile = (libraryDir, key2) => join11(libraryDir, "verify", key2.slice(
|
|
|
5302
5304
|
function readVerdict(file3) {
|
|
5303
5305
|
if (!existsSync12(file3)) return null;
|
|
5304
5306
|
try {
|
|
5305
|
-
|
|
5307
|
+
const c = JSON.parse(readFileSync10(file3, "utf8"));
|
|
5308
|
+
const old = c.verdict;
|
|
5309
|
+
if (old === "pass") c.verdict = "supported";
|
|
5310
|
+
else if (old === "fail") c.verdict = "not_supported";
|
|
5311
|
+
return c;
|
|
5306
5312
|
} catch {
|
|
5307
5313
|
return null;
|
|
5308
5314
|
}
|
|
@@ -6215,7 +6221,7 @@ function csvQuery(text4, query, maxHits) {
|
|
|
6215
6221
|
return out;
|
|
6216
6222
|
}
|
|
6217
6223
|
|
|
6218
|
-
// src/
|
|
6224
|
+
// src/evidencemap.ts
|
|
6219
6225
|
import { existsSync as existsSync19, readFileSync as readFileSync17 } from "fs";
|
|
6220
6226
|
|
|
6221
6227
|
// src/screen.ts
|
|
@@ -6223,22 +6229,22 @@ import Anthropic from "@anthropic-ai/sdk";
|
|
|
6223
6229
|
import { createHash as createHash10 } from "crypto";
|
|
6224
6230
|
import { existsSync as existsSync18, mkdirSync as mkdirSync15, readFileSync as readFileSync16 } from "fs";
|
|
6225
6231
|
import { dirname as dirname10, join as join14 } from "path";
|
|
6226
|
-
var screenParallel = (env = process.env) => num("
|
|
6232
|
+
var screenParallel = (env = process.env) => num("FH_EVIDENCE_MAP_SCREEN_PARALLEL", 100, env, (n) => n >= 1 && n <= 400 && Number.isInteger(n));
|
|
6227
6233
|
var SCREEN_PROVIDERS = {
|
|
6228
6234
|
anthropic: { url: "https://api.anthropic.com", model: "claude-haiku-5-5", keyPrefix: "sk-ant-" },
|
|
6229
6235
|
openai: { url: "https://api.openai.com/v1", model: "", keyPrefix: "sk-" }
|
|
6230
6236
|
};
|
|
6231
6237
|
function screenConfig(env = process.env) {
|
|
6232
|
-
const named = str("
|
|
6233
|
-
const url = str("
|
|
6234
|
-
const key2 = str("
|
|
6235
|
-
if (named && !(named in SCREEN_PROVIDERS)) return { ok: false, reason: `
|
|
6238
|
+
const named = str("FH_EVIDENCE_MAP_SCREEN_PROVIDER", env).toLowerCase();
|
|
6239
|
+
const url = str("FH_EVIDENCE_MAP_SCREEN_URL", env).replace(/\/+$/, "");
|
|
6240
|
+
const key2 = str("FH_EVIDENCE_MAP_SCREEN_API_KEY", env);
|
|
6241
|
+
if (named && !(named in SCREEN_PROVIDERS)) return { ok: false, reason: `FH_EVIDENCE_MAP_SCREEN_PROVIDER: ${named}, not one of ${Object.keys(SCREEN_PROVIDERS).join(", ")}` };
|
|
6236
6242
|
const provider = named ? named : url ? "openai" : key2.startsWith("sk-ant-") ? "anthropic" : null;
|
|
6237
|
-
if (!provider) return { ok: false, reason: key2 ? "
|
|
6243
|
+
if (!provider) return { ok: false, reason: key2 ? "FH_EVIDENCE_MAP_SCREEN_API_KEY: the provider cannot be told from the key; set FH_EVIDENCE_MAP_SCREEN_PROVIDER" : "no screening model (FH_EVIDENCE_MAP_SCREEN_PROVIDER, FH_EVIDENCE_MAP_SCREEN_URL, FH_EVIDENCE_MAP_SCREEN_API_KEY)" };
|
|
6238
6244
|
const p = SCREEN_PROVIDERS[provider];
|
|
6239
|
-
const model = str("
|
|
6240
|
-
if (!model) return { ok: false, reason: `
|
|
6241
|
-
if (!key2 && !url) return { ok: false, reason: `
|
|
6245
|
+
const model = str("FH_EVIDENCE_MAP_SCREEN_MODEL", env) || p.model;
|
|
6246
|
+
if (!model) return { ok: false, reason: `FH_EVIDENCE_MAP_SCREEN_MODEL: needed for ${url ? "a model server of your own" : provider}` };
|
|
6247
|
+
if (!key2 && !url) return { ok: false, reason: `FH_EVIDENCE_MAP_SCREEN_API_KEY: needed for ${provider}'s hosted API` };
|
|
6242
6248
|
return { ok: true, provider, url: url || p.url, model, key: key2 };
|
|
6243
6249
|
}
|
|
6244
6250
|
var FIELDS2 = ["relevance", "population", "design", "n", "outcome", "finding", "aspect", "reason"];
|
|
@@ -6257,7 +6263,7 @@ var SCHEMA = {
|
|
|
6257
6263
|
required: [...FIELDS2],
|
|
6258
6264
|
additionalProperties: false
|
|
6259
6265
|
};
|
|
6260
|
-
var fill = (prompt, topic, paper) => prompt.split("{{topic}}").join(topic).split("{{
|
|
6266
|
+
var fill = (prompt, topic, paper) => prompt.split("{{topic}}").join(topic).split("{{article}}").join(paper);
|
|
6261
6267
|
var cacheKey2 = (model, prompt, topic) => createHash10("sha256").update(JSON.stringify([model, fill(prompt, topic, "")])).digest("hex").slice(0, 16);
|
|
6262
6268
|
var ScreenError = class extends Error {
|
|
6263
6269
|
constructor(message, status) {
|
|
@@ -6267,13 +6273,13 @@ var ScreenError = class extends Error {
|
|
|
6267
6273
|
status;
|
|
6268
6274
|
};
|
|
6269
6275
|
function hint(status, message) {
|
|
6270
|
-
if (status === 401 || status === 403) return "the API key is missing, wrong or has no access to the model \u2014
|
|
6271
|
-
if (status === 404) return "the model or the endpoint does not exist \u2014
|
|
6272
|
-
if (status === 400) return "the provider refused the request; the model may not support structured output (a JSON schema) \u2014
|
|
6273
|
-
if (status === 429) return "rate limit still hit after retries \u2014 lower
|
|
6276
|
+
if (status === 401 || status === 403) return "the API key is missing, wrong or has no access to the model \u2014 FH_EVIDENCE_MAP_SCREEN_API_KEY in the server's .env";
|
|
6277
|
+
if (status === 404) return "the model or the endpoint does not exist \u2014 FH_EVIDENCE_MAP_SCREEN_MODEL, FH_EVIDENCE_MAP_SCREEN_URL in the server's .env";
|
|
6278
|
+
if (status === 400) return "the provider refused the request; the model may not support structured output (a JSON schema) \u2014 FH_EVIDENCE_MAP_SCREEN_MODEL";
|
|
6279
|
+
if (status === 429) return "rate limit still hit after retries \u2014 lower FH_EVIDENCE_MAP_SCREEN_PARALLEL or try again later";
|
|
6274
6280
|
if (status && status >= 500) return "the provider's service is failing \u2014 try again later";
|
|
6275
|
-
if (/connect|fetch failed|ECONNREFUSED|ENOTFOUND|timed? ?out|abort/i.test(message)) return "the endpoint cannot be reached \u2014
|
|
6276
|
-
if (/JSON|no answer|max_tokens/i.test(message)) return "the model did not answer with the screening fields \u2014 a model that supports structured output,
|
|
6281
|
+
if (/connect|fetch failed|ECONNREFUSED|ENOTFOUND|timed? ?out|abort/i.test(message)) return "the endpoint cannot be reached \u2014 FH_EVIDENCE_MAP_SCREEN_URL in the server's .env, and the model server running";
|
|
6282
|
+
if (/JSON|no answer|max_tokens/i.test(message)) return "the model did not answer with the screening fields \u2014 a model that supports structured output, FH_EVIDENCE_MAP_SCREEN_MODEL";
|
|
6277
6283
|
if (/refusal/.test(message)) return "the model refused this abstract";
|
|
6278
6284
|
return "";
|
|
6279
6285
|
}
|
|
@@ -6387,15 +6393,14 @@ async function screenAll(lib, pmids, prompt, topic, paper, ask, model, parallel,
|
|
|
6387
6393
|
return out;
|
|
6388
6394
|
}
|
|
6389
6395
|
var LEVELS = [[/meta-analy|systematic review/i, 50], [/\b(rct|randomi[sz]ed)/i, 40], [/cohort|prospective|registry/i, 30], [/case-control|cross-sectional/i, 20], [/guideline|consensus/i, 35]];
|
|
6390
|
-
function score(s, types, queries) {
|
|
6396
|
+
function score(s, types, queries, citesPerYear = 0) {
|
|
6391
6397
|
if (s.relevance === "off-topic") return 0;
|
|
6392
|
-
if (s.population !== "humans" && s.population !== "none") return 5 + (s.relevance === "direct" ? 5 : 0);
|
|
6393
6398
|
const text4 = `${types ?? ""} ${s.design}`;
|
|
6394
|
-
const level = LEVELS.reduce((m, [re, v]) => re.test(text4) ? Math.max(m, v) : m, 10);
|
|
6399
|
+
const level = s.population === "animals" || s.population === "in vitro" ? 25 : LEVELS.reduce((m, [re, v]) => re.test(text4) ? Math.max(m, v) : m, 10);
|
|
6395
6400
|
const rel = s.relevance === "direct" ? 30 : s.relevance === "indirect" ? 15 : 0;
|
|
6396
6401
|
const hard = s.outcome === "hard" ? 10 : 0;
|
|
6397
6402
|
const size = s.n && s.n > 0 ? Math.min(15, Math.round(3 * Math.log10(s.n))) : 0;
|
|
6398
|
-
return level + rel + hard + size + Math.min(10, 2 * queries);
|
|
6403
|
+
return Math.round(level + rel + hard + size + Math.min(10, 2 * queries) + 20 * Math.log10(1 + citesPerYear));
|
|
6399
6404
|
}
|
|
6400
6405
|
function screenLine(r, ms, model) {
|
|
6401
6406
|
const secs = `${(ms / 1e3).toFixed(1)}s`;
|
|
@@ -6404,14 +6409,44 @@ function screenLine(r, ms, model) {
|
|
|
6404
6409
|
return `screened ${f.relevance} \xB7 ${f.population} \xB7 ${f.design} \xB7 n=${f.n ?? "-"} \xB7 ${f.outcome} \xB7 ${f.finding} \xB7 ${f.aspect} \xB7 ${model} ${secs} \xB7 ${f.reason}`;
|
|
6405
6410
|
}
|
|
6406
6411
|
|
|
6407
|
-
// src/
|
|
6408
|
-
var
|
|
6409
|
-
var
|
|
6410
|
-
var
|
|
6412
|
+
// src/citecount.ts
|
|
6413
|
+
var BATCH = 50;
|
|
6414
|
+
var OA2 = "https://api.openalex.org";
|
|
6415
|
+
var live5 = (url) => fetchText(url, { "User-Agent": "evidence-mcp", Accept: "application/json" });
|
|
6416
|
+
var countsUrl = (pmids) => `${OA2}/works?filter=pmid:${pmids.join("|")}&per-page=${BATCH}&select=ids,cited_by_count&${openalexParams()}`;
|
|
6417
|
+
async function citationCounts(pmids, fetchImpl = live5, parallel = 4) {
|
|
6418
|
+
const counts = /* @__PURE__ */ new Map();
|
|
6419
|
+
const batches = [];
|
|
6420
|
+
for (let i = 0; i < pmids.length; i += BATCH) batches.push(pmids.slice(i, i + BATCH));
|
|
6421
|
+
let next = 0, failed = 0, error;
|
|
6422
|
+
const worker = async () => {
|
|
6423
|
+
while (next < batches.length) {
|
|
6424
|
+
const b = batches[next++];
|
|
6425
|
+
try {
|
|
6426
|
+
const d = JSON.parse(await fetchImpl(countsUrl(b)));
|
|
6427
|
+
for (const w of d?.results ?? []) {
|
|
6428
|
+
const pmid = String(w?.ids?.pmid ?? "").split("/").pop();
|
|
6429
|
+
if (pmid && typeof w.cited_by_count === "number") counts.set(pmid, w.cited_by_count);
|
|
6430
|
+
}
|
|
6431
|
+
} catch (e) {
|
|
6432
|
+
failed += b.length;
|
|
6433
|
+
error ??= e instanceof Error ? e.message : String(e);
|
|
6434
|
+
}
|
|
6435
|
+
}
|
|
6436
|
+
};
|
|
6437
|
+
await Promise.all(Array.from({ length: Math.min(parallel, batches.length) }, worker));
|
|
6438
|
+
return { counts, failed, ...error ? { error } : {} };
|
|
6439
|
+
}
|
|
6440
|
+
var perYear = (count, year, now2 = /* @__PURE__ */ new Date()) => count / Math.max(1, now2.getUTCFullYear() - (Number(year) || now2.getUTCFullYear()) + 1);
|
|
6441
|
+
|
|
6442
|
+
// src/evidencemap.ts
|
|
6443
|
+
var literatureEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_EVIDENCE_MAP_ENABLED?.trim() ?? "");
|
|
6444
|
+
var maxQueries = (env = process.env) => num("FH_EVIDENCE_MAP_MAX_QUERIES", 10, env, (n) => n >= 1 && Number.isInteger(n));
|
|
6445
|
+
var maxResultsPerQuery = (env = process.env) => num("FH_EVIDENCE_MAP_MAX_RESULTS_PER_QUERY", 200, env, (n) => n >= 1 && n <= 1e3 && Number.isInteger(n));
|
|
6411
6446
|
var COLUMNS6 = ["pmid", "title", "first_author", "year", "journal", "types", "score", "signals", "relevance", "population", "design", "n", "outcome", "finding", "aspect", "reason"];
|
|
6412
|
-
var SLOTS = ["{{topic}}", "{{
|
|
6413
|
-
var SETTINGS = "
|
|
6414
|
-
var
|
|
6447
|
+
var SLOTS = ["{{topic}}", "{{article}}"];
|
|
6448
|
+
var SETTINGS = "FH_EVIDENCE_MAP_SCREEN_PROVIDER, FH_EVIDENCE_MAP_SCREEN_API_KEY, FH_EVIDENCE_MAP_SCREEN_MODEL, FH_EVIDENCE_MAP_SCREEN_URL";
|
|
6449
|
+
var live6 = (lib) => ({
|
|
6415
6450
|
search: async (query, max) => {
|
|
6416
6451
|
const r = await searchArticles({ query, max_results: max }, lib, void 0, max);
|
|
6417
6452
|
return r.ok ? { ok: true, total: r.result.total, rows: r.result.rows } : { ok: false, error: r.error };
|
|
@@ -6425,13 +6460,14 @@ var live5 = (lib) => ({
|
|
|
6425
6460
|
const f = entryPaths(lib, "pmid", pmid).md;
|
|
6426
6461
|
return existsSync19(f) ? readFileSync17(f, "utf8") : null;
|
|
6427
6462
|
},
|
|
6428
|
-
|
|
6463
|
+
cites: (pmids) => citationCounts(pmids),
|
|
6464
|
+
log: (id, message) => log("evmap", id, message)
|
|
6429
6465
|
});
|
|
6430
6466
|
function csvCell(v) {
|
|
6431
6467
|
const s = v == null ? "" : String(v);
|
|
6432
6468
|
return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
|
6433
6469
|
}
|
|
6434
|
-
async function doResearch(lib, evid, queries, screening, env = process.env, now2 = /* @__PURE__ */ new Date(), deps =
|
|
6470
|
+
async function doResearch(lib, evid, queries, screening, env = process.env, now2 = /* @__PURE__ */ new Date(), deps = live6(lib)) {
|
|
6435
6471
|
const o = openEvid(lib, evid);
|
|
6436
6472
|
if (!o.ok) return o;
|
|
6437
6473
|
const missing = SLOTS.filter((p) => !screening.includes(p));
|
|
@@ -6441,7 +6477,7 @@ async function doResearch(lib, evid, queries, screening, env = process.env, now2
|
|
|
6441
6477
|
const qs = queries.map((q) => q.trim()).filter(Boolean);
|
|
6442
6478
|
if (!qs.length) return { ok: false, error: "queries: at least one PubMed query" };
|
|
6443
6479
|
const max = maxQueries(env);
|
|
6444
|
-
if (qs.length > max) return { ok: false, error: `queries: ${qs.length}, at most ${max} (
|
|
6480
|
+
if (qs.length > max) return { ok: false, error: `queries: ${qs.length}, at most ${max} (FH_EVIDENCE_MAP_MAX_QUERIES); nothing ran` };
|
|
6445
6481
|
const screener = deps.screener;
|
|
6446
6482
|
if (!screener.ok) return { ok: false, failed: true, error: `screening model: ${screener.reason}. Nothing ran. It is set in the server's .env (${SETTINGS}) by whoever runs the server; calling again will not help until then.` };
|
|
6447
6483
|
const perQuery = maxResultsPerQuery(env);
|
|
@@ -6482,9 +6518,15 @@ async function doResearch(lib, evid, queries, screening, env = process.env, now2
|
|
|
6482
6518
|
const unique = (i) => kept.filter((p) => p.queries.length === 1 && p.queries[0] === i).length;
|
|
6483
6519
|
const n = qs.length;
|
|
6484
6520
|
const row3 = (p, sc, sig, f) => [p.pmid, p.title, p.first_author, p.year, p.journal, p.types, sc, sig, ...FIELDS2.map((k) => f?.[k] ?? "")].map(csvCell).join(",");
|
|
6485
|
-
const
|
|
6521
|
+
const citesP = deps.cites(kept.map((p) => p.pmid)).then((c) => {
|
|
6522
|
+
deps.log(o.evid, `citations counted=${c.counts.size} failed=${c.failed}${c.error ? ` \xB7 ${c.error}` : ""}`);
|
|
6523
|
+
return c;
|
|
6524
|
+
}, (e) => ({ counts: /* @__PURE__ */ new Map(), failed: kept.length, error: String(e) }));
|
|
6525
|
+
let cites = /* @__PURE__ */ new Map();
|
|
6526
|
+
const signals = (p) => `in ${p.queries.length} of ${n} queries${cites.has(p.pmid) ? ` \xB7 cited ${cites.get(p.pmid).toLocaleString("en-US")} times` : ""}`;
|
|
6486
6527
|
const queriesJson = JSON.stringify({ date: started, max_results_per_query: perQuery, queries: runs.map((r, i) => ({ ...r, unique: r.error ? 0 : unique(i) })) }, null, 2) + "\n";
|
|
6487
|
-
const
|
|
6528
|
+
const identified = runs.reduce((a, r) => a + r.kept, 0);
|
|
6529
|
+
const base = { started, queries: n, failed_queries: runs.filter((r) => r.error).length, identified, duplicates: identified - ids.length, removed_retracted: retracted.size, not_found: notFound, model: screener.model, endpoint: screener.where };
|
|
6488
6530
|
const t = Date.now();
|
|
6489
6531
|
const model = screener.model;
|
|
6490
6532
|
const text4 = (pmid) => {
|
|
@@ -6499,36 +6541,38 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
|
|
|
6499
6541
|
const results2 = probe2 ? await screenAll(lib, [probe2], screening, topic, text4, screener.ask, model, 1, note) : [];
|
|
6500
6542
|
if (probe2 && results2[0].error) {
|
|
6501
6543
|
const error = results2[0].error;
|
|
6502
|
-
for (const [name, content] of [["
|
|
6503
|
-
return { ok: false, failed: true, error: `screening failed on the first paper (pmid:${probe2}): ${error}. The searches ran: ${kept.length} papers found and stored in the library with their abstracts; nothing was screened, no
|
|
6544
|
+
for (const [name, content] of [["evidence-map-queries.json", queriesJson], ["evidence-map-run.json", JSON.stringify({ ...base, finished: (/* @__PURE__ */ new Date()).toISOString(), state: "failed", error }, null, 2) + "\n"]]) putObject(lib, o.evid, name, content, env);
|
|
6545
|
+
return { ok: false, failed: true, error: `screening failed on the first paper (pmid:${probe2}): ${error}. The searches ran: ${kept.length} papers found and stored in the library with their abstracts; nothing was screened, no evidence-map.csv. evidence-map-queries.json and evidence-map-run.json are in the EVID; call again once the cause is fixed (the searches answer from the cache).` };
|
|
6504
6546
|
}
|
|
6505
6547
|
results2.push(...await screenAll(lib, order2.filter((pmid) => pmid !== probe2), screening, topic, text4, screener.ask, model, screenParallel(env), note));
|
|
6506
6548
|
const by = new Map(results2.map((r) => [r.pmid, r]));
|
|
6549
|
+
const counted = await citesP;
|
|
6550
|
+
cites = counted.counts;
|
|
6507
6551
|
const scored = kept.map((p) => {
|
|
6508
6552
|
const f = by.get(p.pmid)?.screened;
|
|
6509
|
-
return { p, f, sc: f ? score(f, p.types, p.queries.length) : null };
|
|
6553
|
+
return { p, f, sc: f ? score(f, p.types, p.queries.length, cites.has(p.pmid) ? perYear(cites.get(p.pmid), p.year) : 0) : null };
|
|
6510
6554
|
});
|
|
6511
6555
|
const screenedCsv = [["pmid", "kept", "error", ...FIELDS2].join(","), ...scored.map(({ p, f, sc }) => [p.pmid, sc === null ? "" : sc > 0 ? "yes" : "no", by.get(p.pmid)?.error ?? "", ...FIELDS2.map((k) => f?.[k] ?? "")].map(csvCell).join(","))].join("\n") + "\n";
|
|
6512
6556
|
const ranked = scored.filter(({ sc }) => sc !== 0).sort((a, b) => (b.sc ?? -1) - (a.sc ?? -1));
|
|
6513
6557
|
const lines = ranked.map(({ p, f, sc }) => row3(p, sc ?? "", signals(p), f));
|
|
6514
6558
|
const count = (k) => results2.filter((r) => r.screened?.relevance === k).length;
|
|
6515
6559
|
const failures = results2.filter((r) => r.error);
|
|
6516
|
-
const screenRun = {
|
|
6560
|
+
const screenRun = { screened: results2.filter((r) => r.screened).length, not_screened: failures.length, ...failures.length ? { first_error: failures[0].error } : {}, excluded: count("off-topic"), relevance: { direct: count("direct"), indirect: count("indirect"), background: count("background") }, cached: results2.filter((r) => r.cached).length, citations: { counted: counted.counts.size, failed: counted.failed }, seconds: Math.round((Date.now() - t) / 1e3) };
|
|
6517
6561
|
const csv = [COLUMNS6.join(","), ...lines].join("\n") + "\n";
|
|
6518
6562
|
const state = "screened";
|
|
6519
6563
|
const puts = [
|
|
6520
|
-
["
|
|
6521
|
-
["
|
|
6522
|
-
["
|
|
6523
|
-
["
|
|
6524
|
-
["
|
|
6564
|
+
["evidence-map-screening.md", screening],
|
|
6565
|
+
["evidence-map-queries.json", queriesJson],
|
|
6566
|
+
["evidence-map.csv", csv],
|
|
6567
|
+
["evidence-map-screened.csv", screenedCsv],
|
|
6568
|
+
["evidence-map-run.json", JSON.stringify({ ...base, finished: (/* @__PURE__ */ new Date()).toISOString(), state, ...screenRun, included: lines.length }, null, 2) + "\n"]
|
|
6525
6569
|
];
|
|
6526
6570
|
for (const [name, content] of puts) {
|
|
6527
6571
|
const r = putObject(lib, o.evid, name, content, env);
|
|
6528
6572
|
if (!r.ok) return r;
|
|
6529
6573
|
}
|
|
6530
|
-
const partial = failures.length ? { screening_errors: failures.length, first_error: failures[0].error, note: `${failures.length} of ${results2.length} papers could not be screened; they stay in
|
|
6531
|
-
return { ok: true, evid: o.evid, state,
|
|
6574
|
+
const partial = failures.length ? { screening_errors: failures.length, first_error: failures[0].error, note: `${failures.length} of ${results2.length} papers could not be screened; they stay in evidence-map.csv, unscored, at the end (errors in evidence-map-screened.csv). Call again to retry only those: screened papers answer from the cache.` } : {};
|
|
6575
|
+
return { ok: true, evid: o.evid, state, included: lines.length, objects: puts.map(([name]) => name), ...partial };
|
|
6532
6576
|
}
|
|
6533
6577
|
|
|
6534
6578
|
// src/tools.ts
|
|
@@ -6539,11 +6583,11 @@ var pkg = (() => {
|
|
|
6539
6583
|
return { name: "evidence-mcp", version: "0.0.0" };
|
|
6540
6584
|
}
|
|
6541
6585
|
})();
|
|
6542
|
-
var INSTRUCTIONS = `evidence-mcp keeps a local library of scientific
|
|
6586
|
+
var INSTRUCTIONS = `evidence-mcp keeps a local library of scientific articles, FDA drug labels, clinical trial records and web pages, so you can check what a source actually says, and searches ClinicalTrials.gov. The server downloads each record, converts it to Markdown and stores it on disk. Every tool returns a small JSON answer; the document itself never enters your context \u2014 except fh_fetch_url, which is the standard fetch tool with a cache. One ID per call.
|
|
6543
6587
|
|
|
6544
6588
|
IDs \u2014 always "type:value"
|
|
6545
|
-
- pmid:30955454 \u2014
|
|
6546
|
-
- doi:10.\u2026 \u2014
|
|
6589
|
+
- pmid:30955454 \u2014 an article by PubMed ID. Bare digits are taken as a PMID.
|
|
6590
|
+
- doi:10.\u2026 \u2014 an article by DOI. A DOI PubMed indexes is stored under its PMID; any other gets its record from Crossref.
|
|
6547
6591
|
- dailymed:<set ID> \u2014 an FDA prescribing-information label, current version. The set ID comes from fh_dailymed_search_labels, or is the "setid=" value in the label's DailyMed URL.
|
|
6548
6592
|
- nct:05173896 \u2014 a ClinicalTrials.gov trial record, current version. NCT05173896 is accepted too.
|
|
6549
6593
|
|
|
@@ -6553,9 +6597,9 @@ Tools
|
|
|
6553
6597
|
- fh_library_status(id) \u2014 the status of one record without downloading; level "missing" when it is not stored.
|
|
6554
6598
|
- fh_library_read(id, section?, query?, max_chars?, max_hits?, abstract_only?) \u2014 one small piece of a stored document: its outline, one section, or the passages matching a query. abstract_only: true when the abstract is enough \u2014 answered at once, no full-text download.
|
|
6555
6599
|
- fh_verify_claim(claim, id) \u2014 does this one source state this one finding? A decision model judges the stored text and returns a verdict.
|
|
6556
|
-
- fh_pubmed_fetch_articles(pmids) \u2014 title, first author, year, publication types, retracted and level for up to 200 PMIDs at once; faster and far smaller than asking PubMed, known
|
|
6600
|
+
- fh_pubmed_fetch_articles(pmids) \u2014 title, first author, year, publication types, retracted and level for up to 200 PMIDs at once; faster and far smaller than asking PubMed, known articles from disk, the rest in one request and stored. For abstract or full text: fh_library_read.
|
|
6557
6601
|
- 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.
|
|
6558
|
-
${citationsEnabled() ? "- fh_pubmed_citing_articles(id, types?, years?, sort?, max_results?) \u2014 the
|
|
6602
|
+
${citationsEnabled() ? "- fh_pubmed_citing_articles(id, types?, years?, sort?, max_results?) \u2014 the articles that cite an article (pmid: or doi:), as rows in fh_pubmed_search_articles' columns: follow-ups of a trial, later meta-analyses that include it, guidelines (sort: cited), comments on it (types comment, letter, editorial: PubMed's comments on the article first, listed in comments_on). At most 100 rows, no paging: narrow with types or years. Cached a week.\n" : ""}${evidEnabled() ? "- fh_evid_create(metadata), fh_evid_find(query), fh_evid_list_objects(evid), fh_evid_put(evid, name, content), fh_evid_get(evid, name, section?, query?, lines?, max_chars?, max_hits?, previous?) \u2014 an EVID (evid:<16 hex digits>) is a store that outlives the session: metadata fixed at creation, objects (.json, .csv, .txt, .md) any later session or agent given the EVID reads back. Nothing can be deleted; a put keeps the replaced object as its previous version.\n" : ""}${literatureEnabled() ? "- fh_create_evidence_map(evid, queries, screening) \u2014 the evidence map for an EVID: you bring the PubMed queries and the screening prompt; the result, one ranked row per article with its design, population, outcome and finding, appears in the EVID as evidence-map.csv (fh_evid_get).\n" : ""}- 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.
|
|
6559
6603
|
- 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.
|
|
6560
6604
|
${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.
|
|
6561
6605
|
- 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.
|
|
@@ -6563,25 +6607,25 @@ ${webSearchConfigured() ? "- fh_web_search(query, max_results?) \u2014 search th
|
|
|
6563
6607
|
|
|
6564
6608
|
Hints
|
|
6565
6609
|
- fh_library_read and fh_verify_claim store a missing record themselves; the fh_library_read answer then carries added: true. No fh_library_add necessary first.
|
|
6566
|
-
- Many
|
|
6567
|
-
- citable false \u2014 the
|
|
6610
|
+
- Many articles to look over (a search, evidence-map.csv): abstract_only: true for each, then without it only the articles that need the full text.
|
|
6611
|
+
- citable false \u2014 the article is retracted (a retraction notice, or PubMed's publication type), or holds nothing to read: no abstract and no full text. comment says which; corrections lists the notices as {type, pmid, source}.
|
|
6568
6612
|
- level \u2014 what is stored: "full_text", "abstract" or "title" (not even an abstract; citable false). "abstract": searched, no full text found (the log says why); or fulltext "not tried": stored from PubMed alone, searched at the next read without abstract_only, verify or add.
|
|
6569
6613
|
- error "pmid not found", "doi not found", "ctgov: not a study record", "dailymed: not an SPL document" \u2014 no service knows the ID. Remembered for a day (FH_RETRY_AFTER_DAYS): the same call answers from disk with the date it was checked; after that the service is asked again. "invalid id" \u2014 the ID itself is malformed; the same call gives the same answer. A URL is no library ID: it is refused with what to send instead \u2014 the record's ID for a PubMed, doi.org, ClinicalTrials.gov or DailyMed URL, else fh_fetch_url for the web page.
|
|
6570
6614
|
- Calls may run in parallel: fh_library_add, fh_library_read and fh_verify_claim. Two calls on the same missing record share one add.
|
|
6571
|
-
- fh_fetch_url takes any URL that is not
|
|
6615
|
+
- fh_fetch_url takes any URL that is not an article, label or trial record; those have IDs, and fh_library_add, fh_library_read and fh_verify_claim work on the stored document. A second pass over the same review reads every page from disk; a failed fetch is remembered for a day.
|
|
6572
6616
|
- To verify that a web page exists and what it is: fh_fetch_url(url, title_only: true). The answer is "Contents of <url>:" and the page's title line \u2014 a few tokens \u2014 or the fetch error; the page itself is stored in full, so a later fh_fetch_url of the same URL reads from disk.
|
|
6573
6617
|
|
|
6574
6618
|
Verifying a claim
|
|
6575
|
-
- fh_verify_claim judges one claim against one stored document. A finding backed by three
|
|
6619
|
+
- fh_verify_claim judges one claim against one stored document. A finding backed by three articles takes three calls with the same claim.
|
|
6576
6620
|
- It expects the finding as a complete sentence: who or what, the intervention, the outcome, the number. Citation markers and commentary around the finding are not part of what a document states.
|
|
6577
|
-
- It can only confirm what this one document states. A finding about two interventions from two
|
|
6621
|
+
- It can only confirm what this one document states. A finding about two interventions from two articles is two claims, each against its own article. A summary of several trials ("trials used 60\u2013200 mg") is stated by none of them; the dose this one trial used is.
|
|
6578
6622
|
- It returns error for a claim under four words, a sentence fragment, or a claim still containing citations. A short finding with its setting (in vitro, cell line, dose) is accepted; filler words do not help.
|
|
6579
|
-
- verdict "
|
|
6580
|
-
- verdict "
|
|
6623
|
+
- verdict "supported" \u2014 the document states the claim. score is the model's probability.
|
|
6624
|
+
- verdict "not_supported" \u2014 the stored full text does not state the claim as worded; fh_library_read with a query shows what the document does say. Or, with basis "title", nothing is stored to read: reason says so, score is null.
|
|
6581
6625
|
- verdict "unverifiable" \u2014 only the abstract is stored and it does not state the claim; the full text may (reason says so). A retry gives the same answer until a full text is stored.
|
|
6582
6626
|
- glyphs_unresolved above 0 \u2014 the PDF font lost symbols (minus, \xB1, \u2264); a fail on a number may be the font. fh_library_read shows the passage.
|
|
6583
6627
|
- superseded true \u2014 a published correction replaced the figure the claim uses; the status's corrections holds the notice.
|
|
6584
|
-
- Verdicts are kept for 30 days: the same claim against the same stored text answers from disk, no model call.
|
|
6628
|
+
- Verdicts are kept for 30 days: the same claim against the same stored text answers from disk, no model call. An article that gains its full text is judged afresh.
|
|
6585
6629
|
|
|
6586
6630
|
Reading a document
|
|
6587
6631
|
- fh_library_read with only the ID returns the outline: every heading with its word count, and whether the full text or only the abstract is stored.
|
|
@@ -6595,7 +6639,7 @@ Reading a document
|
|
|
6595
6639
|
Status fields: pmid, pmcid, setid, nctid, publications, year, publication_types, retracted, corrections, citable, comment, has_abstract, level, fulltext, version, retrieved_by, glyphs_unresolved, error. fulltext: "not tried" (no source tried yet) or "stored" (abstract_only read, full text exists). Funding and conflicts of interest: fh_library_read section "Declarations". Answers carry only what the call did not send: no echo of the ID, claim or query; a field that is null or an empty list is left out. fh_verify_claim always has verdict, score (null: no judgement) and basis.
|
|
6596
6640
|
|
|
6597
6641
|
Where records come from: PubMed for the record and abstract; the full text from PubMed Central, Europe PMC, publishers' text-mining links, Unpaywall, OpenAlex, CORE, and a proxy URL template from the configuration. Every action is appended as one line to <library>/logs/evidence.log.`;
|
|
6598
|
-
var idSchema = z.string().describe('ID as "type:value":
|
|
6642
|
+
var idSchema = z.string().describe('ID as "type:value": an article "pmid:30955454" (bare digits count as pmid) or "doi:10.5812/asjsm.110753" (an article PubMed does not index; a DOI PubMed indexes is taken as its PMID), a drug label "dailymed:<set ID>" (the set ID from fh_dailymed_search_labels, or the "setid=" value of its DailyMed URL), or a trial record "nct:05173896" (the eight digits; nct:NCT05173896 and a bare NCT05173896 are accepted).');
|
|
6599
6643
|
var levelWord = (m) => m.level === "abstract" && !m.has_abstract ? "title" : m.level;
|
|
6600
6644
|
var json = (s) => ({ content: [{ type: "text", text: statusAnswer(s) }] });
|
|
6601
6645
|
function noticeTag(m) {
|
|
@@ -6611,10 +6655,10 @@ function noticeTag(m) {
|
|
|
6611
6655
|
var modelFailure = (error, cfg) => error.startsWith("no decision model configured") || !!cfg && error.startsWith(`${cfg.model}:`);
|
|
6612
6656
|
function registerTools(server2) {
|
|
6613
6657
|
async function completeFulltext(paths, meta, requested) {
|
|
6614
|
-
const
|
|
6658
|
+
const article = { title: meta.title, pmid: meta.pmid, pmcid: meta.pmcid, doi: meta.doi, headLine: readHeadLine(paths) };
|
|
6615
6659
|
const tried = /* @__PURE__ */ new Set();
|
|
6616
6660
|
let ran = false;
|
|
6617
|
-
const { hit } = await fulltextCascade(
|
|
6661
|
+
const { hit } = await fulltextCascade(article, meta.attempts, (e) => {
|
|
6618
6662
|
if (e.ok === "alert") {
|
|
6619
6663
|
log("add", requested, `!! ${e.message}`);
|
|
6620
6664
|
return;
|
|
@@ -6723,7 +6767,7 @@ function registerTools(server2) {
|
|
|
6723
6767
|
}
|
|
6724
6768
|
server2.tool(
|
|
6725
6769
|
"fh_library_add",
|
|
6726
|
-
"Download and store one record \u2014
|
|
6770
|
+
"Download and store one record \u2014 an article (pmid:, doi:), a drug label (dailymed:<set ID>) or a trial record (nct:<8 digits>) \u2014 and return its status JSON. An article gets its record, abstract and correction notices from PubMed (Crossref for a DOI PubMed does not index), then the full text from the configured sources; a label or trial record is stored as a full text. A stored full text is returned without any download; an abstract-level record retries only sources that failed transiently; a record older than 30 days gets its notices re-read.",
|
|
6727
6771
|
{ id: idSchema },
|
|
6728
6772
|
({ id }) => addEntry(id)
|
|
6729
6773
|
);
|
|
@@ -6890,7 +6934,7 @@ function registerTools(server2) {
|
|
|
6890
6934
|
}
|
|
6891
6935
|
server2.tool(
|
|
6892
6936
|
"fh_library_status",
|
|
6893
|
-
'Read-only status of the library entry for one ID \u2014
|
|
6937
|
+
'Read-only status of the library entry for one ID \u2014 an article, a drug label or a trial record: the same status JSON as fh_library_add, or level "missing" when there is no entry. Never fetches.',
|
|
6894
6938
|
{ id: idSchema },
|
|
6895
6939
|
async ({ id }) => {
|
|
6896
6940
|
const parsed = parseId(id);
|
|
@@ -6912,11 +6956,11 @@ function registerTools(server2) {
|
|
|
6912
6956
|
);
|
|
6913
6957
|
server2.tool(
|
|
6914
6958
|
"fh_library_read",
|
|
6915
|
-
`One piece of a stored document's Markdown, never the whole. No section/query: the outline (headings with word counts; full text or abstract only). section: that heading's own text (case-insensitive substring; a repeated heading as "Participants [3/12]"), capped at max_chars, its subsections listed. query: passages holding every term, each a window of at most 1000 chars with its section, best first, at most max_hits (more: how many further passages match); partial: true with missing_terms when no passage holds them all. section and query together: inside that section. A missing
|
|
6959
|
+
`One piece of a stored document's Markdown, never the whole. No section/query: the outline (headings with word counts; full text or abstract only). section: that heading's own text (case-insensitive substring; a repeated heading as "Participants [3/12]"), capped at max_chars, its subsections listed. query: passages holding every term, each a window of at most 1000 chars with its section, best first, at most max_hits (more: how many further passages match); partial: true with missing_terms when no passage holds them all. section and query together: inside that section. A missing article is added first (added: true). abstract_only: true reads only the abstract, at once \u2014 use it whenever the abstract is enough (screening, design, size, main finding); without it, an article not yet searched for its full text is searched first (seconds, up to a minute, once).`,
|
|
6916
6960
|
{
|
|
6917
6961
|
id: idSchema,
|
|
6918
6962
|
section: z.string().optional().describe("Heading from the outline (case-insensitive substring)."),
|
|
6919
|
-
query: z.string().optional().describe("Two or three distinctive terms the
|
|
6963
|
+
query: z.string().optional().describe("Two or three distinctive terms the article itself would use \u2014 a measure and a unit, an outcome and a group, a compound name \u2014 not the claim. Passages holding all of them are returned, else the best partial matches. With section: inside that section."),
|
|
6920
6964
|
max_chars: z.number().int().positive().optional().describe("Cap for section text (default 6000); passages are capped at 1000 chars each regardless."),
|
|
6921
6965
|
max_hits: z.number().int().positive().optional().describe("Cap for query passages (default 5)."),
|
|
6922
6966
|
abstract_only: z.boolean().optional().describe('true: the abstract only, at once, no full-text download; section and query search the abstract. A missing pmid: is stored from PubMed alone; a missing doi: is added normally first; dailymed: and nct: ignore it. Use it whenever the abstract answers the question (topic, design, population, size, main result, worth reading?); not for details only the full text holds, nor for checking a claim. fulltext "stored" or "not tried": a read without the flag gets more.')
|
|
@@ -7021,7 +7065,7 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
7021
7065
|
);
|
|
7022
7066
|
server2.tool(
|
|
7023
7067
|
"fh_verify_claim",
|
|
7024
|
-
`Does one source state one finding of a review? claim: the finding as a complete statement (subject, intervention, outcome, number), without citations or the review's framing, and only what this source reports. id: one source the review cites for it \u2014
|
|
7068
|
+
`Does one source state one finding of a review? claim: the finding as a complete statement (subject, intervention, outcome, number), without citations or the review's framing, and only what this source reports. id: one source the review cites for it \u2014 article, drug label (dailymed:\u2026) or trial record (nct:\u2026); added first when missing. fulltext "not tried": the full text is searched first (seconds, up to a minute, once). The server reads the stored text and asks a decision model; nothing enters your context. verdict: supported (score is the probability) | not_supported (the full text does not state it; or only the title is stored \u2014 reason says so) | unverifiable (only the abstract is stored and does not state it \u2014 reason says so) | error (claim refused: under four words, a fragment, carrying citations; add failed; no model; model failure). basis: full_text | abstract | title. glyphs_unresolved: symbols the PDF font lost; above 0 a failed number may be the font. superseded: true when a stored correction replaced the claim's figure.`,
|
|
7025
7069
|
{
|
|
7026
7070
|
claim: z.string().describe("One finding as a complete statement (subject, intervention, outcome, number), built from the review's words, without its citations and framing."),
|
|
7027
7071
|
id: idSchema
|
|
@@ -7138,7 +7182,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
|
|
|
7138
7182
|
);
|
|
7139
7183
|
server2.tool(
|
|
7140
7184
|
"fh_pubmed_fetch_articles",
|
|
7141
|
-
`Title, first author, year, publication types, retracted and library level for up to ${MAX_PMIDS} PubMed IDs in one call. Faster and far smaller than asking PubMed: known
|
|
7185
|
+
`Title, first author, year, publication types, retracted and library level for up to ${MAX_PMIDS} PubMed IDs in one call. Faster and far smaller than asking PubMed: known articles come from disk, the rest in one request, stored for every later call; rows as arrays in columns order, ~120 characters an article. Level "not found": PubMed has no such record. For abstract or full text: fh_library_read.`,
|
|
7142
7186
|
{ pmids: z.array(z.string()).min(1).max(MAX_PMIDS).describe('PubMed IDs, "30955454" or "pmid:30955454", up to 200.') },
|
|
7143
7187
|
async ({ pmids }) => {
|
|
7144
7188
|
const t0 = Date.now();
|
|
@@ -7152,7 +7196,7 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
|
|
|
7152
7196
|
);
|
|
7153
7197
|
server2.tool(
|
|
7154
7198
|
"fh_pubmed_search_articles",
|
|
7155
|
-
`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
|
|
7199
|
+
`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 article 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.`,
|
|
7156
7200
|
{
|
|
7157
7201
|
query: z.string().describe('PubMed query, full syntax: "tadalafil AND (systematic review[pt] OR meta-analysis[pt])".'),
|
|
7158
7202
|
max_results: z.number().int().min(1).max(MAX_RESULTS2).default(20).describe("Rows to return (1\u2013100)."),
|
|
@@ -7175,16 +7219,16 @@ ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "
|
|
|
7175
7219
|
);
|
|
7176
7220
|
if (citationsEnabled()) server2.tool(
|
|
7177
7221
|
"fh_pubmed_citing_articles",
|
|
7178
|
-
`The
|
|
7179
|
-
- types: PubMed publication types, any of them;
|
|
7180
|
-
- Comments: with comment, letter or editorial in types, the comments PubMed links to the
|
|
7222
|
+
`The articles that cite an article, as rows in fh_pubmed_search_articles' columns: PMID, title, first author, year, journal, publication types, PMCID, library level. Use it for a trial's follow-ups, later meta-analyses that include it, guidelines (sort: cited) and comments on it.
|
|
7223
|
+
- types: PubMed publication types, any of them; an article without one (many plain articles, some guidelines) never matches.
|
|
7224
|
+
- Comments: with comment, letter or editorial in types, the comments PubMed links to the article come first, of any year and type, and comments_on lists their PMIDs. The other rows only cite the article and are mostly about something else.
|
|
7181
7225
|
- years and sort newest go by the year column.
|
|
7182
7226
|
- At most ${MAX_RESULTS4} rows, no paging: for more, narrow with types or years, or sort: cited. total counts every match.
|
|
7183
7227
|
Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
|
|
7184
7228
|
{
|
|
7185
|
-
id: z.string().describe('The cited
|
|
7229
|
+
id: z.string().describe('The cited article: "pmid:18378520" or "doi:10.1056/NEJMoa0801317".'),
|
|
7186
7230
|
types: z.array(z.string()).optional().describe('Publication types, any of them: "meta-analysis", "systematic review", "randomized controlled trial", "review", "guideline", "comment", "letter", "editorial".'),
|
|
7187
|
-
years: z.string().optional().describe('Publication years of the citing
|
|
7231
|
+
years: z.string().optional().describe('Publication years of the citing articles, as in the year column: "2020-2026", "2022-", "-2019" or "2022". Not applied to the comments PubMed links.'),
|
|
7188
7232
|
sort: z.enum(["newest", "cited"]).default("newest").describe("newest (latest year first) or cited (most cited first)."),
|
|
7189
7233
|
max_results: z.number().int().min(1).max(MAX_RESULTS4).default(20).describe("Rows to return (1\u2013100).")
|
|
7190
7234
|
},
|
|
@@ -7246,7 +7290,7 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
|
|
|
7246
7290
|
"Store an object in an EVID. name: lowercase letters, digits, _ and -, then the extension, which sets the type: .json, .csv (RFC 4180, a header row), .txt, .md; at most 64 characters, no folders. An invalid name is refused with the valid form; content that does not parse as its type is refused. An existing object of that name is replaced and kept as its previous version (one only). Nothing can be deleted.",
|
|
7247
7291
|
{
|
|
7248
7292
|
evid: z.string().describe("The EVID."),
|
|
7249
|
-
name: z.string().describe(`The object's name, e.g. "
|
|
7293
|
+
name: z.string().describe(`The object's name, e.g. "evidence-map.csv", "notes.md".`),
|
|
7250
7294
|
content: z.string().describe("The whole object as text.")
|
|
7251
7295
|
},
|
|
7252
7296
|
async ({ evid, name, content }) => {
|
|
@@ -7257,10 +7301,10 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
|
|
|
7257
7301
|
);
|
|
7258
7302
|
server2.tool(
|
|
7259
7303
|
"fh_evid_get",
|
|
7260
|
-
`Read an object of an EVID, whole or in pieces, as fh_library_read reads a document. No section/query: the object, when it fits max_chars (default ${DEFAULT_MAX_CHARS}); else its outline (.md: headings with word counts; .csv: columns and row count; .json: keys; .txt: lines and words). section (.md): that heading's own text, its subsections listed. query: .md/.txt the passages holding every term, best first; .csv the rows holding every term, with the columns. lines "a-b": .md/.txt those lines, .csv those data rows (
|
|
7304
|
+
`Read an object of an EVID, whole or in pieces, as fh_library_read reads a document. No section/query: the object, when it fits max_chars (default ${DEFAULT_MAX_CHARS}); else its outline (.md: headings with word counts; .csv: columns and row count; .json: keys; .txt: lines and words). section (.md): that heading's own text, its subsections listed. query: .md/.txt the passages holding every term, best first; .csv the rows holding every term, with the columns. lines "a-b": .md/.txt those lines, .csv those data rows (evidence-map.csv is ranked: "1-50" the top 50). previous: true reads the version before the last put. name metadata.json: the metadata.`,
|
|
7261
7305
|
{
|
|
7262
7306
|
evid: z.string().describe("The EVID."),
|
|
7263
|
-
name: z.string().describe(`The object's name, e.g. "
|
|
7307
|
+
name: z.string().describe(`The object's name, e.g. "evidence-map.csv".`),
|
|
7264
7308
|
section: z.string().optional().describe(".md only: a heading, case-insensitive substring."),
|
|
7265
7309
|
query: z.string().optional().describe("Two or three distinctive terms."),
|
|
7266
7310
|
max_chars: z.number().int().positive().optional().describe(`Cap for the object or section text (default ${DEFAULT_MAX_CHARS}).`),
|
|
@@ -7276,16 +7320,16 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
|
|
|
7276
7320
|
);
|
|
7277
7321
|
}
|
|
7278
7322
|
if (literatureEnabled()) server2.tool(
|
|
7279
|
-
"
|
|
7280
|
-
`The
|
|
7323
|
+
"fh_create_evidence_map",
|
|
7324
|
+
`The evidence map for an EVID: the server runs your PubMed queries (at most ${maxQueries()}), screens each abstract found with your screening prompt ({{topic}} from the EVID's metadata, {{article}} each article), and stores the result in the EVID as evidence-map.csv; read it with fh_evid_get. Also stored: evidence-map-screening.md (your prompt), evidence-map-queries.json (the queries), evidence-map-run.json. The articles found are merged, retracted ones dropped, each stored in the library with its abstract; a model screens every abstract, off-topic articles are dropped, the rest ranked by score (evidence level, relevance, outcome, size, citations per year, how many queries found it). Every screening answer, kept or not, in evidence-map-screened.csv. Takes a minute or two.`,
|
|
7281
7325
|
{
|
|
7282
7326
|
evid: z.string().describe("The EVID."),
|
|
7283
7327
|
queries: z.array(z.string()).min(1).describe("PubMed queries in PubMed's syntax."),
|
|
7284
|
-
screening: z.string().describe("The prompt for the screening model, with {{topic}} (the server puts in the EVID's metadata topic) and {{
|
|
7328
|
+
screening: z.string().describe("The prompt for the screening model, with {{topic}} (the server puts in the EVID's metadata topic) and {{article}} (the server puts in each article: PMID, title, year, publication types, abstract).")
|
|
7285
7329
|
},
|
|
7286
7330
|
async ({ evid, queries, screening }) => {
|
|
7287
7331
|
const r = await doResearch(FH_EVIDENCE_DIR, evid, queries, screening);
|
|
7288
|
-
log("
|
|
7332
|
+
log("evmap", evid, r.ok ? `${r.state} queries=${queries.length} articles=${r.included}${r.screening_errors ? ` screening_errors=${r.screening_errors}` : ""}` : `${r.failed ? "failed" : "error"} ${r.error}`);
|
|
7289
7333
|
const { ok, ...rest } = r;
|
|
7290
7334
|
return { content: [{ type: "text", text: compact2(rest) }], ...ok ? {} : { isError: true } };
|
|
7291
7335
|
}
|
|
@@ -7418,7 +7462,7 @@ function devFeatures(env = process.env) {
|
|
|
7418
7462
|
if (web.length) out.push("FH_WEB_SEARCH_ENABLED");
|
|
7419
7463
|
if (citationsEnabled(env)) out.push("FH_CITATIONS_ENABLED");
|
|
7420
7464
|
if (evidEnabled(env)) out.push("FH_EVID_ENABLED");
|
|
7421
|
-
if (literatureEnabled(env)) out.push("
|
|
7465
|
+
if (literatureEnabled(env)) out.push("FH_EVIDENCE_MAP_ENABLED");
|
|
7422
7466
|
return out;
|
|
7423
7467
|
}
|
|
7424
7468
|
|