evidence-mcp-dev 1.0.17 → 1.0.19

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 +766 -47
  2. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -898,9 +898,9 @@ function renderCitation(nodes2) {
898
898
  }).filter(Boolean);
899
899
  const vol = get4("volume")[0], issue = get4("issue")[0], fp = get4("fpage")[0], lp = get4("lpage")[0];
900
900
  const pages = fp ? lp ? `${fp}-${lp}` : fp : get4("elocation-id")[0];
901
- const where = [get4("source")[0], get4("year")[0] ? `${get4("year")[0]};` : "", vol ? `${vol}${issue ? `(${issue})` : ""}` : "", pages ? `:${pages}` : ""].filter(Boolean).join("").replace(/;$/, "");
901
+ const where2 = [get4("source")[0], get4("year")[0] ? `${get4("year")[0]};` : "", vol ? `${vol}${issue ? `(${issue})` : ""}` : "", pages ? `:${pages}` : ""].filter(Boolean).join("").replace(/;$/, "");
902
902
  const ids = f.filter((x) => tagOf(x) === "pub-id").map((x) => `${attr(x, "pub-id-type")}:${squash(plainText(kids(x)))}`);
903
- return [names2.join(", "), [...get4("article-title"), ...get4("chapter-title")][0], where, ...ids].filter(Boolean).join(". ").replace(/\.\./g, ".");
903
+ return [names2.join(", "), [...get4("article-title"), ...get4("chapter-title")][0], where2, ...ids].filter(Boolean).join(". ").replace(/\.\./g, ".");
904
904
  }
905
905
  var FN_LABELS = {
906
906
  "conflict": "Conflicts of interest",
@@ -2402,9 +2402,11 @@ ${CORRECTED_HEADING}
2402
2402
  pubmed_checked: m.pubmed_checked || null,
2403
2403
  attempts: m.attempts,
2404
2404
  files: m.files,
2405
+ ...fulltextNeverTried(m) ? { fulltext: "not tried" } : {},
2405
2406
  glyphs_unresolved: full === null ? null : countUnresolved(full)
2406
2407
  };
2407
2408
  }
2409
+ var fulltextNeverTried = (m) => m.level === "abstract" && m.attempts.length === 0;
2408
2410
  function readStatus(p, base) {
2409
2411
  return statusFromMeta(p, readMeta(p), base);
2410
2412
  }
@@ -2642,8 +2644,8 @@ function walled(url, stage2, dir = FH_EVIDENCE_DIR) {
2642
2644
  const h = host(url);
2643
2645
  if (!h) return null;
2644
2646
  const all = read(dir, h);
2645
- const live5 = (r) => r && (r.streak >= WALL_STREAK || RULE.test(r.reason)) && daysSince(r.date) < settings().retry_after_days ? r : null;
2646
- return live5(all[stage2] ?? all[legacy(stage2)]) ?? live5(all[pathKey(url, stage2)]);
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
2649
  }
