medical-terminologies-mcp 4.3.2 → 4.4.0

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 +183 -87
  2. package/package.json +6 -3
package/dist/index.js CHANGED
@@ -30,7 +30,7 @@ function unknownCursorError(message) {
30
30
  var package_default = {
31
31
  name: "medical-terminologies-mcp",
32
32
  mcpName: "io.github.SidneyBissoli/medical-terminologies-mcp",
33
- version: "4.3.2",
33
+ version: "4.4.0",
34
34
  description: "Unified MCP server for seven medical terminologies (ICD-11, ICF, LOINC, RxNorm, MeSH, ATC, CID-10) with authoritative WHO ICD-10\u2192ICD-11 mapping. 37 tools, hosted endpoint available, MIT.",
35
35
  author: "Sidney da Silva Pereira Bissoli",
36
36
  license: "MIT",
@@ -84,7 +84,9 @@ var package_default = {
84
84
  typecheck: "tsc --noEmit",
85
85
  prepublishOnly: "npm run build",
86
86
  "build:worker-lib": 'esbuild src/worker-lib.ts --bundle --platform=browser --target=es2022 --format=esm --outfile=dist/worker-lib.js --tree-shaking=false --conditions=workerd,browser --define:process.env.NODE_ENV=\\"production\\" --external:node:* --external:cloudflare:* --external:@modelcontextprotocol/* --external:zod --alias:events=node:events --alias:stream=node:stream --alias:buffer=node:buffer --alias:util=node:util --alias:path=node:path --alias:os=node:os --alias:fs=node:fs --alias:url=node:url --alias:crypto=node:crypto',
87
- "manifest:lhm": "node scripts/gen-lhm-manifest.mjs"
87
+ "manifest:lhm": "node scripts/gen-lhm-manifest.mjs",
88
+ "fixtures:record": "tsx scripts/record-tool-fixtures.ts",
89
+ "eval:answers": "tsx src/evals/run-answers.ts"
88
90
  },
89
91
  dependencies: {
90
92
  "@modelcontextprotocol/server": "^2.0.0",
@@ -96,9 +98,10 @@ var package_default = {
96
98
  },
97
99
  devDependencies: {
98
100
  "@modelcontextprotocol/client": "^2.0.0",
99
- "@sbissoli/mcp-evals": "^0.2.1",
101
+ "@sbissoli/mcp-evals": "^0.3.0",
100
102
  "@sbissoli/mcp-live-source": "^0.5.0",
101
103
  "@sbissoli/mcp-surface": "^0.6.0",
104
+ "@sbissoli/mcp-tool-tests": "^0.2.0",
102
105
  "@types/node": "^26.5.1",
103
106
  esbuild: "^0.28.2",
104
107
  nock: "^15.0.1",
@@ -546,7 +549,17 @@ var lenientBoolean = z.union([
546
549
  var RxCUISchema = numericIdSchema("RxCUI");
547
550
  var LOINCNumberSchema = z.string().regex(/^\d{1,5}-\d$/, 'Invalid LOINC number; expected format like "2339-0"');
548
551
  var MeSHIdSchema = z.string().regex(/^D\d+$/, 'Invalid MeSH descriptor ID; expected "D" followed by digits (e.g., D015242)');
549
- var maxResults = (defaultValue) => z.number().int().min(1).max(100).optional().default(defaultValue).describe(`Maximum number of results (1-100). Default: ${defaultValue}`);
552
+ var maxResults = (defaultValue, max = 100) => z.number().int().min(1).max(max).optional().default(defaultValue).describe(`Maximum number of results (1-${max}). Default: ${defaultValue}`);
553
+ var offsetParam = (max) => {
554
+ const base = z.number().int().min(0);
555
+ return (max === void 0 ? base : base.max(max)).optional().default(0).describe(
556
+ "Number of results to skip, to read the next page: pass `next_offset` from the previous answer, keeping the other arguments. Default: 0" + (max === void 0 ? "" : ` (at most ${max}: the source serves at most the first ${max + 100} results)`)
557
+ );
558
+ };
559
+ var LOINC_MAX_OFFSET = 7400;
560
+ var offsetOut = z.number().int().describe("Results skipped before the first one returned (the `offset` asked for).");
561
+ var nextOffsetOut = z.number().int().nullable().describe("`offset` that returns the next page with the same arguments; null when this page reaches the end of the results.");
562
+ var nextOffset = (offset, shown, total) => shown > 0 && offset + shown < total ? offset + shown : null;
550
563
  var withinSchema = (what) => z.array(z.string().trim().min(1)).min(1).max(10).optional().describe(what);
551
564
  var WithinBranchSchema = z.object({
552
565
  value: z.string().describe("The branch as sent in `within`."),
@@ -558,6 +571,7 @@ var ICD11SearchParamsSchema = z.object({
558
571
  query: z.string().min(1).describe("Search text (disease name, symptom, or keyword)"),
559
572
  language: SupportedLanguageSchema.optional().default("en"),
560
573
  max_results: maxResults(25),
574
+ offset: offsetParam(),
561
575
  within: withinSchema(
562
576
  'Only search these branches of ICD-11 and their descendants (up to 10): a chapter number ("06", "V"), a block range ("5A10-5A14"), a category code ("5A11") or an entity URI. Uses the WHO search subtree filter. A branch that does not exist is an error, never a silent unbounded search.'
563
577
  )
@@ -593,6 +607,8 @@ var ICD11SearchOutputSchema = z.object({
593
607
  query: z.string().describe("The search text as submitted."),
594
608
  within: z.array(WithinBranchSchema).describe("The branches that bounded the search, resolved at the WHO; empty when the search was unbounded."),
595
609
  total_count: z.number().int().describe("Number of entities the WHO search returned, before the max_results cap."),
610
+ offset: offsetOut,
611
+ next_offset: nextOffsetOut,
596
612
  entities: z.array(
597
613
  z.object({
598
614
  code: z.string().nullable(),
@@ -602,7 +618,7 @@ var ICD11SearchOutputSchema = z.object({
602
618
  is_leaf: z.boolean(),
603
619
  matching_pvs: z.array(ICD11MatchingPVSchema)
604
620
  })
605
- ).describe("Matching ICD-11 MMS entities in WHO relevance order, at most max_results.")
621
+ ).describe("Matching ICD-11 MMS entities in WHO relevance order, at most max_results, starting after `offset`.")
606
622
  });
607
623
  var ICD11LabelRefSchema = z.object({
608
624
  uri: z.string().describe("URI of the entity this term comes from: the referenced entity when the WHO names one (release URI, else foundation URI), otherwise the entity being looked up itself \u2014 which is the case for most inclusions and index terms."),
@@ -667,6 +683,7 @@ var ICFSearchParamsSchema = z.object({
667
683
  query: z.string().min(1).describe('Search text (a function, activity, body structure or environmental factor, e.g. "walking")'),
668
684
  language: SupportedLanguageSchema.optional().default("en"),
669
685
  max_results: maxResults(25),
686
+ offset: offsetParam(),
670
687
  within: withinSchema(
671
688
  'Only search these branches of ICF and their descendants (up to 10): a category code ("d450", "b280") or an ICF entity URI. Uses the WHO search subtree filter. A branch that does not exist is an error, never a silent unbounded search.'
672
689
  )
@@ -686,6 +703,8 @@ var ICFSearchOutputSchema = z.object({
686
703
  query: z.string().describe("The search text as submitted."),
687
704
  within: z.array(WithinBranchSchema).describe("The branches that bounded the search, resolved at the WHO; empty when the search was unbounded."),
688
705
  total_count: z.number().int().describe("Number of entities the WHO search returned, before the max_results cap."),
706
+ offset: offsetOut,
707
+ next_offset: nextOffsetOut,
689
708
  entities: z.array(
690
709
  z.object({
691
710
  code: z.string().nullable().describe('ICF code (e.g. "d450"); null for entries without a code.'),
@@ -695,7 +714,7 @@ var ICFSearchOutputSchema = z.object({
695
714
  uri: z.string().describe("WHO ICF entity URI; pass it to icf_lookup."),
696
715
  is_leaf: z.boolean().describe("True when the category has no subcategories.")
697
716
  })
698
- ).describe("Matching ICF entities in WHO relevance order, at most max_results.")
717
+ ).describe("Matching ICF entities in WHO relevance order, at most max_results, starting after `offset`.")
699
718
  });
700
719
  var ICFLookupOutputSchema = z.object({
701
720
  code: z.string().nullable().describe('ICF code (e.g. "d450"); null for chapters and blocks, which have a code_range instead.'),
@@ -711,7 +730,8 @@ var ICFLookupOutputSchema = z.object({
711
730
  });
712
731
  var LOINCSearchParamsSchema = z.object({
713
732
  query: z.string().min(1).describe("Search term (test name, keyword, or partial LOINC code)"),
714
- max_results: maxResults(25)
733
+ max_results: maxResults(25),
734
+ offset: offsetParam(LOINC_MAX_OFFSET)
715
735
  }).strict();
716
736
  var LOINCByCodeParamsSchema = z.object({
717
737
  loinc_num: LOINCNumberSchema.describe('LOINC number (e.g., "2339-0")')
@@ -738,7 +758,9 @@ var LOINCSearchOutputSchema = z.object({
738
758
  query: z.string().describe("The search term as submitted."),
739
759
  total_count: z.number().int().describe("Total number of LOINC terms matching the query at the source, which may exceed the items returned."),
740
760
  shown_count: z.number().int().describe("Number of terms returned in items (at most max_results)."),
741
- items: z.array(LOINCItemOutputSchema).describe("Matching LOINC terms in source relevance order.")
761
+ offset: offsetOut,
762
+ next_offset: nextOffsetOut.describe("`offset` that returns the next page with the same arguments; null at the end of the results, or past the first 7,500 (the most the source serves)."),
763
+ items: z.array(LOINCItemOutputSchema).describe("Matching LOINC terms in source relevance order, starting after `offset`.")
742
764
  });
743
765
  var LOINCDetailsOutputSchema = LOINCItemOutputSchema;
744
766
  var LOINCAnswersOutputSchema = z.object({
@@ -770,7 +792,8 @@ var LOINCPanelsOutputSchema = z.object({
770
792
  });
771
793
  var RxNormSearchParamsSchema = z.object({
772
794
  query: z.string().min(1).describe("Drug name to search (brand or generic)"),
773
- max_results: maxResults(25)
795
+ max_results: maxResults(25),
796
+ offset: offsetParam()
774
797
  }).strict();
775
798
  var RxNormConceptParamsSchema = z.object({
776
799
  rxcui: RxCUISchema.describe('RxNorm Concept Unique Identifier (string of digits or integer, e.g. "161" or 161)'),
@@ -794,10 +817,12 @@ var RxNormDrugOutputSchema = z.object({
794
817
  });
795
818
  var RxNormSearchOutputSchema = z.object({
796
819
  query: z.string().describe("The drug name as submitted."),
797
- total_count: z.number().int().describe("Number of concepts RxNav returned for the name, before the max_results cap."),
820
+ total_count: z.number().int().describe("Number of distinct concepts RxNav returned for the name, before the max_results cap."),
821
+ offset: offsetOut,
822
+ next_offset: nextOffsetOut,
798
823
  // tty === 'APPROX' on items signals the search used the approximate-match
799
824
  // fallback rather than an exact name match.
800
- drugs: z.array(RxNormDrugOutputSchema).describe('Matching RxNorm concepts, at most max_results. tty "APPROX" marks results of the approximate-match fallback, used when the name matched nothing exactly.')
825
+ drugs: z.array(RxNormDrugOutputSchema).describe('Matching RxNorm concepts, at most max_results, starting after `offset`. tty "APPROX" marks results of the approximate-match fallback, used when the name matched nothing exactly.')
801
826
  });
802
827
  var RxNormConceptOutputSchema = z.object({
803
828
  rxcui: z.string().describe("The RxCUI looked up."),
@@ -861,8 +886,15 @@ var MeSHSearchParamsSchema = z.object({
861
886
  language: SupportedLanguageSchema.optional().default("en").describe(
862
887
  "Language code (default: en). MeSH is published by NLM in English; another language is returned only where the NLM record carries it (rare), otherwise English. Never machine-translated."
863
888
  ),
864
- max_results: maxResults(25)
889
+ // The NLM lookup refuses limit > 50 with HTTP 400 ("must be less than or
890
+ // equal to 50", measured 2026-12-02): 51-100 used to fail at the source.
891
+ // The schema keeps 1-100 (narrowing it would break the declared surface);
892
+ // the handler asks for at most MESH_SOURCE_LIMIT and SAYS so.
893
+ max_results: maxResults(25).describe(
894
+ `Maximum number of results (1-100). Default: 25. The NLM lookup returns at most 50: above 50, 50 are asked for and the answer says so.`
895
+ )
865
896
  }).strict();
897
+ var MESH_SOURCE_LIMIT = 50;
866
898
  var MeSHByIdParamsSchema = z.object({
867
899
  mesh_id: MeSHIdSchema.describe("MeSH Descriptor ID (e.g., D015242, D003920)")
868
900
  }).strict();
@@ -884,7 +916,7 @@ var MeSHQualifierOutputSchema = z.object({
884
916
  var MeSHSearchOutputSchema = z.object({
885
917
  query: z.string().describe("The search term as submitted."),
886
918
  match: z.enum(["exact", "contains", "startswith"]).describe("Match type applied to descriptor labels."),
887
- total_count: z.number().int().describe("Number of descriptors returned (the NLM lookup is capped at max_results, so this is not a total count of all matches)."),
919
+ total_count: z.number().int().describe("Number of descriptors returned. The NLM lookup stops at max_results and has no offset, so this is not a count of all matches and there is no next page: when it equals max_results, narrow the query or use `match`."),
888
920
  matched_via: z.enum(["descriptor_label", "entry_term"]).describe('descriptor_label = the query matched descriptor labels; entry_term = no label matched, so the descriptors were reached through MeSH entry terms (synonyms such as "Heart Attack" for Myocardial Infarction).'),
889
921
  descriptors: z.array(
890
922
  z.object({
@@ -1358,6 +1390,7 @@ var CID10SearchParamsSchema = z.object({
1358
1390
  "Restrict search to 3-char categories, 4-char subcategories, or both. Default: all"
1359
1391
  ),
1360
1392
  max_results: maxResults(25),
1393
+ offset: offsetParam(),
1361
1394
  within: withinSchema(
1362
1395
  'Only search these branches of CID-10 (up to 10): a chapter number ("5" = F00-F99), a range of categories ("F30-F39"; both ends must exist) or a category / subcategory code ("F32", "F32.1" \u2014 a category keeps its subcategories). A branch that does not exist is an error, never a silent unbounded search.'
1363
1396
  )
@@ -1405,6 +1438,8 @@ var CID10SearchOutputSchema = z.object({
1405
1438
  within: z.array(WithinBranchSchema).describe("The branches that bounded the search, resolved in the bundled dataset (uri is always null); empty when the search was unbounded."),
1406
1439
  total_count: z.number().int().describe("Number of CID-10 codes matching the query, before the max_results cap."),
1407
1440
  shown_count: z.number().int().describe("Number of codes returned in hits (at most max_results)."),
1441
+ offset: offsetOut,
1442
+ next_offset: nextOffsetOut,
1408
1443
  hits: z.array(CID10HitSchema).describe("Matching CID-10 V2008 codes with their Portuguese titles, chapter and group."),
1409
1444
  // Present only when a query word was translated to the CID-10's own wording
1410
1445
  // ("câncer" → "neoplasia maligna"); says which (src/clients/cid10-vocabulary.ts).
@@ -2325,6 +2360,20 @@ function getWHOClient() {
2325
2360
  return whoClientInstance;
2326
2361
  }
2327
2362
 
2363
+ // src/utils/page.ts
2364
+ function showingRange(offset, shown) {
2365
+ return offset === 0 ? `top ${shown}` : `${offset + 1}\u2013${offset + shown}`;
2366
+ }
2367
+ function nextPageLine(offset, shown, total, next) {
2368
+ if (next === null) return "";
2369
+ return `
2370
+
2371
+ _Showing results ${offset + 1}\u2013${offset + shown} of ${total}. Next page: call again with \`offset: ${next}\`._`;
2372
+ }
2373
+ function pastTheEndText(query, system, offset, total) {
2374
+ return `No results at offset ${offset} for "${query}" in ${system}: the search matched ${total}, so the last page starts before offset ${total}.`;
2375
+ }
2376
+
2328
2377
  // src/provenance.ts
2329
2378
  import { z as z3 } from "zod";
2330
2379
  import {
@@ -2880,11 +2929,14 @@ async function handleICD11Search(args) {
2880
2929
  return falhaDaFonte(`Search error: ${results.errorMessage || "Unknown error"}`);
2881
2930
  }
2882
2931
  const destEntities = results.destinationEntities ?? [];
2883
- const top = destEntities.slice(0, params.max_results);
2932
+ const top = destEntities.slice(params.offset, params.offset + params.max_results);
2933
+ const next = nextOffset(params.offset, top.length, destEntities.length);
2884
2934
  const structured = {
2885
2935
  query: params.query,
2886
2936
  within,
2887
2937
  total_count: destEntities.length,
2938
+ offset: params.offset,
2939
+ next_offset: next,
2888
2940
  entities: top.map((e) => ({
2889
2941
  code: e.theCode ?? null,
2890
2942
  title: e.title,
@@ -2901,19 +2953,19 @@ async function handleICD11Search(args) {
2901
2953
  };
2902
2954
  if (top.length === 0) {
2903
2955
  return provenancedResult({
2904
- text: `No results found for "${params.query}" in ICD-11${withinLabel(within)}.`,
2956
+ text: destEntities.length > 0 ? pastTheEndText(params.query, `ICD-11${withinLabel(within)}`, params.offset, destEntities.length) : `No results found for "${params.query}" in ICD-11${withinLabel(within)}.`,
2905
2957
  structured,
2906
2958
  provenance: icd11Provenance()
2907
2959
  });
2908
2960
  }
2909
- const formatted = top.map((entity, index) => formatSearchResult(entity, index)).join("\n\n");
2961
+ const formatted = top.map((entity, index) => formatSearchResult(entity, params.offset + index)).join("\n\n");
2910
2962
  const header = `## ICD-11 Search Results for "${params.query}"${withinLabel(within)}
2911
2963
 
2912
- Found ${destEntities.length} results (showing top ${top.length}):
2964
+ Found ${destEntities.length} results (showing ${showingRange(params.offset, top.length)}):
2913
2965
 
2914
2966
  `;
2915
2967
  return provenancedResult({
2916
- text: header + formatted,
2968
+ text: header + formatted + nextPageLine(params.offset, top.length, destEntities.length, next),
2917
2969
  structured,
2918
2970
  provenance: icd11Provenance()
2919
2971
  });
@@ -3212,11 +3264,14 @@ async function handleICFSearch(args) {
3212
3264
  return falhaDaFonte(`Search error: ${results.errorMessage || "Unknown error"}`);
3213
3265
  }
3214
3266
  const dest = results.destinationEntities ?? [];
3215
- const top = dest.slice(0, params.max_results);
3267
+ const top = dest.slice(params.offset, params.offset + params.max_results);
3268
+ const next = nextOffset(params.offset, top.length, dest.length);
3216
3269
  const structured = {
3217
3270
  query: params.query,
3218
3271
  within,
3219
3272
  total_count: dest.length,
3273
+ offset: params.offset,
3274
+ next_offset: next,
3220
3275
  entities: top.map((e) => ({
3221
3276
  code: e.theCode || null,
3222
3277
  title: plainTitle(e.title),
@@ -3229,22 +3284,22 @@ async function handleICFSearch(args) {
3229
3284
  const bound = within.length > 0 ? ` within ${within.map((b) => `${b.code ?? b.value} ${b.title}`).join("; ")}` : "";
3230
3285
  if (top.length === 0) {
3231
3286
  return provenancedResult({
3232
- text: `No results found for "${params.query}" in ICF${bound}.`,
3287
+ text: dest.length > 0 ? pastTheEndText(params.query, `ICF${bound}`, params.offset, dest.length) : `No results found for "${params.query}" in ICF${bound}.`,
3233
3288
  structured,
3234
3289
  provenance: icfProvenance()
3235
3290
  });
3236
3291
  }
3237
3292
  const body = structured.entities.map((e, i) => {
3238
3293
  const comp = e.component ? ` (${COMPONENT_LABEL[e.component]})` : "";
3239
- return `${i + 1}. **${e.code ?? "No code"}** - ${e.title}${comp}
3294
+ return `${params.offset + i + 1}. **${e.code ?? "No code"}** - ${e.title}${comp}
3240
3295
  Score: ${e.score.toFixed(2)} | Leaf: ${e.is_leaf ? "Yes" : "No"}`;
3241
3296
  }).join("\n\n");
3242
3297
  return provenancedResult({
3243
3298
  text: `## ICF Search Results for "${params.query}"${bound}
3244
3299
 
3245
- Found ${dest.length} results (showing top ${top.length}):
3300
+ Found ${dest.length} results (showing ${showingRange(params.offset, top.length)}):
3246
3301
 
3247
- ${body}`,
3302
+ ${body}${nextPageLine(params.offset, top.length, dest.length, next)}`,
3248
3303
  structured,
3249
3304
  provenance: icfProvenance()
3250
3305
  });
@@ -3369,18 +3424,20 @@ var NLMClient = class {
3369
3424
  *
3370
3425
  * @param query - Search term
3371
3426
  * @param maxResults - Maximum results to return (default: 25)
3427
+ * @param offset - Results to skip (pagination; default 0)
3372
3428
  * @returns Array of LOINC items
3373
3429
  */
3374
- async searchLOINC(query, maxResults2 = 25) {
3375
- const cacheKey = `loinc:search:${query}:${maxResults2}`;
3430
+ async searchLOINC(query, maxResults2 = 25, offset = 0) {
3431
+ const cacheKey = `loinc:search:${query}:${maxResults2}:${offset}`;
3376
3432
  return cache.getOrSet(
3377
3433
  CACHE_PREFIX.LOINC,
3378
3434
  cacheKey,
3379
3435
  async () => {
3380
3436
  const url = `${NLM_CONFIG.clinicalTablesUrl}/loinc_items/v3/search`;
3437
+ const page = offset === 0 ? { maxList: maxResults2 } : { count: maxResults2, offset };
3381
3438
  const response = await this.request(url, {
3382
3439
  terms: query,
3383
- maxList: maxResults2,
3440
+ ...page,
3384
3441
  df: DEFAULT_LOINC_FIELDS.join(","),
3385
3442
  // LOINC License §10: terms with third-party copyright must carry
3386
3443
  // their notice — request it and pass it through verbatim.
@@ -3730,28 +3787,37 @@ async function handleLOINCSearch(args) {
3730
3787
  try {
3731
3788
  const params = LOINCSearchParamsSchema.parse(args);
3732
3789
  const client = getNLMClient();
3733
- const results = await client.searchLOINC(params.query, params.max_results);
3790
+ const results = await client.searchLOINC(params.query, params.max_results, params.offset);
3791
+ const shown = results.items.length;
3792
+ const reachable = Math.min(results.totalCount, LOINC_MAX_OFFSET + 100);
3793
+ const candidate2 = nextOffset(params.offset, shown, reachable);
3794
+ const next = candidate2 !== null && candidate2 <= LOINC_MAX_OFFSET ? candidate2 : null;
3734
3795
  const structured = {
3735
3796
  query: params.query,
3736
3797
  total_count: results.totalCount,
3737
- shown_count: results.items.length,
3798
+ shown_count: shown,
3799
+ offset: params.offset,
3800
+ next_offset: next,
3738
3801
  items: results.items.map(loincItemToOutput)
3739
3802
  };
3740
- if (results.items.length === 0) {
3803
+ if (shown === 0) {
3741
3804
  return provenancedResult({
3742
- text: `No LOINC codes found for "${params.query}".`,
3805
+ text: results.totalCount > 0 ? pastTheEndText(params.query, "LOINC", params.offset, results.totalCount) : `No LOINC codes found for "${params.query}".`,
3743
3806
  structured,
3744
3807
  provenance: loincProvenance()
3745
3808
  });
3746
3809
  }
3747
- const formatted = results.items.map((item, index) => formatLOINCItem(item, index)).join("\n\n");
3810
+ const formatted = results.items.map((item, index) => formatLOINCItem(item, params.offset + index)).join("\n\n");
3748
3811
  const header = `## LOINC Search Results for "${params.query}"
3749
3812
 
3750
- Found ${results.totalCount} total results (showing ${results.items.length}):
3813
+ Found ${results.totalCount} total results (showing ${params.offset === 0 ? shown : showingRange(params.offset, shown)}):
3751
3814
 
3752
3815
  `;
3816
+ const ceiling = next === null && params.offset + shown < results.totalCount ? `
3817
+
3818
+ _The source serves only the first ${LOINC_MAX_OFFSET + 100} of the ${results.totalCount} results: narrow the query to reach the rest._` : "";
3753
3819
  return provenancedResult({
3754
- text: header + formatted,
3820
+ text: header + formatted + nextPageLine(params.offset, shown, results.totalCount, next) + ceiling,
3755
3821
  structured,
3756
3822
  provenance: loincProvenance()
3757
3823
  });
@@ -4401,6 +4467,7 @@ function getRxNormClient() {
4401
4467
  }
4402
4468
 
4403
4469
  // src/tools/rxnorm.ts
4470
+ var APPROX_POOL = 100;
4404
4471
  var rxnormProvenance = () => medicalProvenance("NLM_RXNAV");
4405
4472
  var rxnormSearchTool = {
4406
4473
  name: "rxnorm_search",
@@ -4612,10 +4679,12 @@ async function handleRxNormSearch(args) {
4612
4679
  const client = getRxNormClient();
4613
4680
  let result = await client.searchDrugs(params.query);
4614
4681
  if (result.drugs.length === 0) {
4615
- const approxMatches = await client.getApproximateMatch(params.query, params.max_results);
4616
- if (approxMatches.length > 0) {
4682
+ const approxMatches = await client.getApproximateMatch(params.query, APPROX_POOL);
4683
+ const seen = /* @__PURE__ */ new Set();
4684
+ const distinct = approxMatches.filter((m) => !seen.has(m.rxcui) && seen.add(m.rxcui));
4685
+ if (distinct.length > 0) {
4617
4686
  result = {
4618
- drugs: approxMatches.map((m) => ({
4687
+ drugs: distinct.map((m) => ({
4619
4688
  rxcui: m.rxcui,
4620
4689
  name: m.name,
4621
4690
  synonym: "",
@@ -4625,10 +4694,13 @@ async function handleRxNormSearch(args) {
4625
4694
  };
4626
4695
  }
4627
4696
  }
4628
- const drugsCapped = result.drugs.slice(0, params.max_results);
4697
+ const drugsCapped = result.drugs.slice(params.offset, params.offset + params.max_results);
4698
+ const next = nextOffset(params.offset, drugsCapped.length, result.drugs.length);
4629
4699
  const structured = {
4630
4700
  query: params.query,
4631
4701
  total_count: result.drugs.length,
4702
+ offset: params.offset,
4703
+ next_offset: next,
4632
4704
  drugs: drugsCapped.map((d) => ({
4633
4705
  rxcui: d.rxcui,
4634
4706
  name: d.name,
@@ -4637,21 +4709,21 @@ async function handleRxNormSearch(args) {
4637
4709
  language: d.language
4638
4710
  }))
4639
4711
  };
4640
- if (result.drugs.length === 0) {
4712
+ if (drugsCapped.length === 0) {
4641
4713
  return provenancedResult({
4642
- text: `No drugs found for "${params.query}".`,
4714
+ text: result.drugs.length > 0 ? pastTheEndText(params.query, "RxNorm", params.offset, result.drugs.length) : `No drugs found for "${params.query}".`,
4643
4715
  structured,
4644
4716
  provenance: rxnormProvenance()
4645
4717
  });
4646
4718
  }
4647
- const formatted = drugsCapped.map((drug, index) => formatDrug(drug, index)).join("\n\n");
4719
+ const formatted = drugsCapped.map((drug, index) => formatDrug(drug, params.offset + index)).join("\n\n");
4648
4720
  const header = `## RxNorm Search Results for "${params.query}"
4649
4721
 
4650
4722
  Found ${result.drugs.length} result(s):
4651
4723
 
4652
4724
  `;
4653
4725
  return provenancedResult({
4654
- text: header + formatted,
4726
+ text: header + formatted + nextPageLine(params.offset, drugsCapped.length, result.drugs.length, next),
4655
4727
  structured,
4656
4728
  provenance: rxnormProvenance()
4657
4729
  });
@@ -5106,21 +5178,21 @@ var MeSHClient = class {
5106
5178
  async fetchTermLabel(uri, language) {
5107
5179
  const lang = language ?? "en";
5108
5180
  const cacheKey = `mesh:term:label:${uri}:${lang}`;
5109
- return cache.getOrSet(
5110
- CACHE_PREFIX.MESH,
5111
- cacheKey,
5112
- async () => {
5113
- try {
5114
- const path = uriToPath(uri);
5115
- if (!path) return "";
5181
+ const path = uriToPath(uri);
5182
+ if (!path) return "";
5183
+ try {
5184
+ return await cache.getOrSet(
5185
+ CACHE_PREFIX.MESH,
5186
+ cacheKey,
5187
+ async () => {
5116
5188
  const raw = await this.request(path, {}, language);
5117
5189
  return this.extractValue(raw?.prefLabel, language) || this.extractValue(raw?.label, language);
5118
- } catch {
5119
- return "";
5120
- }
5121
- },
5122
- DEFAULT_TTL.STATIC
5123
- );
5190
+ },
5191
+ DEFAULT_TTL.STATIC
5192
+ );
5193
+ } catch {
5194
+ return "";
5195
+ }
5124
5196
  }
5125
5197
  /**
5126
5198
  * Fetches a tree number resource. The "label" of a tree number IS the
@@ -5130,21 +5202,22 @@ var MeSHClient = class {
5130
5202
  async fetchTreeNumberLabel(uri, language) {
5131
5203
  const lang = language ?? "en";
5132
5204
  const cacheKey = `mesh:tree:label:${uri}:${lang}`;
5133
- return cache.getOrSet(
5134
- CACHE_PREFIX.MESH,
5135
- cacheKey,
5136
- async () => {
5137
- try {
5138
- const path = uriToPath(uri);
5139
- if (!path) return "";
5205
+ const path = uriToPath(uri);
5206
+ if (!path) return "";
5207
+ try {
5208
+ const label = await cache.getOrSet(
5209
+ CACHE_PREFIX.MESH,
5210
+ cacheKey,
5211
+ async () => {
5140
5212
  const raw = await this.request(path, {}, language);
5141
5213
  return this.extractValue(raw?.label, language);
5142
- } catch {
5143
- return "";
5144
- }
5145
- },
5146
- DEFAULT_TTL.STATIC
5147
- );
5214
+ },
5215
+ DEFAULT_TTL.STATIC
5216
+ );
5217
+ return label || treeNumberFromUri(uri);
5218
+ } catch {
5219
+ return treeNumberFromUri(uri);
5220
+ }
5148
5221
  }
5149
5222
  /**
5150
5223
  * Fetches a qualifier's label. STATIC TTL — qualifiers are part of
@@ -5154,23 +5227,23 @@ var MeSHClient = class {
5154
5227
  async fetchQualifierLabel(qualifierId, language) {
5155
5228
  const lang = language ?? "en";
5156
5229
  const cacheKey = `mesh:qlabel:${qualifierId}:${lang}`;
5157
- return cache.getOrSet(
5158
- CACHE_PREFIX.MESH,
5159
- cacheKey,
5160
- async () => {
5161
- try {
5230
+ try {
5231
+ return await cache.getOrSet(
5232
+ CACHE_PREFIX.MESH,
5233
+ cacheKey,
5234
+ async () => {
5162
5235
  const raw = await this.request(
5163
5236
  `/${qualifierId}.json`,
5164
5237
  {},
5165
5238
  language
5166
5239
  );
5167
5240
  return this.extractValue(raw?.label, language);
5168
- } catch {
5169
- return "";
5170
- }
5171
- },
5172
- DEFAULT_TTL.STATIC
5173
- );
5241
+ },
5242
+ DEFAULT_TTL.STATIC
5243
+ );
5244
+ } catch {
5245
+ return "";
5246
+ }
5174
5247
  }
5175
5248
  // ===========================================================================
5176
5249
  // Internal: resolvers (fan-out across multiple sub-resources in parallel)
@@ -5264,6 +5337,10 @@ function toUriArray(v) {
5264
5337
  if (Array.isArray(v)) return v.filter((x) => typeof x === "string");
5265
5338
  return [];
5266
5339
  }
5340
+ function treeNumberFromUri(uri) {
5341
+ const tail = uri.replace(/^https?:\/\/id\.nlm\.nih\.gov\/mesh\//, "");
5342
+ return /^[A-Z]\d{2}(\.\d{3})*$/.test(tail) ? tail : "";
5343
+ }
5267
5344
  function uriToPath(uri) {
5268
5345
  if (!uri) return "";
5269
5346
  const stripped = uri.replace(/^https?:\/\/id\.nlm\.nih\.gov\/mesh/, "");
@@ -5292,7 +5369,9 @@ Use this tool to:
5292
5369
 
5293
5370
  NLM publishes MeSH in English: the search matches and returns English labels whatever \`language\` says (a handful of records also carry other languages \u2014 13 Portuguese labels in the whole dataset, measured 2026-11-28 \u2014 and mesh_descriptor returns those). Content is never machine-translated.
5294
5371
 
5295
- Returns matching descriptors with MeSH IDs and labels. When no descriptor LABEL matches (lay words such as "heart attack" or "bedsore"), the search falls back to MeSH entry terms and says so (\`matched_via: "entry_term"\`, with the \`matched_term\` per descriptor) \u2014 that fallback takes a few seconds. Not applied with \`match: "exact"\`.`,
5372
+ Returns matching descriptors with MeSH IDs and labels. When no descriptor LABEL matches (lay words such as "heart attack" or "bedsore"), the search falls back to MeSH entry terms and says so (\`matched_via: "entry_term"\`, with the \`matched_term\` per descriptor) \u2014 that fallback takes a few seconds. Not applied with \`match: "exact"\`.
5373
+
5374
+ No pagination: the NLM lookup returns at most 50 descriptors and has no offset. When \`total_count\` equals \`max_results\` there may be more \u2014 narrow the query or use \`match: "startswith"\` / \`"exact"\`.`,
5296
5375
  inputSchema: buildInputSchema(MeSHSearchParamsSchema),
5297
5376
  outputSchema: buildOutputSchema(withProvenance(MeSHSearchOutputSchema)),
5298
5377
  annotations: READ_ONLY_TOOL_ANNOTATIONS
@@ -5473,10 +5552,11 @@ async function handleMeSHSearch(args) {
5473
5552
  try {
5474
5553
  const params = MeSHSearchParamsSchema.parse(args);
5475
5554
  const client = getMeSHClient();
5555
+ const capped = params.max_results > MESH_SOURCE_LIMIT;
5476
5556
  let results = await client.searchDescriptors(
5477
5557
  params.query,
5478
5558
  params.match,
5479
- params.max_results,
5559
+ Math.min(params.max_results, MESH_SOURCE_LIMIT),
5480
5560
  params.language
5481
5561
  );
5482
5562
  let matchedVia = "descriptor_label";
@@ -5500,7 +5580,9 @@ async function handleMeSHSearch(args) {
5500
5580
  }))
5501
5581
  };
5502
5582
  return provenancedResult({
5503
- text: formatSearchResults(params.query, results),
5583
+ text: formatSearchResults(params.query, results) + (capped && matchedVia === "descriptor_label" && results.length >= MESH_SOURCE_LIMIT ? `
5584
+
5585
+ _Asked for ${params.max_results}; the NLM lookup returns at most ${MESH_SOURCE_LIMIT} descriptors and has no next page \u2014 narrow the query or use \`match\` to reach others._` : ""),
5504
5586
  structured,
5505
5587
  provenance: meshProvenance()
5506
5588
  });
@@ -5829,7 +5911,7 @@ var CID10Client = class {
5829
5911
  * had to appear verbatim: "câncer de mama" returned zero against "Neoplasia
5830
5912
  * maligna da mama". `notes` says when a word was translated.
5831
5913
  */
5832
- search(query, level2, maxResults2, branches = []) {
5914
+ search(query, level2, maxResults2, branches = [], offset = 0) {
5833
5915
  const expanded = expandQuery(query);
5834
5916
  if (expanded.length === 0) {
5835
5917
  return { totalCount: 0, hits: [], notes: [] };
@@ -5847,7 +5929,7 @@ var CID10Client = class {
5847
5929
  }
5848
5930
  }
5849
5931
  const kept = branches.length > 0 ? all.filter((h) => branches.some((b) => inBranch(h.code, b))) : all;
5850
- return { totalCount: kept.length, hits: kept.slice(0, maxResults2), notes: vocabularyNotes(expanded) };
5932
+ return { totalCount: kept.length, hits: kept.slice(offset, offset + maxResults2), notes: vocabularyNotes(expanded) };
5851
5933
  }
5852
5934
  /**
5853
5935
  * Resolves a `within` value of cid10_search to a branch (PROGRESS.md 24.4b):
@@ -7578,19 +7660,30 @@ async function handleCID10Search(args) {
7578
7660
  params.query,
7579
7661
  params.level,
7580
7662
  params.max_results,
7581
- branches
7663
+ branches,
7664
+ params.offset
7582
7665
  );
7666
+ const next = nextOffset(params.offset, hits.length, totalCount);
7583
7667
  const structured = {
7584
7668
  query: params.query,
7585
7669
  level: params.level,
7586
7670
  within: branches.map((b) => ({ value: b.value, code: b.code, title: b.title, uri: null })),
7587
7671
  total_count: totalCount,
7588
7672
  shown_count: hits.length,
7673
+ offset: params.offset,
7674
+ next_offset: next,
7589
7675
  hits,
7590
7676
  ...notes.length > 0 ? { vocabulary_notes: notes } : {}
7591
7677
  };
7592
7678
  const notesText = notes.map((n) => `_${n}_
7593
7679
  `).join("");
7680
+ if (hits.length === 0 && totalCount > 0) {
7681
+ return provenancedResult({
7682
+ text: `Nenhum resultado no deslocamento (offset) ${params.offset} para "${params.query}": a busca casou ${totalCount} c\xF3digos, ent\xE3o a \xFAltima p\xE1gina come\xE7a antes de ${totalCount}.`,
7683
+ structured,
7684
+ provenance: cid10Provenance()
7685
+ });
7686
+ }
7594
7687
  if (hits.length === 0) {
7595
7688
  return provenancedResult({
7596
7689
  text: `Nenhum c\xF3digo CID-10 encontrado para "${params.query}".
@@ -7602,12 +7695,15 @@ async function handleCID10Search(args) {
7602
7695
  }
7603
7696
  const header = `## Resultados CID-10 para "${params.query}"
7604
7697
 
7605
- Total: ${totalCount} (mostrando ${hits.length}, escopo: ${params.level}).
7698
+ Total: ${totalCount} (mostrando ${params.offset === 0 ? hits.length : `${params.offset + 1}\u2013${params.offset + hits.length}`}, escopo: ${params.level}).
7606
7699
 
7607
7700
  ` + (notesText ? notesText + "\n" : "");
7608
- const body = hits.map((h, i) => `${i + 1}. ${formatHit(h)}`).join("\n\n");
7701
+ const body = hits.map((h, i) => `${params.offset + i + 1}. ${formatHit(h)}`).join("\n\n");
7702
+ const nextLine = next === null ? "" : `
7703
+
7704
+ _Mostrando ${params.offset + 1}\u2013${params.offset + hits.length} de ${totalCount}. Pr\xF3xima p\xE1gina: chame de novo com \`offset: ${next}\`._`;
7609
7705
  return provenancedResult({
7610
- text: header + body,
7706
+ text: header + body + nextLine,
7611
7707
  structured,
7612
7708
  provenance: cid10Provenance()
7613
7709
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "medical-terminologies-mcp",
3
3
  "mcpName": "io.github.SidneyBissoli/medical-terminologies-mcp",
4
- "version": "4.3.2",
4
+ "version": "4.4.0",
5
5
  "description": "Unified MCP server for seven medical terminologies (ICD-11, ICF, LOINC, RxNorm, MeSH, ATC, CID-10) with authoritative WHO ICD-10→ICD-11 mapping. 37 tools, hosted endpoint available, MIT.",
6
6
  "author": "Sidney da Silva Pereira Bissoli",
7
7
  "license": "MIT",
@@ -55,7 +55,9 @@
55
55
  "typecheck": "tsc --noEmit",
56
56
  "prepublishOnly": "npm run build",
57
57
  "build:worker-lib": "esbuild src/worker-lib.ts --bundle --platform=browser --target=es2022 --format=esm --outfile=dist/worker-lib.js --tree-shaking=false --conditions=workerd,browser --define:process.env.NODE_ENV=\\\"production\\\" --external:node:* --external:cloudflare:* --external:@modelcontextprotocol/* --external:zod --alias:events=node:events --alias:stream=node:stream --alias:buffer=node:buffer --alias:util=node:util --alias:path=node:path --alias:os=node:os --alias:fs=node:fs --alias:url=node:url --alias:crypto=node:crypto",
58
- "manifest:lhm": "node scripts/gen-lhm-manifest.mjs"
58
+ "manifest:lhm": "node scripts/gen-lhm-manifest.mjs",
59
+ "fixtures:record": "tsx scripts/record-tool-fixtures.ts",
60
+ "eval:answers": "tsx src/evals/run-answers.ts"
59
61
  },
60
62
  "dependencies": {
61
63
  "@modelcontextprotocol/server": "^2.0.0",
@@ -67,9 +69,10 @@
67
69
  },
68
70
  "devDependencies": {
69
71
  "@modelcontextprotocol/client": "^2.0.0",
70
- "@sbissoli/mcp-evals": "^0.2.1",
72
+ "@sbissoli/mcp-evals": "^0.3.0",
71
73
  "@sbissoli/mcp-live-source": "^0.5.0",
72
74
  "@sbissoli/mcp-surface": "^0.6.0",
75
+ "@sbissoli/mcp-tool-tests": "^0.2.0",
73
76
  "@types/node": "^26.5.1",
74
77
  "esbuild": "^0.28.2",
75
78
  "nock": "^15.0.1",