evidence-mcp-dev 1.0.21 → 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.
Files changed (2) hide show
  1. package/dist/index.js +97 -60
  2. 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 live6 = (r) => r && (r.streak >= WALL_STREAK || RULE.test(r.reason)) && daysSince(r.date) < settings().retry_after_days ? r : null;
2648
- return live6(all[stage2] ?? all[legacy(stage2)]) ?? live6(all[pathKey(url, stage2)]);
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);
@@ -3267,17 +3267,17 @@ var VARIABLES = [
3267
3267
  "FH_BRIGHTDATA_ZONE",
3268
3268
  "FH_EVID_ENABLED",
3269
3269
  "FH_EVID_MAX_MB",
3270
- "FH_LITERATURE_ENABLED",
3271
- "FH_LITERATURE_MAX_QUERIES",
3272
- "FH_LITERATURE_MAX_RESULTS_PER_QUERY",
3273
- "FH_LITERATURE_SCREEN_PROVIDER",
3274
- "FH_LITERATURE_SCREEN_URL",
3275
- "FH_LITERATURE_SCREEN_API_KEY",
3276
- "FH_LITERATURE_SCREEN_MODEL",
3277
- "FH_LITERATURE_SCREEN_PARALLEL"
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"
3278
3278
  ];
3279
3279
  var on = (v) => /^(true|1|yes|on)$/i.test(v?.trim() ?? "");
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_LITERATURE_") && !on(env.FH_LITERATURE_ENABLED);
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);
3281
3281
  var sources = (env = process.env) => Object.fromEntries(VARIABLES.filter((v) => !hidden(v, env)).map((v) => [v, sourceOf(v, env)]));