2648
2650
  function recordStage(url, stage2, ok, reason = "", dir = FH_EVIDENCE_DIR) {
2649
2651
  const h = host(url);
@@ -3261,10 +3263,20 @@ var VARIABLES = [
3261
3263
  "FH_ZENROWS_API_KEY",
3262
3264
  "FH_ZYTE_API_KEY",
3263
3265
  "FH_BRIGHTDATA_API_KEY",
3264
- "FH_BRIGHTDATA_ZONE"
3266
+ "FH_BRIGHTDATA_ZONE",
3267
+ "FH_EVID_ENABLED",
3268
+ "FH_EVID_MAX_MB",
3269
+ "FH_LITERATURE_ENABLED",
3270
+ "FH_LITERATURE_MAX_QUERIES",
3271
+ "FH_LITERATURE_MAX_RESULTS_PER_QUERY",
3272
+ "FH_LITERATURE_SCREEN_PROVIDER",
3273
+ "FH_LITERATURE_SCREEN_URL",
3274
+ "FH_LITERATURE_SCREEN_API_KEY",
3275
+ "FH_LITERATURE_SCREEN_MODEL",
3276
+ "FH_LITERATURE_SCREEN_PARALLEL"
3265
3277
  ];
3266
3278
  var on = (v) => /^(true|1|yes|on)$/i.test(v?.trim() ?? "");
3267
- var hidden = (v, env) => v.startsWith("FH_WEB_SEARCH_") && !on(env.FH_WEB_SEARCH_ENABLED) || v === "FH_CITATIONS_ENABLED" && !on(env.FH_CITATIONS_ENABLED);
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("FH_LITERATURE_") && !on(env.FH_LITERATURE_ENABLED);
3268
3280
  var sources = (env = process.env) => Object.fromEntries(VARIABLES.filter((v) => !hidden(v, env)).map((v) => [v, sourceOf(v, env)]));
3269
3281
  function settings(env = process.env) {
3270
3282
  return {
@@ -3632,7 +3644,7 @@ function publish() {
3632
3644
  }
3633
3645
 
3634
3646
  // src/tools.ts
3635
- import { existsSync as existsSync17, readFileSync as readFileSync15 } from "fs";
3647
+ import { existsSync as existsSync20, readFileSync as readFileSync18 } from "fs";
3636
3648
  import { z } from "zod";
3637
3649
 
3638
3650
  // src/cascade.ts
@@ -4112,6 +4124,7 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
4112
4124
  const t = info.types[type] ??= { entries: 0, full_text: 0, abstract: 0, title: 0, retracted: 0 };
4113
4125
  t.entries++;
4114
4126
  if (level === "full_text" || level === "abstract" || level === "title") t[level]++;
4127
+ if (raw === "abstract" && /^attempts:[ \t]*$/m.test(md)) t.fulltext_not_tried = (t.fulltext_not_tried ?? 0) + 1;
4115
4128
  const dir = dirname5(meta);
4116
4129
  for (const f of readdirSync4(dir)) {
4117
4130
  try {
@@ -4336,13 +4349,13 @@ ${p.text}`;
4336
4349
  }
4337
4350
  if (p.text.length <= window) return { text: p.text, clipped: false };
4338
4351
  const sents = p.text.split(/(?<=[.!?;])\s+(?=[^a-z])/u);
4339
- const score = sents.map((s) => {
4352
+ const score2 = sents.map((s) => {
4340
4353
  const st = new Set(tokens(s).map(stem));
4341
4354
  return matched.filter((m) => st.has(m)).length;
4342
4355
  });
4343
4356
  let best = 0;
4344
- score.forEach((v, i) => {
4345
- if (v > score[best]) best = i;
4357
+ score2.forEach((v, i) => {
4358
+ if (v > score2[best]) best = i;
4346
4359
  });
4347
4360
  let lo = best, hi = best, len = sents[best].length;
4348
4361
  for (; ; ) {
@@ -4640,8 +4653,8 @@ function metaTags(html) {
4640
4653
  }
4641
4654
  function pageMeta(html) {
4642
4655
  const all = nodes(html);
4643
- const typeOf = (n) => (Array.isArray(n["@type"]) ? n["@type"] : [n["@type"]]).map(String).find((t) => CONTENT.test(t)) ?? null;
4644
- const main = all.filter((n) => typeOf(n)).sort((a, b) => RANK(typeOf(a)) - RANK(typeOf(b)))[0];
4656
+ const typeOf2 = (n) => (Array.isArray(n["@type"]) ? n["@type"] : [n["@type"]]).map(String).find((t) => CONTENT.test(t)) ?? null;
4657
+ const main = all.filter((n) => typeOf2(n)).sort((a, b) => RANK(typeOf2(a)) - RANK(typeOf2(b)))[0];
4645
4658
  const site = all.find((n) => /^(Organization|NewsMediaOrganization|MedicalOrganization|WebSite)$/.test(String(n["@type"])));
4646
4659
  const tags = metaTags(html);
4647
4660
  const tag = (...keys) => {
@@ -4651,7 +4664,7 @@ function pageMeta(html) {
4651
4664
  }
4652
4665
  return [];
4653
4666
  };
4654
- const type = main ? typeOf(main) : null;
4667
+ const type = main ? typeOf2(main) : null;
4655
4668
  const publisher = names(main?.publisher)[0] ?? tag("og:site_name", "citation_journal_title", "citation_publisher", "dc.publisher")[0] ?? names(site)[0] ?? null;
4656
4669
  const key2 = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
4657
4670
  const people = (a) => [...new Set(a)].filter((x) => !/^https?:/i.test(x) && (!publisher || key2(x) !== key2(publisher)));
@@ -5255,12 +5268,12 @@ async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
5255
5268
  const ws = windows(paper.text, cfg.window_chars);
5256
5269
  out.windows = ws.length;
5257
5270
  try {
5258
- let score = 0;
5271
+ let score2 = 0;
5259
5272
  for (const w of ws) {
5260
5273
  const a = await decide({ paper: w, statement: claim }, { backed: { type: "noul", instructions: QUESTION } });
5261
- score = Math.max(score, a.backed?.noul ?? 0);
5274
+ score2 = Math.max(score2, a.backed?.noul ?? 0);
5262
5275
  }
5263
- out.score = score;
5276
+ out.score = score2;
5264
5277
  const corrected = correctedText(paper.text);
5265
5278
  if (corrected) {
5266
5279
  const a = await decide({ corrected, statement: claim }, { superseded: { type: "noul", instructions: SUPERSEDED } });
@@ -5383,14 +5396,14 @@ function yearRange(years) {
5383
5396
  const min = m[1] ?? "1000", max = m[3] ?? (m[2] ? String((/* @__PURE__ */ new Date()).getFullYear()) : m[1]);
5384
5397
  return { min, max };
5385
5398
  }
5386
- function normalizeQuery3(q) {
5399
+ function normalizeQuery3(q, cap = MAX_RESULTS2) {
5387
5400
  const query = (q.query ?? "").replace(/\s+/g, " ").trim();
5388
5401
  if (!query) return { error: "empty query" };
5389
5402
  const sort = q.sort ?? "relevance";
5390
5403
  if (!["relevance", "newest"].includes(sort)) return { error: `sort must be relevance or newest, not "${String(q.sort)}"` };
5391
5404
  const yr = yearRange(q.years);
5392
5405
  if (yr && "error" in yr) return yr;
5393
- const out = { query, sort, max_results: Math.min(MAX_RESULTS2, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS2))) };
5406
+ const out = { query, sort, max_results: Math.min(cap, Math.max(1, Math.floor(q.max_results ?? DEFAULT_RESULTS2))) };
5394
5407
  if (yr) out.years = `${yr.min === "1000" ? "" : yr.min}-${yr.max}`;
5395
5408
  return out;
5396
5409
  }
@@ -5442,8 +5455,8 @@ function levelOf(id, libraryDir) {
5442
5455
  return entryExists(paths) ? String(readStatus(paths, emptyStatus(`pmid:${id}`, "pmid", id, libraryDir)).level) : null;
5443
5456
  }
5444
5457
  var live2 = (url) => fetchText(url, { "User-Agent": "evidence-mcp", Accept: "application/json" });
5445
- async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live2) {
5446
- const q = normalizeQuery3(raw);
5458
+ async function searchArticles(raw, libraryDir = FH_EVIDENCE_DIR, fetchImpl = live2, cap = MAX_RESULTS2) {
5459
+ const q = normalizeQuery3(raw, cap);
5447
5460
  if ("error" in q) return { ok: false, error: q.error, input: true };
5448
5461
  const file3 = searchFile(libraryDir, searchKey3(q));
5449
5462
  if (existsSync13(file3)) {
@@ -5905,10 +5918,586 @@ async function fetchArticles(ids, libraryDir = FH_EVIDENCE_DIR, converter = "evi
5905
5918
  return result;
5906
5919
  }
5907
5920
 
5921
+ // src/evid.ts
5922
+ import { createHash as createHash9 } from "crypto";
5923
+ import { existsSync as existsSync17, mkdirSync as mkdirSync14, readdirSync as readdirSync5, readFileSync as readFileSync15, renameSync as renameSync4, statSync as statSync4 } from "fs";
5924
+ import { join as join13 } from "path";
5925
+ var evidEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_EVID_ENABLED?.trim() ?? "");
5926
+ var maxBytes = (env = process.env) => num("FH_EVID_MAX_MB", 10, env, (n) => n > 0) * 1024 * 1024;
5927
+ var TYPES2 = ["json", "csv", "txt", "md"];
5928
+ var MAX_NAME = 64;
5929
+ var NAME = /^[a-z0-9_-]+\.(json|csv|txt|md)$/;
5930
+ var METADATA = "metadata.json";
5931
+ var PREVIOUS = "previous";
5932
+ var DEFAULT_MAX_CHARS = 2e4;
5933
+ var fail = (error) => ({ ok: false, error });
5934
+ function canonical(v) {
5935
+ if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
5936
+ if (v && typeof v === "object") return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;
5937
+ return JSON.stringify(v);
5938
+ }
5939
+ var hashOf = (metadata) => createHash9("sha256").update(canonical(metadata)).digest("hex").slice(0, 16);
5940
+ var evidDir = (lib, hash) => join13(lib, "evid", hash.slice(0, 2), hash.slice(0, 4), hash);
5941
+ function parseEvid(evid) {
5942
+ const m = /^(?:evid:)?([0-9a-f]{16})$/i.exec(evid.trim());
5943
+ return m ? m[1].toLowerCase() : null;
5944
+ }
5945
+ function checkName(name) {
5946
+ if (name === METADATA) return `${METADATA} is the EVID's metadata, written once at create; it cannot be put`;
5947
+ if (name.length <= MAX_NAME && NAME.test(name)) return null;
5948
+ const dot = name.lastIndexOf(".");
5949
+ const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
5950
+ const base = (dot > 0 ? name.slice(0, dot) : name).toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "object";
5951
+ if (!TYPES2.includes(ext)) return `invalid name '${name}': the extension sets the type; allowed: ${TYPES2.map((t) => "." + t).join(", ")}`;
5952
+ const valid = `${base.slice(0, MAX_NAME - ext.length - 1)}.${ext}`;
5953
+ return `invalid name '${name}'; use '${valid}' (lowercase letters, digits, _ and -, then the extension; at most ${MAX_NAME} characters; no folders)`;
5954
+ }
5955
+ function parseCsv(text4) {
5956
+ const rows = [];
5957
+ let row3 = [], field2 = "", quoted = false, i = 0, line = 1;
5958
+ const endRow = () => {
5959
+ row3.push(field2);
5960
+ field2 = "";
5961
+ rows.push(row3);
5962
+ row3 = [];
5963
+ };
5964
+ while (i < text4.length) {
5965
+ const c = text4[i];
5966
+ if (quoted) {
5967
+ if (c === '"') {
5968
+ if (text4[i + 1] === '"') {
5969
+ field2 += '"';
5970
+ i += 2;
5971
+ continue;
5972
+ }
5973
+ quoted = false;
5974
+ i++;
5975
+ continue;
5976
+ }
5977
+ if (c === "\n") line++;
5978
+ field2 += c;
5979
+ i++;
5980
+ continue;
5981
+ }
5982
+ if (c === '"') {
5983
+ if (field2 !== "") return fail(`csv: line ${line}: a quote inside an unquoted field`);
5984
+ quoted = true;
5985
+ i++;
5986
+ continue;
5987
+ }
5988
+ if (c === ",") {
5989
+ row3.push(field2);
5990
+ field2 = "";
5991
+ i++;
5992
+ continue;
5993
+ }
5994
+ if (c === "\r" && text4[i + 1] === "\n") {
5995
+ i++;
5996
+ continue;
5997
+ }
5998
+ if (c === "\n") {
5999
+ endRow();
6000
+ line++;
6001
+ i++;
6002
+ continue;
6003
+ }
6004
+ field2 += c;
6005
+ i++;
6006
+ }
6007
+ if (quoted) return fail("csv: a quoted field is not closed");
6008
+ if (field2 !== "" || row3.length) endRow();
6009
+ if (!rows.length) return fail("csv: empty; at least a header row");
6010
+ const width = rows[0].length;
6011
+ for (let r = 1; r < rows.length; r++) if (rows[r].length !== width) return fail(`csv: row ${r + 1} has ${rows[r].length} fields, the header ${width}`);
6012
+ return { ok: true, rows };
6013
+ }
6014
+ function checkContent(type, content) {
6015
+ if (content.includes("\0")) return `${type}: holds a NUL character; text only`;
6016
+ if (type === "json") {
6017
+ try {
6018
+ JSON.parse(content);
6019
+ return null;
6020
+ } catch (e) {
6021
+ return `json: does not parse: ${e instanceof Error ? e.message : String(e)}`;
6022
+ }
6023
+ }
6024
+ if (type === "csv") {
6025
+ const r = parseCsv(content);
6026
+ return r.ok ? null : r.error;
6027
+ }
6028
+ return null;
6029
+ }
6030
+ var typeOf = (name) => name.slice(name.lastIndexOf(".") + 1);
6031
+ function createEvid(lib, fields, now2 = /* @__PURE__ */ new Date()) {
6032
+ if (!fields || typeof fields !== "object" || Array.isArray(fields)) return fail('metadata: an object of fields, e.g. { "topic": "\u2026" }');
6033
+ if ("created" in fields) return fail("metadata: created is added by the server; leave it out");
6034
+ const metadata = { ...fields, created: now2.toISOString() };
6035
+ const hash = hashOf(metadata);
6036
+ const dir = evidDir(lib, hash);
6037
+ if (existsSync17(join13(dir, METADATA))) return fail(`evid:${hash} exists already; create again`);
6038
+ mkdirSync14(dir, { recursive: true });
6039
+ writeAtomic(join13(dir, METADATA), JSON.stringify(metadata, null, 2) + "\n");
6040
+ return { ok: true, evid: `evid:${hash}`, metadata };
6041
+ }
6042
+ function openEvid(lib, evid) {
6043
+ const hash = parseEvid(evid);
6044
+ if (!hash) return fail(`invalid evid '${evid}': "evid:" and 16 hex digits`);
6045
+ const dir = evidDir(lib, hash);
6046
+ const file3 = join13(dir, METADATA);
6047
+ if (!existsSync17(file3)) return fail(`evid:${hash} not found`);
6048
+ let metadata;
6049
+ try {
6050
+ metadata = JSON.parse(readFileSync15(file3, "utf8"));
6051
+ } catch {
6052
+ return fail(`evid:${hash}: metadata.json does not parse; nothing read or written`);
6053
+ }
6054
+ if (hashOf(metadata) !== hash) return fail(`evid:${hash}: metadata.json does not match its EVID (edited or damaged); nothing read or written`);
6055
+ return { ok: true, evid: `evid:${hash}`, dir, metadata };
6056
+ }
6057
+ function listObjects(lib, evid) {
6058
+ const o = openEvid(lib, evid);
6059
+ if (!o.ok) return o;
6060
+ const objects = [];
6061
+ for (const name of readdirSync5(o.dir).sort()) {
6062
+ if (name === METADATA || !NAME.test(name)) continue;
6063
+ const st = statSync4(join13(o.dir, name));
6064
+ if (!st.isFile()) continue;
6065
+ const info = { name, type: typeOf(name), size: st.size, written: st.mtime.toISOString() };
6066
+ if (existsSync17(join13(o.dir, PREVIOUS, name))) info.previous = true;
6067
+ objects.push(info);
6068
+ }
6069
+ return { ok: true, evid: o.evid, metadata: o.metadata, objects };
6070
+ }
6071
+ function putObject(lib, evid, name, content, env = process.env) {
6072
+ const bad = checkName(name);
6073
+ if (bad) return fail(bad);
6074
+ const size = Buffer.byteLength(content, "utf8");
6075
+ const max = maxBytes(env);
6076
+ if (size > max) return fail(`${name}: ${size} bytes, above the limit of ${max} (FH_EVID_MAX_MB)`);
6077
+ const problem = checkContent(typeOf(name), content);
6078
+ if (problem) return fail(`${name}: ${problem}`);
6079
+ const o = openEvid(lib, evid);
6080
+ if (!o.ok) return o;
6081
+ const file3 = join13(o.dir, name);
6082
+ const replaced = existsSync17(file3);
6083
+ if (replaced) {
6084
+ mkdirSync14(join13(o.dir, PREVIOUS), { recursive: true });
6085
+ renameSync4(file3, join13(o.dir, PREVIOUS, name));
6086
+ }
6087
+ writeAtomic(file3, content);
6088
+ return { ok: true, replaced, size };
6089
+ }
6090
+ function findEvids(lib, query, max = 20) {
6091
+ if (!query || typeof query !== "object" || Array.isArray(query)) return fail('query: an object of fields, e.g. { "topic": "\u2026" }');
6092
+ const want = Object.entries(query).map(([k, v]) => [k, canonical(v)]);
6093
+ const hits = [];
6094
+ const root = join13(lib, "evid");
6095
+ const dirs = (p) => {
6096
+ try {
6097
+ return readdirSync5(p, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => join13(p, d.name));
6098
+ } catch {
6099
+ return [];
6100
+ }
6101
+ };
6102
+ for (const l1 of dirs(root)) for (const l2 of dirs(l1)) for (const dir of dirs(l2)) {
6103
+ const hash = dir.slice(dir.lastIndexOf("/") + 1);
6104
+ let metadata;
6105
+ try {
6106
+ metadata = JSON.parse(readFileSync15(join13(dir, METADATA), "utf8"));
6107
+ } catch {
6108
+ continue;
6109
+ }
6110
+ if (hashOf(metadata) !== hash) continue;
6111
+ if (want.every(([k, v]) => k in metadata && canonical(metadata[k]) === v)) hits.push({ evid: `evid:${hash}`, metadata });
6112
+ }
6113
+ hits.sort((a, b) => String(b.metadata.created).localeCompare(String(a.metadata.created)));
6114
+ return { ok: true, total: hits.length, evids: hits.slice(0, max) };
6115
+ }
6116
+ function getObject(lib, evid, name, opts = {}, env = process.env) {
6117
+ const bad = name === METADATA ? null : checkName(name);
6118
+ if (bad) return fail(bad);
6119
+ const o = openEvid(lib, evid);
6120
+ if (!o.ok) return o;
6121
+ if (name === METADATA) return { ok: true, content: JSON.stringify(o.metadata, null, 2) };
6122
+ const file3 = opts.previous ? join13(o.dir, PREVIOUS, name) : join13(o.dir, name);
6123
+ if (!existsSync17(file3)) return fail(opts.previous ? `${name}: no previous version` : `${name}: no such object (fh_evid_list_objects lists them)`);
6124
+ const size = statSync4(file3).size;
6125
+ if (size > maxBytes(env)) return fail(`${name}: ${size} bytes, above the limit of ${maxBytes(env)} (FH_EVID_MAX_MB); not opened`);
6126
+ const text4 = readFileSync15(file3, "utf8");
6127
+ const type = typeOf(name);
6128
+ const maxChars = opts.max_chars ?? DEFAULT_MAX_CHARS;
6129
+ if (opts.section !== void 0) {
6130
+ if (type !== "md") return fail(`section: .md objects only; ${name} is .${type}`);
6131
+ if (opts.query === void 0) {
6132
+ const s = readSection(text4, opts.section, maxChars);
6133
+ if (!s) return fail(`section '${opts.section}' not found; headings: ${outline(text4, "full_text").sections.map((x) => x.heading).join(" | ")}`);
6134
+ return { ok: true, ...s };
6135
+ }
6136
+ }
6137
+ if (opts.query !== void 0) {
6138
+ if (type === "csv") return { ok: true, ...csvQuery(text4, opts.query, opts.max_hits ?? 50) };
6139
+ if (type === "json") return fail("query: .md, .txt and .csv objects; a .json object is read whole");
6140
+ let scope;
6141
+ if (opts.section !== void 0) {
6142
+ const found = findSections(text4, opts.section);
6143
+ if (found.length !== 1) return fail(found.length ? `section '${opts.section}' is ambiguous: ${found.map((s) => s.label).join(" | ")}` : `section '${opts.section}' not found`);
6144
+ scope = found[0];
6145
+ }
6146
+ const r = search(text4, opts.query, opts.max_hits ?? 5, { scope });
6147
+ return { ok: true, ...r };
6148
+ }
6149
+ if (text4.length <= maxChars) return { ok: true, content: text4 };
6150
+ return { ok: true, too_large: `${text4.length} chars, above max_chars ${maxChars}: the outline instead; read with section or query, or a larger max_chars`, outline: outlineOf(type, text4) };
6151
+ }
6152
+ function outlineOf(type, text4) {
6153
+ if (type === "md") {
6154
+ const o = outline(text4, "full_text");
6155
+ return { words: o.words, sections: o.sections };
6156
+ }
6157
+ if (type === "csv") {
6158
+ const r = parseCsv(text4);
6159
+ return r.ok ? { columns: r.rows[0], rows: r.rows.length - 1 } : { error: r.error };
6160
+ }
6161
+ if (type === "json") {
6162
+ const v = JSON.parse(text4);
6163
+ return Array.isArray(v) ? { array: v.length } : v && typeof v === "object" ? { keys: Object.keys(v) } : { value: typeof v };
6164
+ }
6165
+ return { lines: text4.split("\n").length, words: (text4.match(/\S+/g) ?? []).length };
6166
+ }
6167
+ function csvQuery(text4, query, maxHits) {
6168
+ const r = parseCsv(text4);
6169
+ if (!r.ok) return { error: r.error };
6170
+ const [columns2, ...rows] = r.rows;
6171
+ const stems = [...new Set(tokens(query).map(stem))];
6172
+ const hits = stems.length ? rows.filter((row3) => {
6173
+ const have = new Set(tokens(row3.join(" ")).map(stem));
6174
+ return stems.every((s) => have.has(s));
6175
+ }) : [];
6176
+ const out = { columns: columns2, rows: hits.slice(0, maxHits), total: hits.length };
6177
+ if (hits.length > maxHits) out.more = hits.length - maxHits;
6178
+ return out;
6179
+ }
6180
+
6181
+ // src/literature.ts
6182
+ import { existsSync as existsSync19, readFileSync as readFileSync17 } from "fs";
6183
+
6184
+ // src/screen.ts
6185
+ import Anthropic from "@anthropic-ai/sdk";
6186
+ import { createHash as createHash10 } from "crypto";
6187
+ import { existsSync as existsSync18, mkdirSync as mkdirSync15, readFileSync as readFileSync16 } from "fs";
6188
+ import { dirname as dirname10, join as join14 } from "path";
6189
+ var screenParallel = (env = process.env) => num("FH_LITERATURE_SCREEN_PARALLEL", 100, env, (n) => n >= 1 && n <= 400 && Number.isInteger(n));
6190
+ var SCREEN_PROVIDERS = {
6191
+ anthropic: { url: "https://api.anthropic.com", model: "claude-haiku-5-5", keyPrefix: "sk-ant-" },
6192
+ openai: { url: "https://api.openai.com/v1", model: "", keyPrefix: "sk-" }
6193
+ };
6194
+ function screenConfig(env = process.env) {
6195
+ const named = str("FH_LITERATURE_SCREEN_PROVIDER", env).toLowerCase();
6196
+ const url = str("FH_LITERATURE_SCREEN_URL", env).replace(/\/+$/, "");
6197
+ const key2 = str("FH_LITERATURE_SCREEN_API_KEY", env);
6198
+ if (named && !(named in SCREEN_PROVIDERS)) return { ok: false, reason: `FH_LITERATURE_SCREEN_PROVIDER: ${named}, not one of ${Object.keys(SCREEN_PROVIDERS).join(", ")}` };
6199
+ const provider = named ? named : url ? "openai" : key2.startsWith("sk-ant-") ? "anthropic" : null;
6200
+ 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)" };
6201
+ const p = SCREEN_PROVIDERS[provider];
6202
+ const model = str("FH_LITERATURE_SCREEN_MODEL", env) || p.model;
6203
+ if (!model) return { ok: false, reason: `FH_LITERATURE_SCREEN_MODEL: needed for ${url ? "a model server of your own" : provider}` };
6204
+ if (!key2 && !url) return { ok: false, reason: `FH_LITERATURE_SCREEN_API_KEY: needed for ${provider}'s hosted API` };
6205
+ return { ok: true, provider, url: url || p.url, model, key: key2 };
6206
+ }
6207
+ var FIELDS2 = ["relevance", "population", "design", "n", "outcome", "finding", "aspect", "reason"];
6208
+ var SCHEMA = {
6209
+ type: "object",
6210
+ properties: {
6211
+ relevance: { type: "string", enum: ["direct", "indirect", "background", "off-topic"], description: "direct: the intervention for the topic's goal; indirect: the intervention for another outcome, or a related drug; background: mechanism, epidemiology; off-topic: not about the topic" },
6212
+ population: { type: "string", enum: ["humans", "animals", "in vitro", "none"] },
6213
+ design: { type: "string", description: "study design, e.g. meta-analysis, systematic review, RCT, cohort, case-control, case report, review, animal study, in vitro" },
6214
+ n: { type: ["integer", "null"], description: "participants, if the abstract states it" },
6215
+ outcome: { type: "string", enum: ["hard", "surrogate", "none"], description: "hard: death, incidence, clinical events; surrogate: biomarker, imaging" },
6216
+ finding: { type: "string", enum: ["benefit", "no effect", "harm", "mixed", "none"] },
6217
+ aspect: { type: "string", enum: ["efficacy", "safety", "mechanism", "dosing", "interaction", "other"] },
6218
+ reason: { type: "string", description: "one sentence: what the paper adds to the topic" }
6219
+ },
6220
+ required: [...FIELDS2],
6221
+ additionalProperties: false
6222
+ };
6223
+ var fill = (prompt, topic, paper) => prompt.split("{{topic}}").join(topic).split("{{paper}}").join(paper);
6224
+ var cacheKey2 = (model, prompt, topic) => createHash10("sha256").update(JSON.stringify([model, fill(prompt, topic, "")])).digest("hex").slice(0, 16);
6225
+ var ScreenError = class extends Error {
6226
+ constructor(message, status) {
6227
+ super(message);
6228
+ this.status = status;
6229
+ }
6230
+ status;
6231
+ };
6232
+ function hint(status, message) {
6233
+ 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";
6234
+ 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";
6235
+ if (status === 400) return "the provider refused the request; the model may not support structured output (a JSON schema) \u2014 FH_LITERATURE_SCREEN_MODEL";
6236
+ if (status === 429) return "rate limit still hit after retries \u2014 lower FH_LITERATURE_SCREEN_PARALLEL or try again later";
6237
+ if (status && status >= 500) return "the provider's service is failing \u2014 try again later";
6238
+ 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";
6239
+ 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";
6240
+ if (/refusal/.test(message)) return "the model refused this abstract";
6241
+ return "";
6242
+ }
6243
+ var describe2 = (e, where2) => {
6244
+ const status = e instanceof ScreenError ? e.status : e instanceof Anthropic.APIError ? e.status : void 0;
6245
+ const message = (e instanceof Error ? e.message : String(e)).replace(/\s+/g, " ").slice(0, 300);
6246
+ const h = hint(status, message);
6247
+ return `${where2}: ${status && !message.includes(String(status)) ? `HTTP ${status} ` : ""}${message}${h ? ` \u2014 ${h}` : ""}`;
6248
+ };
6249
+ var where = (c) => `${c.provider} ${c.model} at ${c.url}`;
6250
+ function askFor(c) {
6251
+ const ask = c.provider === "anthropic" ? anthropicAsk(c.key, c.model, c.url) : openaiAsk(c.url, c.key, c.model);
6252
+ return async (text4) => {
6253
+ try {
6254
+ return await ask(text4);
6255
+ } catch (e) {
6256
+ throw new Error(describe2(e, where(c)));
6257
+ }
6258
+ };
6259
+ }
6260
+ function anthropicAsk(apiKey2, model, baseURL) {
6261
+ const client = new Anthropic({ apiKey: apiKey2, baseURL, maxRetries: 6 });
6262
+ return async (text4) => {
6263
+ const r = await client.messages.create({
6264
+ model,
6265
+ max_tokens: 2048,
6266
+ output_config: { effort: "low", format: { type: "json_schema", schema: SCHEMA } },
6267
+ messages: [{ role: "user", content: text4 }]
6268
+ });
6269
+ if (r.stop_reason === "refusal") throw new Error("refusal");
6270
+ if (r.stop_reason === "max_tokens") throw new Error("max_tokens: the answer was cut off");
6271
+ const block = r.content.find((b) => b.type === "text");
6272
+ if (!block) throw new Error("no answer");
6273
+ return parseAnswer(block.text);
6274
+ };
6275
+ }
6276
+ function openaiAsk(baseUrl, apiKey2, model, fetchImpl = fetch) {
6277
+ return async (text4) => {
6278
+ for (let attempt = 0; ; attempt++) {
6279
+ let r;
6280
+ try {
6281
+ r = await fetchImpl(`${baseUrl}/chat/completions`, {
6282
+ method: "POST",
6283
+ headers: { "content-type": "application/json", ...apiKey2 ? { authorization: `Bearer ${apiKey2}` } : {} },
6284
+ body: JSON.stringify({ model, messages: [{ role: "user", content: text4 }], response_format: { type: "json_schema", json_schema: { name: "screening", strict: true, schema: SCHEMA } } }),
6285
+ signal: AbortSignal.timeout(12e4)
6286
+ });
6287
+ } catch (e) {
6288
+ throw new ScreenError(`cannot connect: ${e instanceof Error ? e.cause instanceof Error ? e.cause.message : e.message : String(e)}`);
6289
+ }
6290
+ if ((r.status === 429 || r.status >= 500) && attempt < 6) {
6291
+ await new Promise((ok) => setTimeout(ok, Math.min(3e4, 1e3 * 2 ** attempt)));
6292
+ continue;
6293
+ }
6294
+ if (!r.ok) throw new ScreenError(`HTTP ${r.status} ${(await r.text()).replace(/\s+/g, " ").slice(0, 200)}`, r.status);
6295
+ const body = await r.json();
6296
+ const choice = body?.choices?.[0];
6297
+ if (choice?.finish_reason === "length") throw new Error("max_tokens: the answer was cut off");
6298
+ const content = choice?.message?.content;
6299
+ if (typeof content !== "string") throw new Error(choice?.message?.refusal ? "refusal" : "no answer");
6300
+ return parseAnswer(content);
6301
+ }
6302
+ };
6303
+ }
6304
+ function parseAnswer(text4) {
6305
+ let a;
6306
+ try {
6307
+ a = JSON.parse(text4);
6308
+ } catch {
6309
+ throw new Error(`the answer is not JSON: ${text4.slice(0, 80)}`);
6310
+ }
6311
+ if (!a || typeof a !== "object" || !SCHEMA.properties.relevance.enum.includes(a.relevance)) throw new Error(`the answer has no valid relevance: ${text4.slice(0, 80)}`);
6312
+ return a;
6313
+ }
6314
+ async function screenAll(lib, pmids, prompt, topic, paper, ask, model, parallel, note = () => {
6315
+ }) {
6316
+ const dir = join14(lib, "screen", cacheKey2(model, prompt, topic));
6317
+ const out = new Array(pmids.length);
6318
+ let next = 0;
6319
+ const worker = async () => {
6320
+ while (next < pmids.length) {
6321
+ const i = next++;
6322
+ const pmid = pmids[i];
6323
+ const file3 = join14(dir, `${pmid}.json`);
6324
+ if (existsSync18(file3)) {
6325
+ try {
6326
+ out[i] = { pmid, screened: JSON.parse(readFileSync16(file3, "utf8")), cached: true };
6327
+ continue;
6328
+ } catch {
6329
+ }
6330
+ }
6331
+ const text4 = paper(pmid);
6332
+ if (!text4) {
6333
+ out[i] = { pmid, error: "no abstract", cached: false };
6334
+ note(out[i], 0);
6335
+ continue;
6336
+ }
6337
+ const t = Date.now();
6338
+ try {
6339
+ const s = await ask(fill(prompt, topic, text4));
6340
+ mkdirSync15(dirname10(file3), { recursive: true });
6341
+ writeAtomic(file3, JSON.stringify(s) + "\n");
6342
+ out[i] = { pmid, screened: s, cached: false };
6343
+ } catch (e) {
6344
+ out[i] = { pmid, error: e instanceof Error ? e.message : String(e), cached: false };
6345
+ }
6346
+ note(out[i], Date.now() - t);
6347
+ }
6348
+ };
6349
+ await Promise.all(Array.from({ length: Math.min(parallel, pmids.length) }, worker));
6350
+ return out;
6351
+ }
6352
+ 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]];
6353
+ function score(s, types, queries) {
6354
+ if (s.relevance === "off-topic") return 0;
6355
+ if (s.population !== "humans" && s.population !== "none") return 5 + (s.relevance === "direct" ? 5 : 0);
6356
+ const text4 = `${types ?? ""} ${s.design}`;
6357
+ const level = LEVELS.reduce((m, [re, v]) => re.test(text4) ? Math.max(m, v) : m, 10);
6358
+ const rel = s.relevance === "direct" ? 30 : s.relevance === "indirect" ? 15 : 0;
6359
+ const hard = s.outcome === "hard" ? 10 : 0;
6360
+ const size = s.n && s.n > 0 ? Math.min(15, Math.round(3 * Math.log10(s.n))) : 0;
6361
+ return level + rel + hard + size + Math.min(10, 2 * queries);
6362
+ }
6363
+ function screenLine(r, ms, model) {
6364
+ const secs = `${(ms / 1e3).toFixed(1)}s`;
6365
+ if (!r.screened) return `failed screen ${model} ${secs}: ${r.error}`;
6366
+ const f = r.screened;
6367
+ 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}`;
6368
+ }
6369
+
6370
+ // src/literature.ts
6371
+ var literatureEnabled = (env = process.env) => /^(true|1|yes|on)$/i.test(env.FH_LITERATURE_ENABLED?.trim() ?? "");
6372
+ var maxQueries = (env = process.env) => num("FH_LITERATURE_MAX_QUERIES", 10, env, (n) => n >= 1 && Number.isInteger(n));
6373
+ var maxResultsPerQuery = (env = process.env) => num("FH_LITERATURE_MAX_RESULTS_PER_QUERY", 200, env, (n) => n >= 1 && n <= 1e3 && Number.isInteger(n));
6374
+ var COLUMNS6 = ["pmid", "title", "first_author", "year", "journal", "types", "score", "signals", "relevance", "population", "design", "n", "outcome", "finding", "aspect", "reason"];
6375
+ var SLOTS = ["{{topic}}", "{{paper}}"];
6376
+ var SETTINGS = "FH_LITERATURE_SCREEN_PROVIDER, FH_LITERATURE_SCREEN_API_KEY, FH_LITERATURE_SCREEN_MODEL, FH_LITERATURE_SCREEN_URL";
6377
+ var live5 = (lib) => ({
6378
+ search: async (query, max) => {
6379
+ const r = await searchArticles({ query, max_results: max }, lib, void 0, max);
6380
+ return r.ok ? { ok: true, total: r.result.total, rows: r.result.rows } : { ok: false, error: r.error };
6381
+ },
6382
+ prefill: async (pmids) => (await fetchArticles(pmids, lib)).rows.map((r) => ({ pmid: r[0], retracted: r[5], level: r[6] })),
6383
+ screener: (() => {
6384
+ const c = screenConfig();
6385
+ return c.ok ? { ok: true, ask: askFor(c), model: c.model, where: where(c) } : { ok: false, reason: c.reason };
6386
+ })(),
6387
+ paper: (pmid) => {
6388
+ const f = entryPaths(lib, "pmid", pmid).md;
6389
+ return existsSync19(f) ? readFileSync17(f, "utf8") : null;
6390
+ },
6391
+ log: (id, message) => log("literature", id, message)
6392
+ });
6393
+ function csvCell(v) {
6394
+ const s = v == null ? "" : String(v);
6395
+ return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
6396
+ }
6397
+ async function doResearch(lib, evid, queries, screening, env = process.env, now2 = /* @__PURE__ */ new Date(), deps = live5(lib)) {
6398
+ const o = openEvid(lib, evid);
6399
+ if (!o.ok) return o;
6400
+ const missing = SLOTS.filter((p) => !screening.includes(p));
6401
+ if (missing.length) return { ok: false, error: `screening: the prompt needs ${missing.join(" and ")} (sample: prompts/screening.md)` };
6402
+ const topic = o.metadata.topic;
6403
+ if (typeof topic !== "string" || !topic.trim()) return { ok: false, error: `${o.evid}: the metadata has no topic for {{topic}}` };
6404
+ const qs = queries.map((q) => q.trim()).filter(Boolean);
6405
+ if (!qs.length) return { ok: false, error: "queries: at least one PubMed query" };
6406
+ const max = maxQueries(env);
6407
+ if (qs.length > max) return { ok: false, error: `queries: ${qs.length}, at most ${max} (FH_LITERATURE_MAX_QUERIES); nothing ran` };
6408
+ const screener = deps.screener;
6409
+ 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.` };
6410
+ const perQuery = maxResultsPerQuery(env);
6411
+ const started = now2.toISOString();
6412
+ const papers = /* @__PURE__ */ new Map();
6413
+ const runs = [];
6414
+ for (const [i, query] of qs.entries()) {
6415
+ const r = await deps.search(query, perQuery);
6416
+ if (!r.ok) {
6417
+ runs.push({ query, total: null, kept: 0, error: r.error });
6418
+ deps.log(o.evid, `failed query ${i + 1}/${qs.length}: ${r.error} \xB7 ${query}`);
6419
+ continue;
6420
+ }
6421
+ runs.push({ query, total: r.total, kept: r.rows.length });
6422
+ deps.log(o.evid, `query ${i + 1}/${qs.length} total=${r.total} kept=${r.rows.length} \xB7 ${query}`);
6423
+ for (const row4 of r.rows) {
6424
+ const pmid = String(row4[0]);
6425
+ const p = papers.get(pmid);
6426
+ if (p) {
6427
+ if (!p.queries.includes(i)) p.queries.push(i);
6428
+ continue;
6429
+ }
6430
+ papers.set(pmid, { pmid, title: row4[1], first_author: row4[2], year: row4[3], journal: row4[4], types: row4[5], queries: [i] });
6431
+ }
6432
+ }
6433
+ if (runs.every((r) => r.error)) return { ok: false, failed: true, error: `pubmed: every query failed (${runs[0].error}). Nothing was stored; try again later, or check the queries' syntax with fh_pubmed_search_articles.` };
6434
+ const ids = [...papers.keys()];
6435
+ const retracted = /* @__PURE__ */ new Set();
6436
+ let notFound = 0;
6437
+ for (let k = 0; k < ids.length; k += MAX_PMIDS) {
6438
+ for (const r of await deps.prefill(ids.slice(k, k + MAX_PMIDS))) {
6439
+ if (r.retracted) retracted.add(r.pmid);
6440
+ if (r.level === "not found") notFound++;
6441
+ }
6442
+ }
6443
+ const kept = ids.filter((id) => !retracted.has(id)).map((id) => papers.get(id));
6444
+ deps.log(o.evid, `prefilled found=${ids.length} retracted=${retracted.size} not_found=${notFound} papers=${kept.length}`);
6445
+ const unique = (i) => kept.filter((p) => p.queries.length === 1 && p.queries[0] === i).length;
6446
+ const n = qs.length;
6447
+ 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(",");
6448
+ const signals = (p) => `in ${p.queries.length} of ${n} queries`;
6449
+ 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";
6450
+ const base = { started, queries: n, failed_queries: runs.filter((r) => r.error).length, found: ids.length, retracted: retracted.size, not_found: notFound, model: screener.model, endpoint: screener.where };
6451
+ const t = Date.now();
6452
+ const model = screener.model;
6453
+ const text4 = (pmid) => {
6454
+ const a = deps.paper(pmid);
6455
+ return a && `${a}
6456
+
6457
+ Publication types: ${papers.get(pmid).types ?? "none listed"}`;
6458
+ };
6459
+ const note = (r, ms) => deps.log(`pmid:${r.pmid}`, screenLine(r, ms, model));
6460
+ const order2 = kept.map((p) => p.pmid);
6461
+ const probe2 = order2.find((pmid) => deps.paper(pmid) !== null);
6462
+ const results2 = probe2 ? await screenAll(lib, [probe2], screening, topic, text4, screener.ask, model, 1, note) : [];
6463
+ if (probe2 && results2[0].error) {
6464
+ const error = results2[0].error;
6465
+ 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);
6466
+ 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-papers.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).` };
6467
+ }
6468
+ results2.push(...await screenAll(lib, order2.filter((pmid) => pmid !== probe2), screening, topic, text4, screener.ask, model, screenParallel(env), note));
6469
+ const by = new Map(results2.map((r) => [r.pmid, r]));
6470
+ const scored = kept.map((p) => {
6471
+ const f = by.get(p.pmid)?.screened;
6472
+ return { p, f, sc: f ? score(f, p.types, p.queries.length) : null };
6473
+ });
6474
+ 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";
6475
+ const ranked = scored.filter(({ sc }) => sc !== 0).sort((a, b) => (b.sc ?? -1) - (a.sc ?? -1));
6476
+ const lines = ranked.map(({ p, f, sc }) => row3(p, sc ?? "", signals(p), f));
6477
+ const count = (k) => results2.filter((r) => r.screened?.relevance === k).length;
6478
+ const failures = results2.filter((r) => r.error);
6479
+ const screenRun = { seconds: Math.round((Date.now() - t) / 1e3), screened: results2.filter((r) => r.screened).length, cached: results2.filter((r) => r.cached).length, errors: failures.length, ...failures.length ? { first_error: failures[0].error } : {}, direct: count("direct"), indirect: count("indirect"), background: count("background"), off_topic: count("off-topic") };
6480
+ const csv = [COLUMNS6.join(","), ...lines].join("\n") + "\n";
6481
+ const state = "screened";
6482
+ const puts = [
6483
+ ["lit-screening.md", screening],
6484
+ ["lit-queries.json", queriesJson],
6485
+ ["lit-papers.csv", csv],
6486
+ ["lit-screened.csv", screenedCsv],
6487
+ ["lit-run.json", JSON.stringify({ ...base, finished: (/* @__PURE__ */ new Date()).toISOString(), state, ...screenRun, papers: lines.length }, null, 2) + "\n"]
6488
+ ];
6489
+ for (const [name, content] of puts) {
6490
+ const r = putObject(lib, o.evid, name, content, env);
6491
+ if (!r.ok) return r;
6492
+ }
6493
+ 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-papers.csv, unscored, at the end (errors in lit-screened.csv). Call again to retry only those: screened papers answer from the cache.` } : {};
6494
+ return { ok: true, evid: o.evid, state, papers: lines.length, objects: puts.map(([name]) => name), ...partial };
6495
+ }
6496
+
5908
6497
  // src/tools.ts
