brainx-skill 1.0.12 → 1.0.14

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 (226) hide show
  1. package/README.md +30 -0
  2. package/installation/lib/bundle.js +51 -13
  3. package/installation/lib/cli.js +16 -4
  4. package/installation/lib/literature-mcp.js +536 -0
  5. package/manifest.json +4 -0
  6. package/mcp-servers/codex/README.md +82 -0
  7. package/mcp-servers/codex/UPSTREAM.md +22 -0
  8. package/mcp-servers/codex/server.mjs +142 -0
  9. package/mcp-servers/codex/skills.json +10 -0
  10. package/mcp-servers/codex/system-prompt.md +73 -0
  11. package/mcp-servers/codex/test/fixtures/fake-codex.mjs +6 -0
  12. package/mcp-servers/codex/test/server.test.mjs +99 -0
  13. package/mcp-servers/fulltext-resolver/README.md +136 -0
  14. package/mcp-servers/fulltext-resolver/REUSE.md +32 -0
  15. package/mcp-servers/fulltext-resolver/THIRD_PARTY_NOTICES.md +57 -0
  16. package/mcp-servers/fulltext-resolver/server.mjs +128 -0
  17. package/mcp-servers/fulltext-resolver/src/document.mjs +253 -0
  18. package/mcp-servers/fulltext-resolver/src/http.mjs +173 -0
  19. package/mcp-servers/fulltext-resolver/src/identifiers.mjs +123 -0
  20. package/mcp-servers/fulltext-resolver/src/model.mjs +105 -0
  21. package/mcp-servers/fulltext-resolver/src/resolver.mjs +305 -0
  22. package/mcp-servers/fulltext-resolver/src/sources/biorxiv.mjs +135 -0
  23. package/mcp-servers/fulltext-resolver/src/sources/europe-pmc.mjs +132 -0
  24. package/mcp-servers/fulltext-resolver/src/sources/openalex.mjs +165 -0
  25. package/mcp-servers/fulltext-resolver/test/document.test.mjs +82 -0
  26. package/mcp-servers/fulltext-resolver/test/resolver.test.mjs +287 -0
  27. package/mcp-servers/fulltext-resolver/test/server.test.mjs +63 -0
  28. package/mcp-servers/fulltext-resolver/test/sources.test.mjs +229 -0
  29. package/package.json +14 -10
  30. package/skills/bio-neuro-lit/SKILL.md +206 -0
  31. package/skills/bio-neuro-lit/THIRD_PARTY_NOTICES.md +34 -0
  32. package/skills/bio-neuro-lit/agents/openai.yaml +4 -0
  33. package/skills/bio-neuro-lit/references/tool-contracts.md +73 -0
  34. package/skills/bio-neuro-lit/scripts/deepxiv_fetch.py +110 -0
  35. package/skills/bio-neuro-lit/scripts/exa_search.py +190 -0
  36. package/skills/brainx-acceleration/SKILL.md +459 -0
  37. package/skills/brainx-general-guard/SKILL.md +31 -9
  38. package/skills/brainx-modeling-loop/SKILL.md +281 -0
  39. package/skills/brainx-modeling-loop/agents/openai.yaml +4 -0
  40. package/skills/brainx-modeling-loop/references/monitor-experiment.md +49 -0
  41. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow/scripts/fitting_hh_neuron.py +254 -0
  42. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +272 -0
  43. package/skills/brainx-modeling-loop/references/run-experiment.md +179 -0
  44. package/skills/brainx-modeling-loop/references/training-workflow.md +270 -0
  45. package/skills/brainx-visualization/SKILL.md +157 -0
  46. package/skills/brainx-visualization/agents/openai.yaml +4 -0
  47. package/skills/brainx-visualization/references/interactive-and-visualization-styling.md +155 -0
  48. package/skills/brainx-visualization/references/neural-data-visualization.md +141 -0
  49. package/skills/brainx-visualization/references/statistical-and-model-visualization.md +133 -0
  50. package/skills/{braincell → package-skills/braincell}/SKILL.md +17 -6
  51. package/skills/package-skills/braincell/references/braintools/input-current.md +200 -0
  52. package/skills/package-skills/braincell/references/braintools/optimizer.md +179 -0
  53. package/skills/{braincell → package-skills/braincell}/references/multicompartment/multicompartment-cell-workflow.md +2 -2
  54. package/skills/package-skills/braincell/references/scripts/fitting_hh_neuron.py +254 -0
  55. package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-constraints-regularization.md +1 -1
  56. package/skills/{brainmass → package-skills/brainmass}/references/coupling-network-api.md +121 -3
  57. package/skills/{brainmass → package-skills/brainmass}/references/modellibrary.md +79 -1
  58. package/skills/package-skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +188 -0
  59. package/skills/{brainmass → package-skills/brainmass}/references/visualization-analysis-api.md +6 -6
  60. package/skills/{brainpy-state → package-skills/brainpy-state}/SKILL.md +4 -3
  61. package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/connectivity.md +1 -1
  62. package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/input-current.md +1 -1
  63. package/skills/package-skills/brainpy-state/references/braintools/metric.md +152 -0
  64. package/skills/package-skills/brainpy-state/references/perturbation-experiment-validity.md +76 -0
  65. package/skills/{brainpy-state → package-skills/brainpy-state}/references/projection-patterns.md +1 -1
  66. package/skills/{brainstate → package-skills/brainstate}/SKILL.md +1 -0
  67. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  68. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-constraints-regularization.md +1 -1
  69. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/randomness-and-reproducibility.md +1 -1
  70. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-grad-expansion.md +2 -2
  71. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-vmap-expansion.md +1 -1
  72. package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-layer-library.md +1 -1
  73. package/skills/package-skills/brainstate/references/paired-perturbation-execution.md +113 -0
  74. package/skills/package-skills/braintrace/SKILL.md +187 -0
  75. package/skills/package-skills/braintrace/references/Drtrl.md +133 -0
  76. package/skills/{braintrace → package-skills/braintrace}/references/ETP operators.md +31 -4
  77. package/skills/package-skills/braintrace/references/algorithm selection.md +64 -0
  78. package/skills/package-skills/braintrace/references/batching.md +140 -0
  79. package/skills/{braintrace → package-skills/braintrace}/references/compiler_internal.md +2 -2
  80. package/skills/{braintrace → package-skills/braintrace}/references/custom algorithms.md +8 -10
  81. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +179 -0
  82. package/skills/{braintrace → package-skills/braintrace}/references/pre-built-braintrace-layer.md +2 -2
  83. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +0 -130
  84. package/skills/braintrace/SKILL.md +0 -161
  85. package/skills/braintrace/references/Drtrl.md +0 -179
  86. package/skills/braintrace/references/algorithm selection.md +0 -120
  87. package/skills/braintrace/references/batching.md +0 -150
  88. package/skills/braintrace/references/pp_pprop workflow.md +0 -196
  89. /package/skills/{braincell → package-skills/braincell}/references/area-scaled-hh-pattern.md +0 -0
  90. /package/skills/{braincell → package-skills/braincell}/references/braincell-custom-ion-channel-authoring.md +0 -0
  91. /package/skills/{brainpy-state → package-skills/braincell}/references/braintools/metric.md +0 -0
  92. /package/skills/{braincell → package-skills/braincell}/references/channel-library.md +0 -0
  93. /package/skills/{braincell → package-skills/braincell}/references/ion-library.md +0 -0
  94. /package/skills/{braincell → package-skills/braincell}/references/mixions-for-adaptation.md +0 -0
  95. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/braincell-manual-morphology-construction.md +0 -0
  96. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/cv-policy-reference.md +0 -0
  97. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/filter-function-library.md +0 -0
  98. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/morphology-io-loading-validation.md +0 -0
  99. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/probe-reference.md +0 -0
  100. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/topology-building-and-visualization.md +0 -0
  101. /package/skills/{braincell → package-skills/braincell}/references/scripts/calcium_channel_gating.py +0 -0
  102. /package/skills/{braincell → package-skills/braincell}/references/scripts/cell_multicompartment_reference.py +0 -0
  103. /package/skills/{braincell → package-skills/braincell}/references/scripts/channel_ablation.py +0 -0
  104. /package/skills/{braincell → package-skills/braincell}/references/scripts/fi_curve.py +0 -0
  105. /package/skills/{braincell → package-skills/braincell}/references/scripts/hh_neuron_basics.py +0 -0
  106. /package/skills/{braincell → package-skills/braincell}/references/scripts/spike_frequency_adaptation.py +0 -0
  107. /package/skills/{braincell → package-skills/braincell}/references/scripts/t_current_rebound.py +0 -0
  108. /package/skills/{braincell → package-skills/braincell}/references/scripts/thalamic_neurons.py +0 -0
  109. /package/skills/{braincell → package-skills/braincell}/references/solver-library-with-effects.md +0 -0
  110. /package/skills/{brainevent → package-skills/brainevent}/SKILL.md +0 -0
  111. /package/skills/{brainevent → package-skills/brainevent}/references/connectivity-variants.md +0 -0
  112. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-cpu.md +0 -0
  113. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-gpu.md +0 -0
  114. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/102_EI_net_1996.py +0 -0
  115. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/204_joglekar_2018_propagation.py +0 -0
  116. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/coba_ei_teaching.py +0 -0
  117. /package/skills/{brainevent → package-skills/brainevent}/references/sparse-formats.md +0 -0
  118. /package/skills/{brainevent → package-skills/brainevent}/references/synaptic-plasticity.md +0 -0
  119. /package/skills/{brainmass → package-skills/brainmass}/SKILL.md +0 -0
  120. /package/skills/{brainmass → package-skills/brainmass}/references/batch-transform-acceleration.md +0 -0
  121. /package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  122. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/cogtask.md +0 -0
  123. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/data-preprocessing.md +0 -0
  124. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/metric.md +0 -0
  125. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/optimizer.md +0 -0
  126. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/parameter-initializer.md +0 -0
  127. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/surrogate.md +0 -0
  128. /package/skills/{brainmass → package-skills/brainmass}/references/datasets-api.md +0 -0
  129. /package/skills/{brainmass → package-skills/brainmass}/references/fitting-with-objectives-api.md +0 -0
  130. /package/skills/{brainmass → package-skills/brainmass}/references/forward-observation-api.md +0 -0
  131. /package/skills/{brainmass → package-skills/brainmass}/references/horn-task-training.md +0 -0
  132. /package/skills/{brainmass → package-skills/brainmass}/references/noiseprocesses.md +0 -0
  133. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/eeg-fitting-with-gradients.py +0 -0
  134. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/gradient-free-fitting.py +0 -0
  135. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/hopf-bifurcation-single-node.py +0 -0
  136. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/horn-cognitive-task-training.py +0 -0
  137. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/jansen-rit-eeg-proxy.py +0 -0
  138. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/kuramoto-synchronization.py +0 -0
  139. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/linear-baseline-node.py +0 -0
  140. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/resting-state-meg-whole-brain-pipeline.py +0 -0
  141. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/seizure-epileptor-case-study.py +0 -0
  142. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wilson-cowan-ei-dynamics.py +0 -0
  143. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-decision-making.py +0 -0
  144. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-dmf-resting-state.py +0 -0
  145. /package/skills/{brainmass → package-skills/brainmass}/references/simulator-input-monitor-api.md +0 -0
  146. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/array-creation.md +0 -0
  147. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brain-dynamics-delay-protocol.md +0 -0
  148. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/analysis.md +0 -0
  149. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/brainpy legacy workflow.md +0 -0
  150. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -0
  151. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/connecting neurons.md +0 -0
  152. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/customize neuron and synpase.md +0 -0
  153. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Input generation.md +0 -0
  154. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -0
  155. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -0
  156. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -0
  157. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -0
  158. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -0
  159. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/delays.md +0 -0
  160. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -0
  161. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/integrators.md +0 -0
  162. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/route activity through connectivity.md +0 -0
  163. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synaptic projections.md +0 -0
  164. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synpase properties.md +0 -0
  165. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/loss library.md +0 -0
  166. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/optimizers.md +0 -0
  167. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/parameter initializers.md +0 -0
  168. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -0
  169. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/surrogate gradients.md +0 -0
  170. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainer library.md +0 -0
  171. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainingworkflows.md +0 -0
  172. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/brainstate-control-flow-patterns.md +0 -0
  173. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/data-preprocessing.md +0 -0
  174. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/optimizer.md +0 -0
  175. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/parameter-initializer.md +0 -0
  176. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/surrogate.md +0 -0
  177. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/component-selection.md +0 -0
  178. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/devices.md +0 -0
  179. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/divergence-and-parity.md +0 -0
  180. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/integration-categories.md +0 -0
  181. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/model-library.md +0 -0
  182. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/nest-workflow.md +0 -0
  183. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/network-building.md +0 -0
  184. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brette_et_al_2007.py +0 -0
  185. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_alpha.py +0 -0
  186. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_delta.py +0 -0
  187. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +0 -0
  188. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +0 -0
  189. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/spatial_gaussex.py +0 -0
  190. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/synapsecollection.py +0 -0
  191. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/synapse-and-connectivity.md +0 -0
  192. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/103_COBA_2005.py +0 -0
  193. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/106_COBA_HH_2007.py +0 -0
  194. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/107_gamma_oscillation_1996.py +0 -0
  195. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/109_fast_global_oscillation.py +0 -0
  196. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -0
  197. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/sound_localization.py +0 -0
  198. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/training-snn.py +0 -0
  199. /package/skills/{brainstate → package-skills/brainstate}/agents/openai.yaml +0 -0
  200. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-control-flow-patterns.md +0 -0
  201. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  202. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-jit-expansion.md +0 -0
  203. /package/skills/{brainstate → package-skills/brainstate}/references/collective_model_operations.md +0 -0
  204. /package/skills/{brainstate → package-skills/brainstate}/references/extension_mechanisms.md +0 -0
  205. /package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-activation-library.md +0 -0
  206. /package/skills/{brainstate → package-skills/brainstate}/references/model-interop-and-migration.md +0 -0
  207. /package/skills/{brainstate → package-skills/brainstate}/references/simulation-environment.md +0 -0
  208. /package/skills/{brainstate → package-skills/brainstate}/references/size-inference-variations.md +0 -0
  209. /package/skills/{brainstate → package-skills/brainstate}/references/state-graph-operations.md +0 -0
  210. /package/skills/{brainstate → package-skills/brainstate}/references/state_collections_and_utilities.md +0 -0
  211. /package/skills/{brainstate → package-skills/brainstate}/scripts/integrator_rnn.py +0 -0
  212. /package/skills/{brainstate → package-skills/brainstate}/scripts/lif_neuron_model.py +0 -0
  213. /package/skills/{brainstate → package-skills/brainstate}/scripts/modern_cnn.py +0 -0
  214. /package/skills/{brainstate → package-skills/brainstate}/scripts/resnet.py +0 -0
  215. /package/skills/{braintrace → package-skills/braintrace}/references/custom ETP primitives.md +0 -0
  216. /package/skills/{braintrace → package-skills/braintrace}/references/customizing_primitive_transforms.md +0 -0
  217. /package/skills/{brainunit → package-skills/brainunit}/SKILL.md +0 -0
  218. /package/skills/{brainunit → package-skills/brainunit}/references/array-creation.md +0 -0
  219. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics/functional-structural-api.md +0 -0
  220. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics.md +0 -0
  221. /package/skills/{brainunit → package-skills/brainunit}/references/math-function-library.md +0 -0
  222. /package/skills/{brainunit → package-skills/brainunit}/references/physical-constant-library.md +0 -0
  223. /package/skills/{brainunit → package-skills/brainunit}/references/prefix-library.md +0 -0
  224. /package/skills/{brainunit → package-skills/brainunit}/references/quantity-inspection-and-conversion.md +0 -0
  225. /package/skills/{brainunit → package-skills/brainunit}/references/typing-and-runtime-validation.md +0 -0
  226. /package/skills/{brainunit → package-skills/brainunit}/references/unit-structure-and-definition.md +0 -0
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { pathToFileURL } from 'node:url';
4
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
+ import { z } from 'zod';
7
+ import { FullTextResolver } from './src/resolver.mjs';
8
+
9
+ const workInputSchema = {
10
+ doi: z.string().optional().describe('Published or preprint DOI. Preferred when available.'),
11
+ pmid: z.string().optional().describe('PubMed identifier.'),
12
+ pmcid: z.string().optional().describe('PubMed Central identifier, with or without the PMC prefix.'),
13
+ title: z.string().optional().describe('Exact publication title. Used conservatively when no stronger identifier is available.'),
14
+ authors: z.union([z.string(), z.array(z.string())]).optional().describe('Author names used only to narrow title lookup.'),
15
+ year: z.number().int().min(1600).max(3000).optional().describe('Publication year used only to narrow title lookup.'),
16
+ };
17
+
18
+ const annotations = {
19
+ readOnlyHint: true,
20
+ destructiveHint: false,
21
+ idempotentHint: true,
22
+ openWorldHint: true,
23
+ };
24
+
25
+ function jsonContent(value) {
26
+ return [{ type: 'text', text: JSON.stringify(value, null, 2) }];
27
+ }
28
+
29
+ function fulltextContent(result) {
30
+ const resolved = result.resolved_document;
31
+ const lines = [
32
+ '# Full-text resolution',
33
+ '',
34
+ `- Requested DOI: ${result.requested_work.doi || 'not supplied'}`,
35
+ `- Retrieved identifier: ${resolved?.resolved_doi || resolved?.identifier || 'none'}`,
36
+ `- Source: ${result.source || 'none'}`,
37
+ `- Version: ${result.version || 'none'}`,
38
+ `- Relationship: ${result.relationship || 'none'}`,
39
+ `- Location: ${result.location || 'none'}`,
40
+ '',
41
+ ];
42
+ if (result.document?.markdown) {
43
+ lines.push(result.document.markdown);
44
+ } else {
45
+ lines.push(result.document?.retrieval_note || result.unresolved_reason || 'No full text was retrieved.');
46
+ }
47
+ return [{ type: 'text', text: lines.join('\n') }];
48
+ }
49
+
50
+ export function createMcpServer(options = {}) {
51
+ const resolver = options.resolver ?? new FullTextResolver(options);
52
+ const server = new McpServer({
53
+ name: 'brainx-fulltext-resolver',
54
+ version: '1.0.0',
55
+ });
56
+
57
+ server.registerTool('resolve_fulltext', {
58
+ title: 'Resolve full text',
59
+ description: 'Resolve the best accessible version of a biology or neuroscience work through PMC, OpenAlex, then bioRxiv/medRxiv. Returns provenance without downloading the document.',
60
+ inputSchema: workInputSchema,
61
+ annotations,
62
+ }, async (input, extra) => {
63
+ const result = await resolver.resolve(input, { signal: extra.signal });
64
+ return {
65
+ content: jsonContent(result),
66
+ structuredContent: result,
67
+ };
68
+ });
69
+
70
+ server.registerTool('list_versions', {
71
+ title: 'List full-text versions',
72
+ description: 'List accessible published, accepted-manuscript, and submitted/preprint versions while preserving source and identifier relationships.',
73
+ inputSchema: workInputSchema,
74
+ annotations,
75
+ }, async (input, extra) => {
76
+ const result = await resolver.listVersions(input, { signal: extra.signal });
77
+ return {
78
+ content: jsonContent(result),
79
+ structuredContent: result,
80
+ };
81
+ });
82
+
83
+ server.registerTool('get_fulltext', {
84
+ title: 'Get full text',
85
+ description: 'Resolve and retrieve the best accessible document as Markdown when JATS or HTML is available. PDF-only versions are returned as provenance-preserving source links and are not parsed in v1.',
86
+ inputSchema: {
87
+ ...workInputSchema,
88
+ version: z.enum(['publishedVersion', 'acceptedVersion', 'submittedVersion', 'unknown'])
89
+ .optional()
90
+ .describe('Optional version selector.'),
91
+ source: z.enum(['PMC', 'OpenAlex', 'bioRxiv', 'medRxiv'])
92
+ .optional()
93
+ .describe('Optional source selector.'),
94
+ include_raw: z.boolean().default(false).describe('Include source JATS/HTML in structuredContent.'),
95
+ max_chars: z.number().int().min(1000).max(2_000_000)
96
+ .optional()
97
+ .describe('Optionally truncate returned Markdown to this many characters.'),
98
+ },
99
+ annotations,
100
+ }, async ({ version, source, include_raw, max_chars, ...work }, extra) => {
101
+ const result = await resolver.getFulltext(
102
+ work,
103
+ { version, source, include_raw, max_chars },
104
+ { signal: extra.signal },
105
+ );
106
+ return {
107
+ content: fulltextContent(result),
108
+ structuredContent: result,
109
+ isError: !result.resolved,
110
+ };
111
+ });
112
+
113
+ return server;
114
+ }
115
+
116
+ export async function main() {
117
+ const server = createMcpServer();
118
+ const transport = new StdioServerTransport();
119
+ await server.connect(transport);
120
+ }
121
+
122
+ const invokedPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : '';
123
+ if (import.meta.url === invokedPath) {
124
+ main().catch((error) => {
125
+ process.stderr.write(`Full-text resolver MCP failed: ${error.stack || error.message}\n`);
126
+ process.exitCode = 1;
127
+ });
128
+ }
@@ -0,0 +1,253 @@
1
+ // JATS conversion behavior adapts yogsoth-ai/biorxiv-mcp convert.py
2
+ // (Apache-2.0); modified into a structured Node.js converter. See ../REUSE.md.
3
+
4
+ import { DOMParser, parseHTML } from 'linkedom';
5
+ import TurndownService from 'turndown';
6
+
7
+ function cleanText(value = '') {
8
+ return String(value).replace(/\s+/g, ' ').trim();
9
+ }
10
+
11
+ function elementName(node) {
12
+ return String(node.localName || node.nodeName || '').toLowerCase();
13
+ }
14
+
15
+ function childElements(node) {
16
+ return Array.from(node?.childNodes || []).filter((child) => child.nodeType === 1);
17
+ }
18
+
19
+ function renderInline(node) {
20
+ if (!node) return '';
21
+ if (node.nodeType === 3) return node.nodeValue || '';
22
+ if (node.nodeType !== 1) return '';
23
+ const name = elementName(node);
24
+ const content = Array.from(node.childNodes || []).map(renderInline).join('');
25
+ if (['italic', 'i', 'em'].includes(name)) return `*${content}*`;
26
+ if (['bold', 'b', 'strong'].includes(name)) return `**${content}**`;
27
+ if (name === 'sup') return `<sup>${content}</sup>`;
28
+ if (name === 'sub') return `<sub>${content}</sub>`;
29
+ if (name === 'break' || name === 'br') return '\n';
30
+ if (name === 'ext-link') {
31
+ const href = node.getAttribute('xlink:href') || node.getAttribute('href');
32
+ return href ? `[${content || href}](${href})` : content;
33
+ }
34
+ return content;
35
+ }
36
+
37
+ function paragraphMarkdown(node) {
38
+ return cleanText(renderInline(node));
39
+ }
40
+
41
+ function tableMarkdown(table) {
42
+ if (!table) return '';
43
+ const rows = Array.from(table.querySelectorAll('tr')).map((row) =>
44
+ Array.from(row.querySelectorAll('th, td')).map((cell) => cleanText(renderInline(cell))),
45
+ ).filter((row) => row.length > 0);
46
+ if (!rows.length) return '';
47
+ const width = Math.max(...rows.map((row) => row.length));
48
+ const normalized = rows.map((row) => [...row, ...Array(Math.max(0, width - row.length)).fill('')]);
49
+ const header = normalized[0];
50
+ const body = normalized.slice(1);
51
+ return [
52
+ `| ${header.join(' | ')} |`,
53
+ `| ${header.map(() => '---').join(' | ')} |`,
54
+ ...body.map((row) => `| ${row.join(' | ')} |`),
55
+ ].join('\n');
56
+ }
57
+
58
+ function figureMarkdown(figure) {
59
+ const label = cleanText(figure.querySelector(':scope > label')?.textContent || 'Figure');
60
+ const title = paragraphMarkdown(figure.querySelector(':scope > caption > title'));
61
+ const paragraphs = Array.from(figure.querySelectorAll(':scope > caption > p'))
62
+ .map(paragraphMarkdown)
63
+ .filter(Boolean);
64
+ const caption = [title, ...paragraphs].filter(Boolean).join(' ');
65
+ return caption ? `**${label}.** ${caption}` : '';
66
+ }
67
+
68
+ function listMarkdown(list, depth = 0) {
69
+ const ordered = list.getAttribute('list-type') === 'order';
70
+ return childElements(list)
71
+ .filter((child) => elementName(child) === 'list-item')
72
+ .map((item, index) => {
73
+ const prefix = ordered ? `${index + 1}.` : '-';
74
+ const paragraphs = childElements(item)
75
+ .filter((child) => elementName(child) === 'p')
76
+ .map(paragraphMarkdown)
77
+ .filter(Boolean);
78
+ const nested = childElements(item).find((child) => elementName(child) === 'list');
79
+ const line = `${' '.repeat(depth)}${prefix} ${paragraphs.join(' ')}`.trimEnd();
80
+ return nested ? `${line}\n${listMarkdown(nested, depth + 1)}` : line;
81
+ })
82
+ .join('\n');
83
+ }
84
+
85
+ function renderBlocks(parent, headingLevel, collectors) {
86
+ const blocks = [];
87
+ for (const child of childElements(parent)) {
88
+ const name = elementName(child);
89
+ if (name === 'title') continue;
90
+ if (name === 'p') {
91
+ const paragraph = paragraphMarkdown(child);
92
+ if (paragraph) blocks.push(paragraph);
93
+ } else if (name === 'sec') {
94
+ blocks.push(renderSection(child, headingLevel, collectors));
95
+ } else if (name === 'fig') {
96
+ const figure = figureMarkdown(child);
97
+ if (figure) {
98
+ collectors.figureCaptions.push(figure);
99
+ blocks.push(figure);
100
+ }
101
+ } else if (name === 'table-wrap') {
102
+ const label = cleanText(child.querySelector(':scope > label')?.textContent || 'Table');
103
+ const caption = cleanText(child.querySelector(':scope > caption')?.textContent || '');
104
+ const table = tableMarkdown(child.querySelector('table'));
105
+ const rendered = [`**${label}.**${caption ? ` ${caption}` : ''}`, table].filter(Boolean).join('\n\n');
106
+ if (rendered) {
107
+ collectors.tables.push(rendered);
108
+ blocks.push(rendered);
109
+ }
110
+ } else if (name === 'list') {
111
+ const list = listMarkdown(child);
112
+ if (list) blocks.push(list);
113
+ } else if (['disp-quote', 'boxed-text', 'statement'].includes(name)) {
114
+ const quote = cleanText(child.textContent);
115
+ if (quote) blocks.push(quote.split('\n').map((line) => `> ${line}`).join('\n'));
116
+ }
117
+ }
118
+ return blocks.filter(Boolean).join('\n\n');
119
+ }
120
+
121
+ function renderSection(section, headingLevel, collectors) {
122
+ const title = cleanText(section.querySelector(':scope > title')?.textContent || 'Untitled section');
123
+ const level = Math.min(Math.max(headingLevel, 2), 6);
124
+ const body = renderBlocks(section, level + 1, collectors);
125
+ collectors.sections.push({ title, markdown: body });
126
+ return `${'#'.repeat(level)} ${title}${body ? `\n\n${body}` : ''}`;
127
+ }
128
+
129
+ function jatsAuthors(document) {
130
+ return Array.from(document.querySelectorAll('article-meta > contrib-group[content-type="author"] > contrib, article-meta > contrib-group > contrib'))
131
+ .map((contributor) => {
132
+ const given = cleanText(contributor.querySelector('given-names')?.textContent);
133
+ const surname = cleanText(contributor.querySelector('surname')?.textContent);
134
+ const collaborative = cleanText(contributor.querySelector('collab')?.textContent);
135
+ return collaborative || [given, surname].filter(Boolean).join(' ');
136
+ })
137
+ .filter(Boolean);
138
+ }
139
+
140
+ function jatsVersion(document) {
141
+ const customMetadata = new Map(
142
+ Array.from(document.querySelectorAll('custom-meta')).map((entry) => [
143
+ cleanText(entry.querySelector('meta-name')?.textContent).toLowerCase(),
144
+ cleanText(entry.querySelector('meta-value')?.textContent).toLowerCase(),
145
+ ]),
146
+ );
147
+ const enabled = (name) => ['yes', 'true', '1'].includes(customMetadata.get(name));
148
+ if (enabled('is-preprint')) return 'submittedVersion';
149
+ if (enabled('is-manuscript')) return 'acceptedVersion';
150
+ return 'publishedVersion';
151
+ }
152
+
153
+ export function jatsToDocument(xml) {
154
+ const document = new DOMParser().parseFromString(xml, 'text/xml');
155
+ const parserError = document.querySelector('parsererror');
156
+ if (parserError) throw new Error(`Invalid JATS XML: ${cleanText(parserError.textContent)}`);
157
+
158
+ const title = cleanText(document.querySelector('article-meta article-title')?.textContent);
159
+ const authors = jatsAuthors(document);
160
+ const abstractNodes = Array.from(document.querySelectorAll('article-meta > abstract'));
161
+ const abstract = abstractNodes
162
+ .map((node) => Array.from(node.querySelectorAll(':scope > p')).map(paragraphMarkdown).filter(Boolean).join('\n\n'))
163
+ .filter(Boolean)
164
+ .join('\n\n');
165
+ const collectors = { sections: [], figureCaptions: [], tables: [] };
166
+ const body = document.querySelector('article > body') || document.querySelector('body');
167
+ const bodyMarkdown = body ? renderBlocks(body, 2, collectors) : '';
168
+ const references = Array.from(document.querySelectorAll('ref-list > ref'))
169
+ .map((reference) => {
170
+ const label = cleanText(reference.querySelector(':scope > label')?.textContent);
171
+ const citation = cleanText(Array.from(reference.childNodes || [])
172
+ .filter((child) => child !== reference.querySelector(':scope > label'))
173
+ .map((child) => child.textContent || child.nodeValue || '')
174
+ .join(' '));
175
+ return [label, citation].filter(Boolean).join(' ');
176
+ })
177
+ .filter(Boolean);
178
+ const journal = cleanText(document.querySelector('journal-title')?.textContent);
179
+ const year = Number(cleanText(document.querySelector('article-meta > pub-date > year')?.textContent)) || null;
180
+ const doi = cleanText(document.querySelector('article-id[pub-id-type="doi"]')?.textContent) || null;
181
+ const pmcid = cleanText(document.querySelector('article-id[pub-id-type="pmcid"]')?.textContent) || null;
182
+ const version = jatsVersion(document);
183
+
184
+ const header = [
185
+ title ? `# ${title}` : '',
186
+ authors.length ? `**Authors:** ${authors.join(', ')}` : '',
187
+ journal ? `**Journal:** ${journal}${year ? ` (${year})` : ''}` : '',
188
+ abstract ? `## Abstract\n\n${abstract}` : '',
189
+ ].filter(Boolean).join('\n\n');
190
+ const referenceMarkdown = references.length
191
+ ? `## References\n\n${references.map((reference) => `- ${reference}`).join('\n')}`
192
+ : '';
193
+ const markdown = [header, bodyMarkdown, referenceMarkdown].filter(Boolean).join('\n\n').trim();
194
+ if (!markdown) throw new Error('JATS document contains no extractable text.');
195
+
196
+ return {
197
+ title: title || null,
198
+ authors,
199
+ doi,
200
+ pmcid,
201
+ version,
202
+ journal: journal || null,
203
+ year,
204
+ abstract: abstract || null,
205
+ sections: collectors.sections,
206
+ figure_captions: collectors.figureCaptions,
207
+ tables: collectors.tables,
208
+ references,
209
+ markdown,
210
+ original_format: 'jats_xml',
211
+ normalized_format: 'markdown',
212
+ };
213
+ }
214
+
215
+ function createTurndown() {
216
+ const turndown = new TurndownService({
217
+ bulletListMarker: '-',
218
+ codeBlockStyle: 'fenced',
219
+ headingStyle: 'atx',
220
+ });
221
+ turndown.remove(['script', 'style', 'noscript', 'nav', 'form', 'button', 'svg']);
222
+ turndown.addRule('table', {
223
+ filter: 'table',
224
+ replacement(_content, node) {
225
+ const table = tableMarkdown(node);
226
+ return table ? `\n\n${table}\n\n` : '';
227
+ },
228
+ });
229
+ return turndown;
230
+ }
231
+
232
+ export function htmlToDocument(html, sourceUrl) {
233
+ const { document } = parseHTML(html);
234
+ for (const node of document.querySelectorAll('script, style, noscript, nav, form, button, svg, header, footer, aside')) {
235
+ node.remove();
236
+ }
237
+ const root = document.querySelector('.fulltext-view, article, main, [role="main"], .article') || document.body;
238
+ const markdown = createTurndown().turndown(root?.innerHTML || '').trim();
239
+ if (!markdown) throw new Error(`HTML page contains no extractable article text: ${sourceUrl}`);
240
+ return {
241
+ title: cleanText(root?.querySelector('h1')?.textContent || document.querySelector('title')?.textContent) || null,
242
+ authors: [],
243
+ abstract: null,
244
+ sections: [],
245
+ figure_captions: [],
246
+ tables: [],
247
+ references: [],
248
+ markdown,
249
+ original_format: 'html',
250
+ normalized_format: 'markdown',
251
+ source_url: sourceUrl,
252
+ };
253
+ }
@@ -0,0 +1,173 @@
1
+ // Retry, timeout, rate-limit, and response guards adapt cyanheads MCP services
2
+ // (Apache-2.0); modified for this Node 18 resolver. See ../REUSE.md.
3
+
4
+ import { assertPublicHttpUrl } from './identifiers.mjs';
5
+
6
+ export class HttpError extends Error {
7
+ constructor(message, options = {}) {
8
+ super(message, options.cause ? { cause: options.cause } : undefined);
9
+ this.name = 'HttpError';
10
+ this.status = options.status;
11
+ this.retryable = Boolean(options.retryable);
12
+ this.retryAfter = options.retryAfter;
13
+ this.url = options.url;
14
+ }
15
+ }
16
+
17
+ function parseRetryAfter(value) {
18
+ if (!value) return undefined;
19
+ if (/^\d+$/.test(value.trim())) return Number(value.trim());
20
+ const date = Date.parse(value);
21
+ if (Number.isNaN(date)) return undefined;
22
+ return Math.max(0, Math.round((date - Date.now()) / 1000));
23
+ }
24
+
25
+ function abortAfter(timeoutMs, externalSignal) {
26
+ const controller = new AbortController();
27
+ const timeout = setTimeout(() => controller.abort(new Error(`Request timed out after ${timeoutMs} ms`)), timeoutMs);
28
+ const abort = () => controller.abort(externalSignal?.reason);
29
+ externalSignal?.addEventListener('abort', abort, { once: true });
30
+ return {
31
+ signal: controller.signal,
32
+ dispose() {
33
+ clearTimeout(timeout);
34
+ externalSignal?.removeEventListener('abort', abort);
35
+ },
36
+ };
37
+ }
38
+
39
+ async function sleep(milliseconds, signal) {
40
+ if (milliseconds <= 0) return;
41
+ await new Promise((resolve, reject) => {
42
+ const timeout = setTimeout(resolve, milliseconds);
43
+ const abort = () => {
44
+ clearTimeout(timeout);
45
+ reject(signal.reason ?? new Error('Request aborted'));
46
+ };
47
+ signal?.addEventListener('abort', abort, { once: true });
48
+ });
49
+ }
50
+
51
+ export class HttpClient {
52
+ constructor(options = {}) {
53
+ this.fetch = options.fetchImpl ?? globalThis.fetch;
54
+ this.timeoutMs = options.timeoutMs ?? Number(process.env.FULLTEXT_HTTP_TIMEOUT_MS || 30_000);
55
+ this.maxBytes = options.maxBytes ?? Number(process.env.FULLTEXT_MAX_BYTES || 8_000_000);
56
+ this.retries = options.retries ?? 2;
57
+ this.userAgent = options.userAgent
58
+ ?? process.env.FULLTEXT_RESOLVER_USER_AGENT
59
+ ?? 'brainx-fulltext-resolver/1.0 (+https://github.com/chaobrain/BrainX-skill)';
60
+ }
61
+
62
+ async request(urlValue, options = {}) {
63
+ let lastError;
64
+ for (let attempt = 0; attempt <= this.retries; attempt += 1) {
65
+ try {
66
+ const response = await this.#fetchFollowingRedirects(urlValue, options);
67
+ if (response.ok) return response;
68
+
69
+ const retryAfter = parseRetryAfter(response.headers.get('retry-after'));
70
+ const retryable = response.status === 429 || response.status >= 500;
71
+ const error = new HttpError(`HTTP ${response.status} from ${response.url || urlValue}`, {
72
+ status: response.status,
73
+ retryable,
74
+ retryAfter,
75
+ url: response.url || String(urlValue),
76
+ });
77
+ if (!retryable || attempt === this.retries) throw error;
78
+ lastError = error;
79
+ const waitMs = retryAfter === undefined
80
+ ? 250 * (2 ** attempt)
81
+ : Math.min(retryAfter * 1000, 10_000);
82
+ await sleep(waitMs, options.signal);
83
+ } catch (error) {
84
+ if (error instanceof HttpError && !error.retryable) throw error;
85
+ if (options.signal?.aborted) throw options.signal.reason ?? error;
86
+ lastError = error;
87
+ if (attempt === this.retries) {
88
+ if (error instanceof HttpError) throw error;
89
+ throw new HttpError(`Request failed for ${urlValue}: ${error.message}`, {
90
+ cause: error,
91
+ retryable: true,
92
+ url: String(urlValue),
93
+ });
94
+ }
95
+ await sleep(250 * (2 ** attempt), options.signal);
96
+ }
97
+ }
98
+ throw lastError;
99
+ }
100
+
101
+ async #fetchFollowingRedirects(urlValue, options) {
102
+ let url = assertPublicHttpUrl(urlValue);
103
+ for (let redirectCount = 0; redirectCount <= 5; redirectCount += 1) {
104
+ const timed = abortAfter(this.timeoutMs, options.signal);
105
+ try {
106
+ const response = await this.fetch(url, {
107
+ headers: {
108
+ accept: options.accept ?? '*/*',
109
+ 'user-agent': this.userAgent,
110
+ ...options.headers,
111
+ },
112
+ redirect: 'manual',
113
+ signal: timed.signal,
114
+ });
115
+ if (![301, 302, 303, 307, 308].includes(response.status)) return response;
116
+ const location = response.headers.get('location');
117
+ if (!location) return response;
118
+ url = assertPublicHttpUrl(new URL(location, url).toString());
119
+ } finally {
120
+ timed.dispose();
121
+ }
122
+ }
123
+ throw new HttpError(`Too many redirects from ${urlValue}`, {
124
+ retryable: false,
125
+ url: String(urlValue),
126
+ });
127
+ }
128
+
129
+ async text(url, options = {}) {
130
+ const response = await this.request(url, options);
131
+ const contentLength = Number(response.headers.get('content-length') || 0);
132
+ if (contentLength > this.maxBytes) {
133
+ throw new HttpError(`Response exceeds ${this.maxBytes} bytes: ${response.url || url}`, {
134
+ retryable: false,
135
+ url: response.url || String(url),
136
+ });
137
+ }
138
+ const buffer = Buffer.from(await response.arrayBuffer());
139
+ if (buffer.byteLength > this.maxBytes) {
140
+ throw new HttpError(`Response exceeds ${this.maxBytes} bytes: ${response.url || url}`, {
141
+ retryable: false,
142
+ url: response.url || String(url),
143
+ });
144
+ }
145
+ return {
146
+ body: buffer.toString('utf8'),
147
+ contentType: response.headers.get('content-type') || '',
148
+ url: response.url || String(url),
149
+ };
150
+ }
151
+
152
+ async json(url, options = {}) {
153
+ const response = await this.text(url, {
154
+ ...options,
155
+ accept: options.accept ?? 'application/json',
156
+ });
157
+ if (/^\s*<(!doctype\s+html|html[\s>])/i.test(response.body)) {
158
+ throw new HttpError(`Expected JSON but received HTML from ${response.url}`, {
159
+ retryable: true,
160
+ url: response.url,
161
+ });
162
+ }
163
+ try {
164
+ return JSON.parse(response.body);
165
+ } catch (error) {
166
+ throw new HttpError(`Invalid JSON from ${response.url}`, {
167
+ cause: error,
168
+ retryable: true,
169
+ url: response.url,
170
+ });
171
+ }
172
+ }
173
+ }
@@ -0,0 +1,123 @@
1
+ // Adapted from DeyangLiu123/openalex-mcp ids.py (MIT); modified for Node.js.
2
+ // See ../REUSE.md and ../THIRD_PARTY_NOTICES.md.
3
+
4
+ import { domainToASCII } from 'node:url';
5
+
6
+ const DOI_PATTERN = /^10\.\d{4,9}\/\S+$/i;
7
+ const PMCID_PATTERN = /^PMC\d+$/i;
8
+ const PMID_PATTERN = /^\d+$/;
9
+
10
+ export function normalizeDoi(value = '') {
11
+ let normalized = decodeURIComponent(String(value).trim());
12
+ normalized = normalized.replace(/^doi:\s*/i, '');
13
+ normalized = normalized.replace(/^https?:\/\/(?:dx\.)?doi\.org\//i, '');
14
+ return normalized.replace(/[\s.]+$/, '').toLowerCase();
15
+ }
16
+
17
+ export function isValidDoi(value) {
18
+ return DOI_PATTERN.test(normalizeDoi(value));
19
+ }
20
+
21
+ export function normalizePmcid(value = '') {
22
+ const normalized = String(value).trim().toUpperCase();
23
+ if (!normalized) return '';
24
+ return normalized.startsWith('PMC') ? normalized : `PMC${normalized}`;
25
+ }
26
+
27
+ export function normalizePmid(value = '') {
28
+ return String(value).trim();
29
+ }
30
+
31
+ export function normalizeTitle(value = '') {
32
+ return String(value)
33
+ .normalize('NFKC')
34
+ .toLocaleLowerCase('en-US')
35
+ .replace(/[\p{P}\p{S}\s]+/gu, '');
36
+ }
37
+
38
+ export function normalizeAuthors(authors) {
39
+ if (Array.isArray(authors)) {
40
+ return authors.map((author) => String(author).trim()).filter(Boolean);
41
+ }
42
+ if (typeof authors === 'string') {
43
+ return authors.split(/\s*;\s*/).map((author) => author.trim()).filter(Boolean);
44
+ }
45
+ return [];
46
+ }
47
+
48
+ export function normalizeRequest(input = {}) {
49
+ const request = {
50
+ doi: normalizeDoi(input.doi),
51
+ pmid: normalizePmid(input.pmid),
52
+ pmcid: normalizePmcid(input.pmcid),
53
+ title: String(input.title ?? '').trim(),
54
+ authors: normalizeAuthors(input.authors),
55
+ year: input.year === undefined ? undefined : Number(input.year),
56
+ };
57
+
58
+ if (!request.doi && !request.pmid && !request.pmcid && !request.title) {
59
+ throw new Error('Provide at least one of doi, pmid, pmcid, or title.');
60
+ }
61
+ if (request.doi && !DOI_PATTERN.test(request.doi)) {
62
+ throw new Error(`Malformed DOI: ${input.doi}`);
63
+ }
64
+ if (request.pmid && !PMID_PATTERN.test(request.pmid)) {
65
+ throw new Error(`Malformed PMID: ${input.pmid}`);
66
+ }
67
+ if (request.pmcid && !PMCID_PATTERN.test(request.pmcid)) {
68
+ throw new Error(`Malformed PMCID: ${input.pmcid}`);
69
+ }
70
+ if (request.year !== undefined && (!Number.isInteger(request.year) || request.year < 1600 || request.year > 3000)) {
71
+ throw new Error(`Malformed publication year: ${input.year}`);
72
+ }
73
+ return request;
74
+ }
75
+
76
+ export function doiFromUrl(value = '') {
77
+ const text = String(value);
78
+ const doiUrlMatch = text.match(/doi\.org\/(10\.\d{4,9}\/[^?#\s]+)/i);
79
+ if (doiUrlMatch) return normalizeDoi(doiUrlMatch[1]);
80
+
81
+ const preprintMatch = text.match(/\/(10\.1101\/[^/?#]+)/i);
82
+ if (preprintMatch) {
83
+ // Remove bioRxiv revision and representation suffixes before comparing work identity.
84
+ const doi = preprintMatch[1].replace(/(?:v\d+)?(?:\.(?:full|source))?(?:\.(?:pdf|xml))?$/i, '');
85
+ return normalizeDoi(doi);
86
+ }
87
+
88
+ const arxivMatch = text.match(/arxiv\.org\/(?:abs|pdf|html)\/([^?#]+?)(?:\.pdf)?$/i);
89
+ if (arxivMatch) return `10.48550/arxiv.${arxivMatch[1].replace(/v\d+$/i, '').toLowerCase()}`;
90
+ return '';
91
+ }
92
+
93
+ function isPrivateIpv4(hostname) {
94
+ const parts = hostname.split('.').map(Number);
95
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
96
+ return false;
97
+ }
98
+ return parts[0] === 10
99
+ || parts[0] === 127
100
+ || (parts[0] === 169 && parts[1] === 254)
101
+ || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31)
102
+ || (parts[0] === 192 && parts[1] === 168)
103
+ || parts[0] === 0;
104
+ }
105
+
106
+ export function assertPublicHttpUrl(value) {
107
+ const url = new URL(value);
108
+ if (!['http:', 'https:'].includes(url.protocol)) {
109
+ throw new Error(`Unsupported source URL protocol: ${url.protocol}`);
110
+ }
111
+ const hostname = domainToASCII(url.hostname).toLowerCase();
112
+ if (!hostname || hostname === 'localhost' || hostname.endsWith('.localhost') || isPrivateIpv4(hostname)) {
113
+ throw new Error(`Refusing non-public source URL: ${value}`);
114
+ }
115
+ if (hostname === '::1' || hostname.startsWith('fc') || hostname.startsWith('fd') || hostname.startsWith('fe80:')) {
116
+ throw new Error(`Refusing non-public source URL: ${value}`);
117
+ }
118
+ return url;
119
+ }
120
+
121
+ export function encodeDoiPath(doi) {
122
+ return normalizeDoi(doi).split('/').map(encodeURIComponent).join('/');
123
+ }