3282
3282
  function settings(env = process.env) {
3283
3283
  return {
@@ -6221,7 +6221,7 @@ function csvQuery(text4, query, maxHits) {
6221
6221
  return out;
6222
6222
  }
6223
6223
 
6224
- // src/literature.ts
6224
+ // src/evidencemap.ts
6225
6225
  import { existsSync as existsSync19, readFileSync as readFileSync17 } from "fs";
6226
6226
 
6227
6227
  // src/screen.ts
@@ -6229,22 +6229,22 @@ import Anthropic from "@anthropic-ai/sdk";
6229
6229
  import { createHash as createHash10 } from "crypto";
6230
6230
  import { existsSync as existsSync18, mkdirSync as mkdirSync15, readFileSync as readFileSync16 } from "fs";
6231
6231
  import { dirname as dirname10, join as join14 } from "path";
6232
- var screenParallel = (env = process.env) => num("FH_LITERATURE_SCREEN_PARALLEL", 100, env, (n) => n >= 1 && n <= 400 && Number.isInteger(n));
6232
+ var screenParallel = (env = process.env) => num("FH_EVIDENCE_MAP_SCREEN_PARALLEL", 100, env, (n) => n >= 1 && n <= 400 && Number.isInteger(n));
6233
6233
  var SCREEN_PROVIDERS = {
6234
6234
  anthropic: { url: "https://api.anthropic.com", model: "claude-haiku-5-5", keyPrefix: "sk-ant-" },
6235
6235
  openai: { url: "https://api.openai.com/v1", model: "", keyPrefix: "sk-" }
6236
6236
  };
6237
6237
  function screenConfig(env = process.env) {
6238
- const named = str("FH_LITERATURE_SCREEN_PROVIDER", env).toLowerCase();
6239
- const url = str("FH_LITERATURE_SCREEN_URL", env).replace(/\/+$/, "");
6240
- const key2 = str("FH_LITERATURE_SCREEN_API_KEY", env);
6241
- if (named && !(named in SCREEN_PROVIDERS)) return { ok: false, reason: `FH_LITERATURE_SCREEN_PROVIDER: ${named}, not one of ${Object.keys(SCREEN_PROVIDERS).join(", ")}` };
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(", ")}` };
6242
6242
  const provider = named ? named : url ? "openai" : key2.startsWith("sk-ant-") ? "anthropic" : null;
6243
- if (!provider) return { ok: false, reason: key2 ? "FH_LITERATURE_SCREEN_API_KEY: the provider cannot be told from the key; set FH_LITERATURE_SCREEN_PROVIDER" : "no screening model (FH_LITERATURE_SCREEN_PROVIDER, FH_LITERATURE_SCREEN_URL, FH_LITERATURE_SCREEN_API_KEY)" };
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)" };
6244
6244
  const p = SCREEN_PROVIDERS[provider];
6245
- const model = str("FH_LITERATURE_SCREEN_MODEL", env) || p.model;
6246
- if (!model) return { ok: false, reason: `FH_LITERATURE_SCREEN_MODEL: needed for ${url ? "a model server of your own" : provider}` };
6247
- if (!key2 && !url) return { ok: false, reason: `FH_LITERATURE_SCREEN_API_KEY: needed for ${provider}'s hosted API` };
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` };
6248
6248
  return { ok: true, provider, url: url || p.url, model, key: key2 };
6249
6249
  }
6250
6250
  var FIELDS2 = ["relevance", "population", "design", "n", "outcome", "finding", "aspect", "reason"];
@@ -6273,13 +6273,13 @@ var ScreenError = class extends Error {
6273
6273
  status;
6274
6274
  };
6275
6275
  function hint(status, message) {
6276
- if (status === 401 || status === 403) return "the API key is missing, wrong or has no access to the model \u2014 FH_LITERATURE_SCREEN_API_KEY in the server's .env";
6277
- if (status === 404) return "the model or the endpoint does not exist \u2014 FH_LITERATURE_SCREEN_MODEL, FH_LITERATURE_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_LITERATURE_SCREEN_MODEL";
6279
- if (status === 429) return "rate limit still hit after retries \u2014 lower FH_LITERATURE_SCREEN_PARALLEL or try again later";
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";
6280
6280
  if (status && status >= 500) return "the provider's service is failing \u2014 try again later";
6281
- if (/connect|fetch failed|ECONNREFUSED|ENOTFOUND|timed? ?out|abort/i.test(message)) return "the endpoint cannot be reached \u2014 FH_LITERATURE_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_LITERATURE_SCREEN_MODEL";
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";
6283
6283
  if (/refusal/.test(message)) return "the model refused this abstract";
6284
6284
  return "";
6285
6285
  }
@@ -6393,15 +6393,14 @@ async function screenAll(lib, pmids, prompt, topic, paper, ask, model, parallel,
6393
6393
  return out;
6394
6394
  }
6395
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]];
6396
- function score(s, types, queries) {
6396
+ function score(s, types, queries, citesPerYear = 0) {
6397
6397
  if (s.relevance === "off-topic") return 0;
6398
- if (s.population !== "humans" && s.population !== "none") return 5 + (s.relevance === "direct" ? 5 : 0);
6399
6398
  const text4 = `${types ?? ""} ${s.design}`;
6400
- 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);
6401
6400
  const rel = s.relevance === "direct" ? 30 : s.relevance === "indirect" ? 15 : 0;
6402
6401
  const hard = s.outcome === "hard" ? 10 : 0;
6403
6402
  const size = s.n && s.n > 0 ? Math.min(15, Math.round(3 * Math.log10(s.n))) : 0;
6404
- 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));
6405
6404
  }
6406
6405
  function screenLine(r, ms, model) {
6407
6406
  const secs = `${(ms / 1e3).toFixed(1)}s`;
@@ -6410,14 +6409,44 @@ function screenLine(r, ms, model) {
6410
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}`;
6411
6410
  }
6412
6411
 
6413
- // src/literature.ts
6414
- var literatureEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_LITERATURE_ENABLED?.trim() ?? "");
6415
- var maxQueries = (env = process.env) => num("FH_LITERATURE_MAX_QUERIES", 10, env, (n) => n >= 1 && Number.isInteger(n));
6416
- var maxResultsPerQuery = (env = process.env) => num("FH_LITERATURE_MAX_RESULTS_PER_QUERY", 200, env, (n) => n >= 1 && n <= 1e3 && Number.isInteger(n));
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));
6417
6446
  var COLUMNS6 = ["pmid", "title", "first_author", "year", "journal", "types", "score", "signals", "relevance", "population", "design", "n", "outcome", "finding", "aspect", "reason"];
6418
6447
  var SLOTS = ["{{topic}}", "{{article}}"];