5909
6498
  var pkg = (() => {
5910
6499
  try {
5911
- return JSON.parse(readFileSync15(new URL("../package.json", import.meta.url), "utf8"));
6500
+ return JSON.parse(readFileSync18(new URL("../package.json", import.meta.url), "utf8"));
5912
6501
  } catch {
5913
6502
  return { name: "evidence-mcp", version: "0.0.0" };
5914
6503
  }
@@ -5925,11 +6514,11 @@ Tools
5925
6514
  - fh_info() \u2014 this server's package and version, then the whole library: entry counts by type and level, the retrieval sources, browsers, the decision model, the configuration, this server's cache hits and misses since it started (cache).
5926
6515
  - fh_library_add(id) \u2014 download and store one record; returns its status. A stored full text is returned without any download; an abstract-level record retries only the sources that failed transiently; a record older than 30 days gets its correction notices re-read.
5927
6516
  - fh_library_status(id) \u2014 the status of one record without downloading; level "missing" when it is not stored.
5928
- - fh_library_read(id, section?, query?, max_chars?, max_hits?) \u2014 one small piece of a stored document: its outline, one section, or the passages matching a query.
6517
+ - 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.
5929
6518
  - 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.
5930
6519
  - 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 papers from disk, the rest in one request and stored. For abstract or full text: fh_library_read.
5931
6520
  - 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.
5932
- ${citationsEnabled() ? "- fh_pubmed_citing_articles(id, types?, years?, sort?, max_results?) \u2014 the papers that cite a paper (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 paper first, listed in comments_on). At most 100 rows, no paging: narrow with types or years. Cached a week.\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.
6521
+ ${citationsEnabled() ? "- fh_pubmed_citing_articles(id, types?, years?, sort?, max_results?) \u2014 the papers that cite a paper (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 paper 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?, 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_do_research(evid, queries, screening) \u2014 the literature research for an EVID: you bring the PubMed queries and the screening prompt; the result appears in the EVID as lit-papers.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.
5933
6522
  - 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.
5934
6523
  ${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.
5935
6524
  - 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.
@@ -5937,8 +6526,9 @@ ${webSearchConfigured() ? "- fh_web_search(query, max_results?) \u2014 search th
5937
6526
 
5938
6527
  Hints
5939
6528
  - 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.
6529
+ - Many papers to look over (a search, lit-papers.csv): abstract_only: true for each, then without it only the papers that need the full text.
5940
6530
  - citable false \u2014 the paper 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}.
5941
- - level \u2014 what is stored: "full_text", "abstract" (no full text could be found; the log names each source tried and why it failed) or "title" (not even an abstract; citable false).
6531
+ - 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.
5942
6532
  - 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.
5943
6533
  - 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.
5944
6534
  - fh_fetch_url takes any URL that is not a paper, 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.
@@ -5965,10 +6555,10 @@ Reading a document
5965
6555
  - section and query together search inside that section only.
5966
6556
  - section "Abstract" on a full text without one returns the stored abstract. section "Declarations" returns funding, conflicts of interest, acknowledgements and ethics statements, assembled when the document has no section of that name, else the statements of the PubMed or Crossref record.
5967
6557
 
5968
- Status fields: pmid, pmcid, setid, nctid, publications, year, publication_types, retracted, corrections, citable, comment, has_abstract, level, version, retrieved_by, glyphs_unresolved, error. 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.
6558
+ 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.
5969
6559
 
5970
6560
  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.`;
5971
- var idSchema = z.string().describe('ID as "type:value": a paper "pmid:30955454" (bare digits count as pmid) or "doi:10.5812/asjsm.110753" (a paper PubMed does not index; a DOI PubMed indexes is taken as its PMID), a drug label "dailymed:<set ID>" (the set ID from its DailyMed page URL), or a trial record "nct:05173896" (the eight digits; nct:NCT05173896 and a bare NCT05173896 are accepted).');
6561
+ var idSchema = z.string().describe('ID as "type:value": a paper "pmid:30955454" (bare digits count as pmid) or "doi:10.5812/asjsm.110753" (a paper 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).');
5972
6562
  var levelWord = (m) => m.level === "abstract" && !m.has_abstract ? "title" : m.level;
5973
6563
  var json = (s) => ({ content: [{ type: "text", text: statusAnswer(s) }] });
5974
6564
  function noticeTag(m) {
@@ -6101,6 +6691,13 @@ function registerTools(server2) {
6101
6691
  ({ id }) => addEntry(id)
6102
6692
  );
6103
6693
  const inflight2 = /* @__PURE__ */ new Map();
6694
+ const untried = (paths) => {
6695
+ try {
6696
+ return entryExists(paths) && fulltextNeverTried(readMeta(paths));
6697
+ } catch {
6698
+ return false;
6699
+ }
6700
+ };
6104
6701
  function addEntry(id) {
6105
6702
  const key2 = parseId(id).requested;
6106
6703
  let p = inflight2.get(key2);
@@ -6278,15 +6875,16 @@ function registerTools(server2) {
6278
6875
  );
6279
6876
  server2.tool(
6280
6877
  "fh_library_read",
6281
- `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 paper is added first (added: true).`,
6878
+ `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 paper 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, a paper not yet searched for its full text is first looked up at every source, up to a minute.`,
6282
6879
  {
6283
6880
  id: idSchema,
6284
6881
  section: z.string().optional().describe("Heading from the outline (case-insensitive substring)."),
6285
6882
  query: z.string().optional().describe("Two or three distinctive terms the paper 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."),
6286
6883
  max_chars: z.number().int().positive().optional().describe("Cap for section text (default 6000); passages are capped at 1000 chars each regardless."),
6287
- max_hits: z.number().int().positive().optional().describe("Cap for query passages (default 5).")
6884
+ max_hits: z.number().int().positive().optional().describe("Cap for query passages (default 5)."),
6885
+ 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.')
6288
6886
  },
6289
- async ({ id, section: section2, query, max_chars, max_hits }) => {
6887
+ async ({ id, section: section2, query, max_chars, max_hits, abstract_only }) => {
6290
6888
  const parsed = parseId(id);
6291
6889
  const out = (o2) => ({ content: [{ type: "text", text: readAnswer(o2) }] });
6292
6890
  if (parsed.error) {
@@ -6295,8 +6893,19 @@ function registerTools(server2) {
6295
6893
  }
6296
6894
  const paths = entryPaths(FH_EVIDENCE_DIR, parsed.type, parsed.id);
6297
6895
  let added = false;
6298
- if (!entryExists(paths)) {
6299
- log("read", parsed.requested, "missing adding first");
6896
+ const abstractOnly = abstract_only === true && (parsed.type === "pmid" || parsed.type === "doi");
6897
+ if (abstractOnly && !entryExists(paths) && parsed.type === "pmid") {
6898
+ log("read", parsed.requested, "missing adding abstract only");
6899
+ const r = await fetchArticles([parsed.id], FH_EVIDENCE_DIR).catch((e) => ({ error: e instanceof Error ? e.message : String(e) }));
6900
+ if (!entryExists(paths)) {
6901
+ const why = "error" in r ? r.error : "PubMed has no such record";
6902
+ log("read", parsed.requested, `error ${why}`);
6903
+ return out({ requested: parsed.requested, entry: paths.entry, error: `not in the library and PubMed gave no record: ${why}` });
6904
+ }
6905
+ added = true;
6906
+ }
6907
+ if (!entryExists(paths) || !abstractOnly && untried(paths)) {
6908
+ log("read", parsed.requested, entryExists(paths) ? "untried adding first" : "missing adding first");
6300
6909
  const r = JSON.parse((await addEntry(id)).content[0].text);
6301
6910
  if (!entryExists(paths)) {
6302
6911
  log("read", parsed.requested, `error ${r.error ?? "fh_library_add failed"}`);
@@ -6304,12 +6913,18 @@ function registerTools(server2) {
6304
6913
  }
6305
6914
  added = true;
6306
6915
  }
6307
- const full = existsSync17(paths.fulltextMd);
6308
- const md = readFileSync15(full ? paths.fulltextMd : paths.md, "utf8");
6916
+ const stored = existsSync20(paths.fulltextMd);
6917
+ if (abstractOnly && !existsSync20(paths.md)) {
6918
+ log("read", parsed.requested, "error abstract only: no abstract stored");
6919
+ return out({ requested: parsed.requested, entry: paths.entry, error: `no abstract stored for ${parsed.requested}${stored ? "; a full text is: read again without abstract_only" : ""}` });
6920
+ }
6921
+ const full = stored && !abstractOnly;
6922
+ const md = readFileSync18(full ? paths.fulltextMd : paths.md, "utf8");
6309
6923
  const text4 = full ? "full_text" : "abstract";
6310
- const base = added ? { requested: parsed.requested, entry: paths.entry, text: text4, added: true } : { requested: parsed.requested, entry: paths.entry, text: text4 };
6924
+ const more = abstractOnly ? stored ? { fulltext: "stored" } : untried(paths) ? { fulltext: "not tried" } : {} : {};
6925
+ const base = { requested: parsed.requested, entry: paths.entry, text: text4, ...more, ...added ? { added: true } : {} };
6311
6926
  const headings2 = () => outline(md, text4).sections;
6312
- const describe2 = (r) => `${r.passages.length} passages${r.partial ? " partial" : ""}${r.passages.filter((x) => x.clipped).length ? ` ${r.passages.filter((x) => x.clipped).length} clipped` : ""}${r.missing_terms.length ? ` (missing: ${r.missing_terms.join(", ")})` : ""}`;
6927
+ const describe3 = (r) => `${r.passages.length} passages${r.partial ? " partial" : ""}${r.passages.filter((x) => x.clipped).length ? ` ${r.passages.filter((x) => x.clipped).length} clipped` : ""}${r.missing_terms.length ? ` (missing: ${r.missing_terms.join(", ")})` : ""}`;
6313
6928
  if (section2 && query) {
6314
6929
  const found = findSections(md, section2);
6315
6930
  if (found.length !== 1) {
@@ -6318,15 +6933,15 @@ function registerTools(server2) {
6318
6933
  return out({ ...base, error: `${found.length} sections match "${section2}" \u2014 name one, e.g. "${found[0].label}"`, ambiguous: found.map((s) => ({ heading: s.label, words: s.words })) });
6319
6934
  }
6320
6935
  const r = search(md, query, max_hits ?? 5, { scope: found[0] });
6321
- log("read", parsed.requested, `section "${found[0].label}" query "${query}" \u2192 ${describe2(r)}`);
6936
+ log("read", parsed.requested, `section "${found[0].label}" query "${query}" \u2192 ${describe3(r)}`);
6322
6937
  return out({ ...base, section: found[0].label, query, ...r });
6323
6938
  }
6324
6939
  if (section2) {
6325
6940
  const cap = max_chars ?? 6e3;
6326
6941
  let sec = readSection(md, section2, cap);
6327
6942
  let via = "";
6328
- if (!sec && /abstract/i.test(section2) && full && existsSync17(paths.md)) {
6329
- sec = readSection(readFileSync15(paths.md, "utf8"), "abstract", cap);
6943
+ if (!sec && /abstract/i.test(section2) && full && existsSync20(paths.md)) {
6944
+ sec = readSection(readFileSync18(paths.md, "utf8"), "abstract", cap);
6330
6945
  via = " (from the abstract file)";
6331
6946
  }
6332
6947
  if (!sec && /declaration/i.test(section2)) {
@@ -6358,7 +6973,7 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
6358
6973
  }
6359
6974
  if (query) {
6360
6975
  const r = search(md, query, max_hits ?? 5);
6361
- log("read", parsed.requested, `query "${query}" \u2192 ${describe2(r)}`);
6976
+ log("read", parsed.requested, `query "${query}" \u2192 ${describe3(r)}`);
6362
6977
  if (!r.passages.length) return out({ ...base, query, ...r, sections: headings2().map((s) => s.heading) });
6363
6978
  return out({ ...base, query, ...r });
6364
6979
  }
@@ -6369,7 +6984,7 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
6369
6984
  );
6370
6985
  server2.tool(
6371
6986
  "fh_verify_claim",
6372
- "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 paper, drug label (dailymed:\u2026) or trial record (nct:\u2026); added first when missing. The server reads the stored text and asks a decision model; nothing enters your context. verdict: pass (score is the probability) | fail (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.",
6987
+ `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 paper, drug label (dailymed:\u2026) or trial record (nct:\u2026); added first when missing. fulltext "not tried": the full text is searched first (seconds, once). The server reads the stored text and asks a decision model; nothing enters your context. verdict: pass (score is the probability) | fail (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.`,
6373
6988
  {
6374
6989
  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."),
6375
6990
  id: idSchema
@@ -6378,9 +6993,15 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
6378
6993
  const t0 = Date.now();
6379
6994
  const cfg = verifyConfig();
6380
6995
  const pid = parseId(id);
6381
- if (!pid.error && !entryExists(entryPaths(FH_EVIDENCE_DIR, pid.type, pid.id))) {
6382
- log("verify", pid.requested, "missing adding first");
6383
- await addEntry(id);
6996
+ if (!pid.error) {
6997
+ const vp = entryPaths(FH_EVIDENCE_DIR, pid.type, pid.id);
6998
+ if (!entryExists(vp)) {
6999
+ log("verify", pid.requested, "missing adding first");
7000
+ await addEntry(id);
7001
+ } else if (untried(vp)) {
7002
+ log("verify", pid.requested, "untried adding first");
7003
+ await addEntry(id);
7004
+ }
6384
7005
  }
6385
7006
  const { cached, ...r } = await verifyCached(claim, id, cfg, cfg ? decider(cfg) : null, FH_EVIDENCE_DIR);
6386
7007
  if (!r.error && r.score !== null) bump("verify", cached);
@@ -6455,8 +7076,8 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
6455
7076
  return { content: [{ type: "text", text: `Failed to fetch ${url}: ${added.error}` }], isError: true };
6456
7077
  }
6457
7078
  }
6458
- const file3 = pid.type === "pmid" ? paths.md : existsSync17(paths.fulltextMd) ? paths.fulltextMd : paths.md;
6459
- const md = existsSync17(file3) ? readFileSync15(file3, "utf8") : "";
7079
+ const file3 = pid.type === "pmid" ? paths.md : existsSync20(paths.fulltextMd) ? paths.fulltextMd : paths.md;
7080
+ const md = existsSync20(file3) ? readFileSync18(file3, "utf8") : "";
6460
7081
  const text4 = title_only ? `Contents of ${url}:
6461
7082
  ${(md.split("\n").find((l) => l.trim()) ?? "").trim()}` : fetchAnswer(url, md, "", max_length, start_index);
6462
7083
  bump("fetch", had);
@@ -6545,6 +7166,92 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
6545
7166
  return { content: [{ type: "text", text: compact2({ total, comments_on, columns: columns2, rows }) }] };
6546
7167
  }
6547
7168
  );
7169
+ if (evidEnabled()) {
7170
+ const answer = (r) => {
7171
+ const { ok, ...rest } = r;
7172
+ return { content: [{ type: "text", text: compact2(rest) }], ...ok ? {} : { isError: true } };
7173
+ };
7174
+ server2.tool(
7175
+ "fh_evid_create",
7176
+ 'Create an EVID: a store that outlives the session, named by its metadata. metadata: any fields, any JSON values (e.g. { "topic": "\u2026" }); fixed once created \u2014 a fact known only later is an object (fh_evid_put). The server adds created (UTC) and returns the EVID (evid:<16 hex digits>, a hash of the metadata). Every create is a new EVID, even with the same fields.',
7177
+ { metadata: z.record(z.any()).describe("The fields describing what the EVID is for; any JSON values. created is added by the server.") },
7178
+ async ({ metadata }) => {
7179
+ const r = createEvid(FH_EVIDENCE_DIR, metadata);
7180
+ log("evid", r.ok ? r.evid : null, r.ok ? `created fields=${Object.keys(metadata).join(",")}` : `create error ${r.error}`);
7181
+ return answer(r.ok ? { ok: true, evid: r.evid, created: r.metadata.created } : r);
7182
+ }
7183
+ );
7184
+ server2.tool(
7185
+ "fh_evid_find",
7186
+ "The EVIDs whose metadata has every given field with exactly that value (case and spelling count), newest first, with their metadata. query {} lists all.",
7187
+ {
7188
+ query: z.record(z.any()).describe('Fields and values to match exactly, e.g. { "topic": "Telmisartan" }.'),
7189
+ max_results: z.number().int().min(1).max(100).default(20).describe("EVIDs to return (1\u2013100); total counts every match.")
7190
+ },
7191
+ async ({ query, max_results }) => {
7192
+ const r = findEvids(FH_EVIDENCE_DIR, query, max_results);
7193
+ log("evid", "find", r.ok ? `ok total=${r.total} | ${JSON.stringify(query)}` : `error ${r.error}`);
7194
+ return answer(r);
7195
+ }
7196
+ );
7197
+ server2.tool(
7198
+ "fh_evid_list_objects",
7199
+ "An EVID's metadata and its objects: name, type, size in bytes, when last written, previous: true when a replaced version is kept.",
7200
+ { evid: z.string().describe('The EVID, "evid:" and 16 hex digits.') },
7201
+ async ({ evid }) => {
7202
+ const r = listObjects(FH_EVIDENCE_DIR, evid);
7203
+ log("evid", r.ok ? r.evid : evid, r.ok ? `list objects=${r.objects.length}` : `list error ${r.error}`);
7204
+ return answer(r);
7205
+ }
7206
+ );
7207
+ server2.tool(
7208
+ "fh_evid_put",
7209
+ "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.",
7210
+ {
7211
+ evid: z.string().describe("The EVID."),
7212
+ name: z.string().describe(`The object's name, e.g. "lit-papers.csv", "notes.md".`),
7213
+ content: z.string().describe("The whole object as text.")
7214
+ },
7215
+ async ({ evid, name, content }) => {
7216
+ const r = putObject(FH_EVIDENCE_DIR, evid, name, content);
7217
+ log("evid", evid, r.ok ? `put ${name} ${r.size}B${r.replaced ? " replaced" : ""}` : `put error ${r.error}`);
7218
+ return answer(r);
7219
+ }
7220
+ );
7221
+ server2.tool(
7222
+ "fh_evid_get",
7223
+ `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. previous: true reads the version before the last put. name metadata.json: the metadata.`,
7224
+ {
7225
+ evid: z.string().describe("The EVID."),
7226
+ name: z.string().describe(`The object's name, e.g. "lit-papers.csv".`),
7227
+ section: z.string().optional().describe(".md only: a heading, case-insensitive substring."),
7228
+ query: z.string().optional().describe("Two or three distinctive terms."),
7229
+ max_chars: z.number().int().positive().optional().describe(`Cap for the object or section text (default ${DEFAULT_MAX_CHARS}).`),
7230
+ max_hits: z.number().int().positive().optional().describe("With query: passages (default 5) or csv rows (default 50)."),
7231
+ previous: z.boolean().optional().describe("true: the previous version.")
7232
+ },
7233
+ async ({ evid, name, ...opts }) => {
7234
+ const r = getObject(FH_EVIDENCE_DIR, evid, name, opts);
7235
+ log("evid", evid, r.ok ? `get ${name}${opts.previous ? " previous" : ""}${opts.section ? ` section=${opts.section}` : ""}${opts.query ? ` query=${opts.query}` : ""}${"too_large" in r ? " outline" : ""}` : `get error ${r.error}`);
7236
+ return answer(r);
7237
+ }
7238
+ );
7239
+ }
7240
+ if (literatureEnabled()) server2.tool(
7241
+ "fh_literature_do_research",
7242
+ `The literature research 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, {{paper}} each paper), and stores the result in the EVID as lit-papers.csv; read it with fh_evid_get. Also stored: lit-screening.md (your prompt), lit-queries.json (the queries), lit-run.json. The papers found are merged, retracted ones dropped, each stored in the library with its abstract; a model screens every abstract, off-topic papers 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.`,
7243
+ {
7244
+ evid: z.string().describe("The EVID."),
7245
+ queries: z.array(z.string()).min(1).describe("PubMed queries in PubMed's syntax."),
7246
+ screening: z.string().describe("The prompt for the screening model, with {{topic}} (the server puts in the EVID's metadata topic) and {{paper}} (the server puts in each paper: PMID, title, year, publication types, abstract).")
7247
+ },
7248
+ async ({ evid, queries, screening }) => {
7249
+ const r = await doResearch(FH_EVIDENCE_DIR, evid, queries, screening);
7250
+ log("literature", evid, r.ok ? `${r.state} queries=${queries.length} papers=${r.papers}${r.screening_errors ? ` screening_errors=${r.screening_errors}` : ""}` : `${r.failed ? "failed" : "error"} ${r.error}`);
7251
+ const { ok, ...rest } = r;
7252
+ return { content: [{ type: "text", text: compact2(rest) }], ...ok ? {} : { isError: true } };
7253
+ }
7254
+ );
6548
7255
  server2.tool(
6549
7256
  "fh_clinicaltrials_search_studies",
6550
7257
  `Search ClinicalTrials.gov by free text, intervention or condition; status ongoing | completed | all; sort relevance | newest | largest | completion. Returns the total and up to ${MAX_RESULTS} rows as arrays in columns order: NCT ID, title, status, phase, enrollment ("~100" estimated), start, primary completion, primary outcome, conditions, interventions, has_results. Link: https://clinicaltrials.gov/study/<NCT ID>. Cached ${searchCacheDays()} days. One trial in detail: fh_clinicaltrials_get_study_record.`,
@@ -6639,7 +7346,7 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
6639
7346
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
6640
7347
  }
6641
7348
  const raw = e.paths.fulltextRaw("json");
6642
- const r = existsSync17(raw) ? recordSummary(readFileSync15(raw, "utf8")) : null;
7349
+ const r = existsSync20(raw) ? recordSummary(readFileSync18(raw, "utf8")) : null;
6643
7350
  if (!r) {
6644
7351
  log("trials", e.requested, "record error: no stored record");
6645
7352
  return { content: [{ type: "text", text: compact2({ error: "no stored record" }) }], isError: true };
@@ -6658,7 +7365,7 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
6658
7365
  log("trials", nct, `results error: ${e.error}`);
6659
7366
  return { content: [{ type: "text", text: compact2({ error: e.error }) }], isError: true };
6660
7367
  }
6661
- const md = existsSync17(e.paths.fulltextMd) ? readFileSync15(e.paths.fulltextMd, "utf8") : "";
7368
+ const md = existsSync20(e.paths.fulltextMd) ? readFileSync18(e.paths.fulltextMd, "utf8") : "";
6662
7369
  const r = resultsText(e.requested.replace(/^nct:/, "NCT"), md, max_chars);
6663
7370
  log("trials", e.requested, `results ${r.has_results ? `${r.outcomes.length} outcomes${r.truncated ? " truncated" : ""}` : "none"}`);
6664
7371
  return { content: [{ type: "text", text: leanJson(r) }] };
@@ -6666,6 +7373,17 @@ Citations from OpenAlex. Cached ${searchCacheDays()} days.`,
6666
7373
  );
6667
7374
  }
6668
7375
 
7376
+ // src/devfeatures.ts
7377
+ function devFeatures(env = process.env) {
7378
+ const out = [];
7379
+ const web = webSearchConfig(env);
7380
+ if (web.length) out.push("FH_WEB_SEARCH_ENABLED");
7381
+ if (citationsEnabled(env)) out.push("FH_CITATIONS_ENABLED");
7382
+ if (evidEnabled(env)) out.push("FH_EVID_ENABLED");
7383
+ if (literatureEnabled(env)) out.push("FH_LITERATURE_ENABLED");
7384
+ return out;
7385
+ }
7386
+
6669
7387
  // src/index.ts
6670
7388
  var server = new McpServer(
6671
7389
  { name: pkg.name, version: pkg.version },
@@ -6676,6 +7394,7 @@ startStats(pkg);
6676
7394
  migrateLogName();
6677
7395
  migrateWalls();
6678
7396
  log("startup", null, `${pkg.name} ${pkg.version}`);
7397
+ for (const f of devFeatures()) log("startup", null, f);
6679
7398
  process.on("exit", abandonAll);
6680
7399
  for (const problem of [...resolveTiers().problems, ...verifyProblems()]) log("startup", null, `!! ${problem}`);
6681
7400
  var transport = new StdioServerTransport();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "evidence-mcp-dev",
3
- "version": "1.0.17",
3
+ "version": "1.0.19",
4
4
  "description": "Internal development build of evidence-mcp. Not for public use.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,6 +13,7 @@
13
13
  "node": ">=20.18.1"
14
14
  },
15
15
  "dependencies": {
16
+ "@anthropic-ai/sdk": "^1.10.0",
16
17
  "@joplin/turndown-plugin-gfm": "^1.0.68",
17
18
  "@modelcontextprotocol/sdk": "^1.0.0",
18
19
  "fast-xml-parser": "^5.11.2",