6419
- var SETTINGS = "FH_LITERATURE_SCREEN_PROVIDER, FH_LITERATURE_SCREEN_API_KEY, FH_LITERATURE_SCREEN_MODEL, FH_LITERATURE_SCREEN_URL";
6420
- var live5 = (lib) => ({
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) => ({
6421
6450
  search: async (query, max) => {
6422
6451
  const r = await searchArticles({ query, max_results: max }, lib, void 0, max);
6423
6452
  return r.ok ? { ok: true, total: r.result.total, rows: r.result.rows } : { ok: false, error: r.error };
@@ -6431,13 +6460,14 @@ var live5 = (lib) => ({
6431
6460
  const f = entryPaths(lib, "pmid", pmid).md;
6432
6461
  return existsSync19(f) ? readFileSync17(f, "utf8") : null;
6433
6462
  },
6434
- log: (id, message) => log("lit", id, message)
6463
+ cites: (pmids) => citationCounts(pmids),
6464
+ log: (id, message) => log("evmap", id, message)
6435
6465
  });
6436
6466
  function csvCell(v) {
6437
6467
  const s = v == null ? "" : String(v);
6438
6468
  return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
6439
6469
  }
6440
- async function doResearch(lib, evid, queries, screening, env = process.env, now2 = /* @__PURE__ */ new Date(), deps = live5(lib)) {
6470
+ async function doResearch(lib, evid, queries, screening, env = process.env, now2 = /* @__PURE__ */ new Date(), deps = live6(lib)) {
6441
6471
  const o = openEvid(lib, evid);
6442
6472
  if (!o.ok) return o;
6443
6473
  const missing = SLOTS.filter((p) => !screening.includes(p));
@@ -6447,7 +6477,7 @@ async function doResearch(lib, evid, queries, screening, env = process.env, now2
6447
6477
  const qs = queries.map((q) => q.trim()).filter(Boolean);
6448
6478
  if (!qs.length) return { ok: false, error: "queries: at least one PubMed query" };
6449
6479
  const max = maxQueries(env);
6450
- if (qs.length > max) return { ok: false, error: `queries: ${qs.length}, at most ${max} (FH_LITERATURE_MAX_QUERIES); nothing ran` };
6480
+ if (qs.length > max) return { ok: false, error: `queries: ${qs.length}, at most ${max} (FH_EVIDENCE_MAP_MAX_QUERIES); nothing ran` };
6451
6481
  const screener = deps.screener;
6452
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.` };
6453
6483
  const perQuery = maxResultsPerQuery(env);
@@ -6488,7 +6518,12 @@ async function doResearch(lib, evid, queries, screening, env = process.env, now2
6488
6518
  const unique = (i) => kept.filter((p) => p.queries.length === 1 && p.queries[0] === i).length;
6489
6519
  const n = qs.length;
6490
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(",");
6491
- const signals = (p) => `in ${p.queries.length} of ${n} queries`;
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` : ""}`;
6492
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";
6493
6528
  const identified = runs.reduce((a, r) => a + r.kept, 0);
6494
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 };
@@ -6506,35 +6541,37 @@ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
6506
6541
  const results2 = probe2 ? await screenAll(lib, [probe2], screening, topic, text4, screener.ask, model, 1, note) : [];
6507
6542
  if (probe2 && results2[0].error) {
6508
6543
  const error = results2[0].error;
6509
- for (const [name, content] of [["lit-queries.json", queriesJson], ["lit-run.json", JSON.stringify({ ...base, finished: (/* @__PURE__ */ new Date()).toISOString(), state: "failed", error }, null, 2) + "\n"]]) putObject(lib, o.evid, name, content, env);
6510
- 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 lit-map.csv. lit-queries.json and lit-run.json are in the EVID; call again once the cause is fixed (the searches answer from the cache).` };
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).` };
6511
6546
  }
6512
6547
  results2.push(...await screenAll(lib, order2.filter((pmid) => pmid !== probe2), screening, topic, text4, screener.ask, model, screenParallel(env), note));
6513
6548
  const by = new Map(results2.map((r) => [r.pmid, r]));
6549
+ const counted = await citesP;
6550
+ cites = counted.counts;
6514
6551
  const scored = kept.map((p) => {
6515
6552
  const f = by.get(p.pmid)?.screened;
6516
- 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 };
6517
6554
  });
6518
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";
6519
6556
  const ranked = scored.filter(({ sc }) => sc !== 0).sort((a, b) => (b.sc ?? -1) - (a.sc ?? -1));
6520
6557
  const lines = ranked.map(({ p, f, sc }) => row3(p, sc ?? "", signals(p), f));
6521
6558
  const count = (k) => results2.filter((r) => r.screened?.relevance === k).length;
6522
6559
  const failures = results2.filter((r) => r.error);
6523
- 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, seconds: Math.round((Date.now() - t) / 1e3) };
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) };
6524
6561
  const csv = [COLUMNS6.join(","), ...lines].join("\n") + "\n";
6525
6562
  const state = "screened";
6526
6563
  const puts = [
6527
- ["lit-screening.md", screening],
6528
- ["lit-queries.json", queriesJson],
6529
- ["lit-map.csv", csv],
6530
- ["lit-screened.csv", screenedCsv],
6531
- ["lit-run.json", JSON.stringify({ ...base, finished: (/* @__PURE__ */ new Date()).toISOString(), state, ...screenRun, included: lines.length }, null, 2) + "\n"]
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"]
6532
6569
  ];
6533
6570
  for (const [name, content] of puts) {
6534
6571
  const r = putObject(lib, o.evid, name, content, env);
6535
6572
  if (!r.ok) return r;
6536
6573
  }
6537
- 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 lit-map.csv, unscored, at the end (errors in lit-screened.csv). Call again to retry only those: screened papers answer from the cache.` } : {};
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.` } : {};
6538
6575
  return { ok: true, evid: o.evid, state, included: lines.length, objects: puts.map(([name]) => name), ...partial };
6539
6576
  }
6540
6577
 
@@ -6562,7 +6599,7 @@ Tools
6562
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.
6563
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.
6564
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.
6565
- ${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_literature_map_evidence(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 lit-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.
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.
6566
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.
6567
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.
6568
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.
@@ -6570,7 +6607,7 @@ ${webSearchConfigured() ? "- fh_web_search(query, max_results?) \u2014 search th
6570
6607
 
6571
6608
  Hints
6572
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.
6573
- - Many articles to look over (a search, lit-map.csv): abstract_only: true for each, then without it only the articles that need the full text.
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.
6574
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}.
6575
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.
6576
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.
@@ -7253,7 +7290,7 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7253
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.",
7254
7291
  {
7255
7292
  evid: z.string().describe("The EVID."),
7256
- name: z.string().describe(`The object's name, e.g. "lit-map.csv", "notes.md".`),
7293
+ name: z.string().describe(`The object's name, e.g. "evidence-map.csv", "notes.md".`),
7257
7294
  content: z.string().describe("The whole object as text.")
7258
7295
  },
7259
7296
  async ({ evid, name, content }) => {
@@ -7264,10 +7301,10 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7264
7301
  );
7265
7302
  server2.tool(
7266
7303
  "fh_evid_get",
7267
- `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 (lit-map.csv is ranked: "1-50" the top 50). previous: true reads the version before the last put. name metadata.json: the metadata.`,
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.`,
7268
7305
  {
7269
7306
  evid: z.string().describe("The EVID."),
7270
- name: z.string().describe(`The object's name, e.g. "lit-map.csv".`),
7307
+ name: z.string().describe(`The object's name, e.g. "evidence-map.csv".`),
7271
7308
  section: z.string().optional().describe(".md only: a heading, case-insensitive substring."),
7272
7309
  query: z.string().optional().describe("Two or three distinctive terms."),
7273
7310
  max_chars: z.number().int().positive().optional().describe(`Cap for the object or section text (default ${DEFAULT_MAX_CHARS}).`),
@@ -7283,8 +7320,8 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7283
7320
  );
7284
7321
  }
7285
7322
  if (literatureEnabled()) server2.tool(
7286
- "fh_literature_map_evidence",
7287
- `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 lit-map.csv; read it with fh_evid_get. Also stored: lit-screening.md (your prompt), lit-queries.json (the queries), lit-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, how many queries found it). Every screening answer, kept or not, in lit-screened.csv. Takes a minute or two.`,
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.`,
7288
7325
  {
7289
7326
  evid: z.string().describe("The EVID."),
7290
7327
  queries: z.array(z.string()).min(1).describe("PubMed queries in PubMed's syntax."),
@@ -7292,7 +7329,7 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
7292
7329
  },
7293
7330
  async ({ evid, queries, screening }) => {
7294
7331
  const r = await doResearch(FH_EVIDENCE_DIR, evid, queries, screening);
7295
- log("lit", 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}`);
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}`);
7296
7333
  const { ok, ...rest } = r;
7297
7334
  return { content: [{ type: "text", text: compact2(rest) }], ...ok ? {} : { isError: true } };
7298
7335
  }
@@ -7425,7 +7462,7 @@ function devFeatures(env = process.env) {
7425
7462
  if (web.length) out.push("FH_WEB_SEARCH_ENABLED");
7426
7463
  if (citationsEnabled(env)) out.push("FH_CITATIONS_ENABLED");
7427
7464
  if (evidEnabled(env)) out.push("FH_EVID_ENABLED");
7428
- if (literatureEnabled(env)) out.push("FH_LITERATURE_ENABLED");
7465
+ if (literatureEnabled(env)) out.push("FH_EVIDENCE_MAP_ENABLED");
7429
7466
  return out;
7430
7467
  }
7431
7468
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "evidence-mcp-dev",
3
- "version": "1.0.21",
3
+ "version": "1.0.22",
4
4
  "description": "Internal development build of evidence-mcp. Not for public use.",
5
5
  "type": "module",
6
6
  "bin": {