biodata-mcp 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,12 @@
1
+ BioData MCP Licence
2
+ Copyright (c) 2026 Root 7 (Pty) Ltd, South Africa. All rights reserved.
3
+
4
+ 1. Free use. You may install and use BioData MCP, including its free tools, for personal, academic and commercial purposes at no charge.
5
+
6
+ 2. Pro features. The Pro tools (evidence_pack, gene_dossier, export_citations and extended batch limits) may only be used with a valid licence key purchased from the copyright holder. Each key is for one named person and may not be shared or resold.
7
+
8
+ 3. Restrictions. You may not (a) remove, disable or work around the licence key check, (b) redistribute modified versions of this software, or (c) sell or sublicense this software.
9
+
10
+ 4. Third-party data. Data returned by the tools comes from NCBI/PubMed, ClinicalTrials.gov, UniProt and Ensembl and is subject to their terms of use. The copyright holder is not affiliated with these providers.
11
+
12
+ 5. No warranty. The software is provided "as is", without warranty of any kind. Outputs are for research purposes only and are not medical, clinical or regulatory advice. The copyright holder is not liable for any decision made using the software or its outputs.
package/README.md CHANGED
@@ -1,3 +1,96 @@
1
- # Temporary Holding Version
1
+ # BioData MCP
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Cited biomedical research inside your AI assistant. Every answer traces back to a PMID, NCT ID or database accession.**
4
+
5
+ BioData MCP is a [Model Context Protocol](https://modelcontextprotocol.io) server for Claude Desktop, Cursor and other MCP clients. It connects your assistant to PubMed, ClinicalTrials.gov, UniProt and Ensembl, for biotech and pharma analysts, medical writers, researchers and students who need answers they can cite.
6
+
7
+ - **Four databases, one install.** Literature, registered trials, proteins and genes.
8
+ - **Evidence ordered by study design.** Meta-analyses and randomised trials appear before case reports.
9
+ - **Citations ready to use.** Numbered references, DOIs, and RIS or BibTeX export for Zotero, EndNote and Mendeley.
10
+ - **No account needed for the free tools.** Data is read live from the public databases.
11
+
12
+ ## Tools
13
+
14
+ | Tool | Tier | What it does |
15
+ |---|---|---|
16
+ | `search_pubmed` | Free | Search PubMed (full query syntax, year filters, newest-first sort) |
17
+ | `get_pubmed_articles` | Free (5/call) · Pro (50/call) | Abstracts, MeSH terms and citation details |
18
+ | `search_trials` | Free | ClinicalTrials.gov by condition, intervention, country and status |
19
+ | `get_trial` | Free | Full trial record: outcomes, eligibility, locations |
20
+ | `search_proteins` | Free | UniProtKB search (reviewed entries by default) |
21
+ | `get_protein` | Free | Function, location, disease links, cross-references |
22
+ | `lookup_gene` | Free | Ensembl gene location, biotype, canonical transcript |
23
+ | `evidence_pack` | **Pro** | Cited evidence pack: papers ranked by study design, key findings, related trials, numbered references |
24
+ | `gene_dossier` | **Pro** | One-call gene profile across Ensembl, UniProt, PubMed and ClinicalTrials.gov |
25
+ | `export_citations` | **Pro** | Up to 200 PMIDs as RIS or BibTeX |
26
+ | `biodata_status` | Free | Shows your tier and settings |
27
+
28
+ ## Install
29
+
30
+ Requires [Node.js](https://nodejs.org) 18.17 or newer.
31
+
32
+ ### Claude Desktop
33
+
34
+ Open **Settings → Developer → Edit Config** and add:
35
+
36
+ ```json
37
+ {
38
+ "mcpServers": {
39
+ "biodata": {
40
+ "command": "npx",
41
+ "args": ["-y", "biodata-mcp"],
42
+ "env": {
43
+ "NCBI_EMAIL": "you@example.com",
44
+ "BIODATA_LICENSE_KEY": ""
45
+ }
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ Restart Claude Desktop. You should see the BioData tools in the tools menu.
52
+
53
+ ### Cursor and other MCP clients
54
+
55
+ Use the same `command`, `args` and `env` in your client's MCP configuration (for Cursor: `.cursor/mcp.json`).
56
+
57
+ ### Settings
58
+
59
+ | Variable | Required | Purpose |
60
+ |---|---|---|
61
+ | `NCBI_EMAIL` | Recommended | NCBI asks API users to identify themselves |
62
+ | `NCBI_API_KEY` | Optional | Raises the PubMed rate limit from 3 to 10 requests/second. Free from your NCBI account settings |
63
+ | `BIODATA_LICENSE_KEY` | For Pro | Unlocks Pro tools |
64
+
65
+ ## Try these prompts
66
+
67
+ - "Build an evidence pack on SGLT2 inhibitors and heart failure hospitalisation since 2018, high-level evidence only."
68
+ - "Give me a gene dossier for PCSK9 and summarise what is in trials right now."
69
+ - "Find recruiting phase 3 trials for tuberculosis in South Africa and compare their primary outcomes."
70
+ - "Read the abstracts for these PMIDs and tell me where they disagree: …"
71
+ - "Export the references from that evidence pack as BibTeX."
72
+
73
+ ## Pro
74
+
75
+ Pro unlocks `evidence_pack`, `gene_dossier`, `export_citations` and 50-article batch reads.
76
+
77
+ **$99 a year or $12 a month.** Founding offer: use the code `FOUNDING` for 50% off your first year (first 20 buyers).
78
+
79
+ 1. Buy Pro at **[buy.polar.sh](https://buy.polar.sh/polar_cl_izX9bcMQvKqrvU4t66u2P4pp07GycLlSpQoSq45gkOW)**. Your licence key appears on the confirmation page and in your Polar customer portal.
80
+ 2. Paste it as the value of `BIODATA_LICENSE_KEY` in your MCP client config.
81
+ 3. Restart the client and ask it to run `biodata_status` to confirm.
82
+
83
+ The key is checked with Polar, our payment provider, about once every six hours. Only the key is sent, never your queries.
84
+
85
+ ## Good to know
86
+
87
+ - **Research use only.** Outputs summarise public records and are not medical advice. Always check the primary source before relying on a finding.
88
+ - **Study-design labels are not quality grades.** They come from PubMed publication-type tags and do not assess risk of bias.
89
+ - **Data sources and their terms.** Data comes from NCBI E-utilities, ClinicalTrials.gov, UniProt and Ensembl, each under its own terms of use. This product is not affiliated with or endorsed by any of them.
90
+ - **Privacy.** The server runs on your machine. Queries go directly to the public databases above and are never sent to us. Pro users' licence keys are checked with Polar.
91
+
92
+ ## Support
93
+
94
+ Questions or bugs: [open an issue](https://github.com/kramdayal-create/biodata-mcp/issues) or email hello@root7.co.za.
95
+
96
+ BioData MCP is built by Root 7 (Pty) Ltd, South Africa.
package/dist/format.js ADDED
@@ -0,0 +1,43 @@
1
+ export function toRis(items) {
2
+ return items
3
+ .map((p) => {
4
+ const lines = ["TY - JOUR", `TI - ${p.title}`];
5
+ for (const a of p.authors)
6
+ lines.push(`AU - ${a}`);
7
+ if (p.journal)
8
+ lines.push(`JO - ${p.journal}`);
9
+ if (p.year)
10
+ lines.push(`PY - ${p.year}`);
11
+ if (p.doi)
12
+ lines.push(`DO - ${p.doi}`);
13
+ lines.push(`AN - PMID:${p.pmid}`, `UR - ${p.url}`, "ER - ");
14
+ return lines.join("\n");
15
+ })
16
+ .join("\n\n");
17
+ }
18
+ function bibEscape(s) {
19
+ return s.replace(/[{}]/g, "").replace(/([&%$#_])/g, "\\$1");
20
+ }
21
+ export function toBibtex(items) {
22
+ return items
23
+ .map((p) => {
24
+ const first = (p.authors[0] ?? "anon").split(" ")[0].replace(/[^A-Za-z]/g, "").toLowerCase() || "anon";
25
+ const key = `${first}${p.year || ""}pmid${p.pmid}`;
26
+ const fields = [
27
+ ` title = {${bibEscape(p.title)}}`,
28
+ ` author = {${bibEscape(p.authors.join(" and "))}}`,
29
+ p.journal ? ` journal = {${bibEscape(p.journal)}}` : "",
30
+ p.year ? ` year = {${p.year}}` : "",
31
+ p.doi ? ` doi = {${p.doi}}` : "",
32
+ ` pmid = {${p.pmid}}`,
33
+ ` url = {${p.url}}`,
34
+ ].filter(Boolean);
35
+ return `@article{${key},\n${fields.join(",\n")}\n}`;
36
+ })
37
+ .join("\n\n");
38
+ }
39
+ export function truncate(s, max) {
40
+ if (s.length <= max)
41
+ return s;
42
+ return `${s.slice(0, max).trimEnd()}…`;
43
+ }
package/dist/http.js ADDED
@@ -0,0 +1,115 @@
1
+ // Shared HTTP layer: timeouts, retries, per-host politeness delay and a small in-memory cache.
2
+ const USER_AGENT = "biodata-mcp/0.1 (+https://github.com/biodata-mcp)";
3
+ const DEFAULT_TIMEOUT_MS = 20_000;
4
+ const CACHE_TTL_MS = 15 * 60 * 1000;
5
+ const CACHE_MAX = 500;
6
+ // Minimum gap between requests to the same host.
7
+ // NCBI asks for <= 3 req/s without an API key and <= 10 req/s with one.
8
+ const hostGapMs = {
9
+ "eutils.ncbi.nlm.nih.gov": process.env.NCBI_API_KEY ? 110 : 350,
10
+ "rest.ensembl.org": 70,
11
+ "rest.uniprot.org": 50,
12
+ "clinicaltrials.gov": 50,
13
+ };
14
+ const lastCall = new Map();
15
+ const cache = new Map();
16
+ export class UpstreamError extends Error {
17
+ status;
18
+ constructor(message, status) {
19
+ super(message);
20
+ this.status = status;
21
+ this.name = "UpstreamError";
22
+ }
23
+ }
24
+ async function politeDelay(host) {
25
+ const gap = hostGapMs[host] ?? 50;
26
+ const now = Date.now();
27
+ const next = (lastCall.get(host) ?? 0) + gap;
28
+ lastCall.set(host, Math.max(now, next));
29
+ if (next > now)
30
+ await new Promise((r) => setTimeout(r, next - now));
31
+ }
32
+ function cacheGet(key) {
33
+ const hit = cache.get(key);
34
+ if (!hit)
35
+ return undefined;
36
+ if (Date.now() - hit.at > CACHE_TTL_MS) {
37
+ cache.delete(key);
38
+ return undefined;
39
+ }
40
+ // refresh LRU position
41
+ cache.delete(key);
42
+ cache.set(key, hit);
43
+ return hit.body;
44
+ }
45
+ function cacheSet(key, body) {
46
+ cache.set(key, { at: Date.now(), body });
47
+ if (cache.size > CACHE_MAX) {
48
+ const oldest = cache.keys().next().value;
49
+ if (oldest !== undefined)
50
+ cache.delete(oldest);
51
+ }
52
+ }
53
+ export function clearCache() {
54
+ cache.clear();
55
+ lastCall.clear();
56
+ }
57
+ export async function fetchText(url, accept = "application/json") {
58
+ const cached = cacheGet(url);
59
+ if (cached !== undefined)
60
+ return cached;
61
+ const host = new URL(url).host;
62
+ let lastErr;
63
+ for (let attempt = 0; attempt < 3; attempt++) {
64
+ await politeDelay(host);
65
+ try {
66
+ const res = await fetch(url, {
67
+ headers: { "User-Agent": USER_AGENT, Accept: accept },
68
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
69
+ });
70
+ if (res.status === 429 || res.status >= 500) {
71
+ lastErr = new UpstreamError(`${host} returned HTTP ${res.status}`, res.status);
72
+ const retryAfter = Number(res.headers.get("retry-after"));
73
+ const wait = Number.isFinite(retryAfter) && retryAfter > 0
74
+ ? retryAfter * 1000
75
+ : 500 * 2 ** attempt;
76
+ await new Promise((r) => setTimeout(r, Math.min(wait, 5000)));
77
+ continue;
78
+ }
79
+ if (res.status === 404) {
80
+ throw new UpstreamError(`Not found at ${host}`, 404);
81
+ }
82
+ if (!res.ok) {
83
+ throw new UpstreamError(`${host} returned HTTP ${res.status}`, res.status);
84
+ }
85
+ const body = await res.text();
86
+ cacheSet(url, body);
87
+ return body;
88
+ }
89
+ catch (err) {
90
+ if (err instanceof UpstreamError && err.status && err.status < 500 && err.status !== 429) {
91
+ throw err;
92
+ }
93
+ lastErr = err;
94
+ }
95
+ }
96
+ const msg = lastErr instanceof Error ? lastErr.message : String(lastErr);
97
+ throw new UpstreamError(`Could not reach ${host}: ${msg}`);
98
+ }
99
+ export async function fetchJson(url) {
100
+ const text = await fetchText(url, "application/json");
101
+ try {
102
+ return JSON.parse(text);
103
+ }
104
+ catch {
105
+ throw new UpstreamError(`Unexpected non-JSON response from ${new URL(url).host}`);
106
+ }
107
+ }
108
+ export function qs(params) {
109
+ const sp = new URLSearchParams();
110
+ for (const [k, v] of Object.entries(params)) {
111
+ if (v !== undefined && v !== "")
112
+ sp.set(k, String(v));
113
+ }
114
+ return sp.toString();
115
+ }
package/dist/index.js ADDED
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { z } from "zod";
5
+ import { getLicence, upgradeMessage, UPGRADE_URL } from "./license.js";
6
+ import { TRIAL_STATUSES } from "./sources/trials.js";
7
+ import { FREE_ARTICLE_LIMIT, PRO_ARTICLE_LIMIT, toolEvidencePack, toolExportCitations, toolGeneDossier, toolGetProtein, toolGetPubMedArticles, toolGetTrial, toolLookupGene, toolSearchProteins, toolSearchPubMed, toolSearchTrials, } from "./tools.js";
8
+ export const VERSION = "0.1.0";
9
+ function ok(text) {
10
+ return { content: [{ type: "text", text }] };
11
+ }
12
+ async function run(fn) {
13
+ try {
14
+ return ok(await fn());
15
+ }
16
+ catch (err) {
17
+ const msg = err instanceof Error ? err.message : String(err);
18
+ return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
19
+ }
20
+ }
21
+ async function pro(tool, fn) {
22
+ const lic = await getLicence();
23
+ if (!lic.valid)
24
+ return ok(upgradeMessage(tool, lic.reason));
25
+ return run(fn);
26
+ }
27
+ const readOnly = { readOnlyHint: true, openWorldHint: true };
28
+ export function createServer() {
29
+ const server = new McpServer({ name: "biodata-mcp", version: VERSION });
30
+ // ----- Free tools -----
31
+ server.registerTool("search_pubmed", {
32
+ title: "Search PubMed",
33
+ description: "Search PubMed for biomedical literature. Returns titles, journals, years, PMIDs, DOIs and a study-design tag. Supports PubMed query syntax (e.g. 'metformin AND aging[tiab]').",
34
+ inputSchema: {
35
+ query: z.string().min(2).describe("PubMed query. Field tags like [tiab], [mh], [au] are supported."),
36
+ max_results: z.number().int().min(1).max(50).optional().describe("Default 10."),
37
+ sort: z.enum(["relevance", "pub_date"]).optional().describe("Default relevance."),
38
+ from_year: z.number().int().min(1800).max(2100).optional(),
39
+ to_year: z.number().int().min(1800).max(2100).optional(),
40
+ },
41
+ annotations: readOnly,
42
+ }, (a) => run(() => toolSearchPubMed(a)));
43
+ server.registerTool("get_pubmed_articles", {
44
+ title: "Read PubMed abstracts",
45
+ description: `Fetch full abstracts, MeSH terms and citation details for PubMed IDs. Free tier: up to ${FREE_ARTICLE_LIMIT} per call; Pro: up to ${PRO_ARTICLE_LIMIT}.`,
46
+ inputSchema: {
47
+ pmids: z.array(z.string()).min(1).max(PRO_ARTICLE_LIMIT).describe("PubMed IDs, e.g. ['31234567']."),
48
+ },
49
+ annotations: readOnly,
50
+ }, (a) => run(async () => toolGetPubMedArticles(a, (await getLicence()).valid)));
51
+ server.registerTool("search_trials", {
52
+ title: "Search ClinicalTrials.gov",
53
+ description: "Search ClinicalTrials.gov registered studies by free text, condition, intervention, location and recruitment status.",
54
+ inputSchema: {
55
+ query: z.string().optional().describe("Free-text search across all fields."),
56
+ condition: z.string().optional().describe("Disease or condition, e.g. 'type 2 diabetes'."),
57
+ intervention: z.string().optional().describe("Drug, device or procedure, e.g. 'semaglutide'."),
58
+ country: z.string().optional().describe("Location filter, e.g. 'South Africa'."),
59
+ status: z.array(z.enum(TRIAL_STATUSES)).optional().describe("Overall status filter, e.g. ['RECRUITING']."),
60
+ max_results: z.number().int().min(1).max(50).optional().describe("Default 10."),
61
+ },
62
+ annotations: readOnly,
63
+ }, (a) => run(() => toolSearchTrials(a)));
64
+ server.registerTool("get_trial", {
65
+ title: "Get a clinical trial",
66
+ description: "Get full details for one ClinicalTrials.gov study: summary, outcomes, eligibility and locations.",
67
+ inputSchema: { nct_id: z.string().describe("NCT ID, e.g. NCT04368728.") },
68
+ annotations: readOnly,
69
+ }, (a) => run(() => toolGetTrial(a)));
70
+ server.registerTool("search_proteins", {
71
+ title: "Search UniProt",
72
+ description: "Search UniProtKB proteins by name, gene or keyword. Defaults to reviewed (Swiss-Prot) entries. Use organism_tax_id 9606 for human.",
73
+ inputSchema: {
74
+ query: z.string().min(1).describe("UniProt query, e.g. 'insulin receptor' or 'gene:TP53'."),
75
+ organism_tax_id: z.number().int().optional().describe("NCBI taxonomy ID, e.g. 9606 human, 10090 mouse."),
76
+ reviewed_only: z.boolean().optional().describe("Default true."),
77
+ max_results: z.number().int().min(1).max(50).optional().describe("Default 10."),
78
+ },
79
+ annotations: readOnly,
80
+ }, (a) => run(() => toolSearchProteins(a)));
81
+ server.registerTool("get_protein", {
82
+ title: "Get a UniProt entry",
83
+ description: "Get function, subcellular location, disease associations, keywords and key cross-references for a UniProt accession.",
84
+ inputSchema: { accession: z.string().describe("UniProt accession, e.g. P38398.") },
85
+ annotations: readOnly,
86
+ }, (a) => run(() => toolGetProtein(a)));
87
+ server.registerTool("lookup_gene", {
88
+ title: "Look up a gene in Ensembl",
89
+ description: "Look up a gene by symbol or Ensembl ID: description, biotype, genomic location and canonical transcript.",
90
+ inputSchema: {
91
+ symbol_or_id: z.string().describe("Gene symbol (BRCA1) or Ensembl gene ID (ENSG00000012048)."),
92
+ species: z.string().optional().describe("Ensembl species name, default homo_sapiens."),
93
+ },
94
+ annotations: readOnly,
95
+ }, (a) => run(() => toolLookupGene(a)));
96
+ // ----- Pro tools -----
97
+ server.registerTool("evidence_pack", {
98
+ title: "Evidence pack (Pro)",
99
+ description: "PRO. Build a cited evidence pack on a research question: ranks papers by study design (meta-analyses and RCTs first), extracts conclusions from abstracts, lists related clinical trials and returns numbered references ready to cite.",
100
+ inputSchema: {
101
+ topic: z.string().min(3).describe("Research question or topic, e.g. 'vitamin D supplementation and fracture risk'."),
102
+ max_papers: z.number().int().min(3).max(40).optional().describe("Default 15."),
103
+ high_level_only: z.boolean().optional().describe("Only meta-analyses, systematic reviews, RCTs and guidelines."),
104
+ from_year: z.number().int().min(1800).max(2100).optional(),
105
+ include_trials: z.boolean().optional().describe("Default true."),
106
+ },
107
+ annotations: readOnly,
108
+ }, (a) => pro("evidence_pack", () => toolEvidencePack(a)));
109
+ server.registerTool("gene_dossier", {
110
+ title: "Gene dossier (Pro)",
111
+ description: "PRO. One-call cross-database profile of a gene: Ensembl genomic context, reviewed UniProt protein function and disease links, key PubMed papers and related clinical trials.",
112
+ inputSchema: {
113
+ gene: z.string().describe("Gene symbol or Ensembl ID, e.g. EGFR."),
114
+ species: z.string().optional().describe("Ensembl species name, default homo_sapiens."),
115
+ max_papers: z.number().int().min(1).max(20).optional().describe("Default 8."),
116
+ },
117
+ annotations: readOnly,
118
+ }, (a) => pro("gene_dossier", () => toolGeneDossier(a)));
119
+ server.registerTool("export_citations", {
120
+ title: "Export citations (Pro)",
121
+ description: "PRO. Export up to 200 PubMed IDs as RIS (Zotero, EndNote, Mendeley) or BibTeX.",
122
+ inputSchema: {
123
+ pmids: z.array(z.string()).min(1).max(200),
124
+ format: z.enum(["ris", "bibtex"]),
125
+ },
126
+ annotations: readOnly,
127
+ }, (a) => pro("export_citations", () => toolExportCitations(a)));
128
+ server.registerTool("biodata_status", {
129
+ title: "BioData MCP status",
130
+ description: "Show the server version, licence tier and which tools are available.",
131
+ inputSchema: {},
132
+ annotations: { readOnlyHint: true, openWorldHint: false },
133
+ }, async () => {
134
+ const lic = await getLicence();
135
+ return ok([
136
+ `BioData MCP v${VERSION}`,
137
+ `Tier: ${lic.valid ? `Pro (${lic.holder ?? "licensed"}${lic.expires ? `, expires ${lic.expires.slice(0, 10)}` : ""})` : "Free"}`,
138
+ lic.note ? `Note: ${lic.note}` : "",
139
+ lic.valid ? "" : `Upgrade: ${UPGRADE_URL}${lic.reason ? ` (${lic.reason})` : ""}`,
140
+ `NCBI API key: ${process.env.NCBI_API_KEY ? "set (10 req/s)" : "not set (3 req/s)"}`,
141
+ "Free: search_pubmed, get_pubmed_articles, search_trials, get_trial, search_proteins, get_protein, lookup_gene",
142
+ "Pro: evidence_pack, gene_dossier, export_citations, get_pubmed_articles up to 50 per call",
143
+ ]
144
+ .filter(Boolean)
145
+ .join("\n"));
146
+ });
147
+ return server;
148
+ }
149
+ async function main() {
150
+ const server = createServer();
151
+ await server.connect(new StdioServerTransport());
152
+ console.error(`biodata-mcp v${VERSION} running on stdio`);
153
+ }
154
+ main().catch((err) => {
155
+ console.error("Fatal:", err);
156
+ process.exit(1);
157
+ });
@@ -0,0 +1,8 @@
1
+ // Fill these in once your Polar product exists (see LAUNCH.md, step "Set up Polar").
2
+ // Both values are safe to publish.
3
+ /** Your Polar organization ID (Polar dashboard → Settings → Organization ID). */
4
+ export const POLAR_ORGANIZATION_ID = "e39dfc88-1017-408a-b038-8c3fcd847e65";
5
+ /** Hosted Polar checkout link for BioData MCP Pro. Shown to free users. */
6
+ export const DEFAULT_UPGRADE_URL = "https://buy.polar.sh/polar_cl_izX9bcMQvKqrvU4t66u2P4pp07GycLlSpQoSq45gkOW";
7
+ /** Polar API base. Polar's sandbox is https://sandbox-api.polar.sh for testing. */
8
+ export const POLAR_API_BASE = process.env.BIODATA_POLAR_API ?? "https://api.polar.sh";
@@ -0,0 +1,2 @@
1
+ // Generated by `npm run keys:init`. Leave empty until you have created your signing key pair.
2
+ export const PUBLIC_KEY_PEM = "";
@@ -0,0 +1,113 @@
1
+ // Licence checks for BioData MCP Pro.
2
+ //
3
+ // Two kinds of key are accepted:
4
+ // 1. Polar keys (issued automatically when someone buys on Polar). Checked online against
5
+ // Polar's public validate endpoint, cached for 6 hours.
6
+ // 2. Offline keys starting "bd1." (issued by you with `npm run keys:issue`, e.g. for testers
7
+ // and reviewers). Signed with Ed25519; only the public key ships in the package.
8
+ import { createPublicKey, verify } from "node:crypto";
9
+ import { PUBLIC_KEY_PEM } from "./license-pubkey.js";
10
+ import { DEFAULT_UPGRADE_URL, POLAR_API_BASE, POLAR_ORGANIZATION_ID } from "./license-config.js";
11
+ const OFFLINE_PREFIX = "bd1.";
12
+ const CACHE_MS = 6 * 60 * 60 * 1000;
13
+ function b64urlDecode(s) {
14
+ return Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64");
15
+ }
16
+ export function checkOfflineKey(key, publicKeyPem = PUBLIC_KEY_PEM) {
17
+ if (!publicKeyPem)
18
+ return { valid: false, reason: "This build has no offline-key public key configured." };
19
+ const [payloadB64, sigB64] = key.slice(OFFLINE_PREFIX.length).split(".");
20
+ if (!payloadB64 || !sigB64)
21
+ return { valid: false, reason: "Licence key is incomplete." };
22
+ let ok = false;
23
+ try {
24
+ ok = verify(null, Buffer.from(payloadB64), createPublicKey(publicKeyPem), b64urlDecode(sigB64));
25
+ }
26
+ catch {
27
+ ok = false;
28
+ }
29
+ if (!ok)
30
+ return { valid: false, reason: "Licence key signature is invalid." };
31
+ let payload;
32
+ try {
33
+ payload = JSON.parse(b64urlDecode(payloadB64).toString("utf8"));
34
+ }
35
+ catch {
36
+ return { valid: false, reason: "Licence key payload is unreadable." };
37
+ }
38
+ if (payload.exp && Date.parse(payload.exp) < Date.now()) {
39
+ return { valid: false, reason: `Licence expired on ${payload.exp.slice(0, 10)}.`, holder: payload.sub };
40
+ }
41
+ return { valid: true, source: "offline", plan: payload.plan ?? "pro", holder: payload.sub, expires: payload.exp ?? null };
42
+ }
43
+ export async function checkPolarKey(key, organizationId = POLAR_ORGANIZATION_ID) {
44
+ if (!organizationId)
45
+ return { valid: false, reason: "This build has no Polar organization configured." };
46
+ let res;
47
+ try {
48
+ res = await fetch(`${POLAR_API_BASE}/v1/customer-portal/license-keys/validate`, {
49
+ method: "POST",
50
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
51
+ body: JSON.stringify({ key, organization_id: organizationId }),
52
+ signal: AbortSignal.timeout(10_000),
53
+ });
54
+ }
55
+ catch {
56
+ // The research tools need the internet anyway, so a brief outage at Polar should not lock out a paying user.
57
+ return { valid: true, source: "polar", note: "Could not reach Polar to confirm the key; Pro is enabled for now." };
58
+ }
59
+ if (res.status === 404)
60
+ return { valid: false, reason: "Licence key not found, revoked or expired." };
61
+ if (res.status === 422 || res.status === 400)
62
+ return { valid: false, reason: "Licence key was rejected by Polar." };
63
+ if (!res.ok) {
64
+ return { valid: true, source: "polar", note: `Polar returned HTTP ${res.status}; Pro is enabled for now.` };
65
+ }
66
+ let body;
67
+ try {
68
+ body = await res.json();
69
+ }
70
+ catch {
71
+ return { valid: true, source: "polar", note: "Unexpected reply from Polar; Pro is enabled for now." };
72
+ }
73
+ if (body.status !== "granted")
74
+ return { valid: false, reason: `Licence status is "${body.status ?? "unknown"}".` };
75
+ if (body.expires_at && Date.parse(body.expires_at) < Date.now()) {
76
+ return { valid: false, reason: `Licence expired on ${body.expires_at.slice(0, 10)}.` };
77
+ }
78
+ return {
79
+ valid: true,
80
+ source: "polar",
81
+ plan: "pro",
82
+ holder: body.customer?.email ?? body.customer?.name ?? undefined,
83
+ expires: body.expires_at ?? null,
84
+ };
85
+ }
86
+ let cached;
87
+ /** Resolves the current licence, caching the result for 6 hours. */
88
+ export function getLicence(key = process.env.BIODATA_LICENSE_KEY) {
89
+ const k = key?.trim();
90
+ if (!k)
91
+ return Promise.resolve({ valid: false, reason: "No licence key set (BIODATA_LICENSE_KEY)." });
92
+ if (k.startsWith(OFFLINE_PREFIX))
93
+ return Promise.resolve(checkOfflineKey(k));
94
+ if (cached && cached.key === k && Date.now() - cached.at < CACHE_MS)
95
+ return cached.info;
96
+ const info = checkPolarKey(k);
97
+ cached = { key: k, at: Date.now(), info };
98
+ return info;
99
+ }
100
+ export function resetLicenceCache() {
101
+ cached = undefined;
102
+ }
103
+ export const UPGRADE_URL = process.env.BIODATA_UPGRADE_URL ?? DEFAULT_UPGRADE_URL;
104
+ export function upgradeMessage(tool, reason) {
105
+ return [
106
+ `"${tool}" is a BioData MCP Pro tool.`,
107
+ reason ? `Licence check: ${reason}` : "",
108
+ `Get a Pro key at ${UPGRADE_URL}, then set BIODATA_LICENSE_KEY in your MCP client config and restart it.`,
109
+ "Free tools (search_pubmed, get_pubmed_articles, search_trials, get_trial, search_proteins, get_protein, lookup_gene) keep working without a key.",
110
+ ]
111
+ .filter(Boolean)
112
+ .join("\n");
113
+ }
@@ -0,0 +1,29 @@
1
+ // Ensembl REST API (https://rest.ensembl.org).
2
+ import { fetchJson, qs } from "../http.js";
3
+ const BASE = "https://rest.ensembl.org";
4
+ function toGene(d) {
5
+ const strand = d.strand === 1 ? "+" : d.strand === -1 ? "-" : "";
6
+ const species = d.species ?? "";
7
+ return {
8
+ ensemblId: d.id ?? "",
9
+ symbol: d.display_name ?? "",
10
+ description: (d.description ?? "").replace(/\s*\[Source:.*\]$/, ""),
11
+ biotype: d.biotype ?? "",
12
+ species,
13
+ location: d.seq_region_name
14
+ ? `${d.seq_region_name}:${d.start}-${d.end}${strand ? ` (${strand})` : ""}`
15
+ : "",
16
+ assembly: d.assembly_name ?? "",
17
+ canonicalTranscript: d.canonical_transcript,
18
+ url: `https://www.ensembl.org/${species ? species.charAt(0).toUpperCase() + species.slice(1) : "Homo_sapiens"}/Gene/Summary?g=${d.id ?? ""}`,
19
+ };
20
+ }
21
+ export async function lookupGene(symbolOrId, species = "homo_sapiens") {
22
+ const q = symbolOrId.trim();
23
+ const isId = /^ENS[A-Z]*G\d{11}(\.\d+)?$/i.test(q);
24
+ const path = isId
25
+ ? `/lookup/id/${encodeURIComponent(q)}`
26
+ : `/lookup/symbol/${encodeURIComponent(species)}/${encodeURIComponent(q)}`;
27
+ const d = await fetchJson(`${BASE}${path}?${qs({ "content-type": "application/json" })}`);
28
+ return toGene(d);
29
+ }
@@ -0,0 +1,145 @@
1
+ // PubMed via NCBI E-utilities (https://www.ncbi.nlm.nih.gov/books/NBK25501/).
2
+ import { fetchJson, fetchText, qs } from "../http.js";
3
+ const BASE = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils";
4
+ function commonParams() {
5
+ return {
6
+ tool: "biodata-mcp",
7
+ email: process.env.NCBI_EMAIL,
8
+ api_key: process.env.NCBI_API_KEY,
9
+ };
10
+ }
11
+ export async function searchPubMed(query, opts = {}) {
12
+ let term = query.trim();
13
+ if (opts.fromYear || opts.toYear) {
14
+ const from = opts.fromYear ?? 1800;
15
+ const to = opts.toYear ?? 3000;
16
+ term = `(${term}) AND ${from}:${to}[dp]`;
17
+ }
18
+ const url = `${BASE}/esearch.fcgi?${qs({
19
+ db: "pubmed",
20
+ term,
21
+ retmax: Math.min(opts.max ?? 10, 100),
22
+ sort: opts.sort === "pub_date" ? "pub_date" : "relevance",
23
+ retmode: "json",
24
+ ...commonParams(),
25
+ })}`;
26
+ const data = await fetchJson(url);
27
+ const r = data.esearchresult ?? {};
28
+ return { total: Number(r.count ?? 0), ids: r.idlist ?? [] };
29
+ }
30
+ export async function summarisePubMed(ids) {
31
+ if (ids.length === 0)
32
+ return [];
33
+ const url = `${BASE}/esummary.fcgi?${qs({
34
+ db: "pubmed",
35
+ id: ids.join(","),
36
+ retmode: "json",
37
+ ...commonParams(),
38
+ })}`;
39
+ const data = await fetchJson(url);
40
+ const result = data.result ?? {};
41
+ const uids = result.uids ?? ids;
42
+ return uids
43
+ .map((uid) => result[uid])
44
+ .filter((d) => d && !d.error)
45
+ .map((d) => {
46
+ const doi = (d.articleids ?? []).find((a) => a.idtype === "doi")?.value;
47
+ const pubDate = d.pubdate ?? "";
48
+ return {
49
+ pmid: String(d.uid),
50
+ title: stripTags(d.title ?? ""),
51
+ journal: d.fulljournalname || d.source || "",
52
+ pubDate,
53
+ year: (pubDate.match(/\d{4}/) ?? [""])[0],
54
+ authors: (d.authors ?? []).map((a) => a.name).filter(Boolean),
55
+ doi,
56
+ pubTypes: d.pubtype ?? [],
57
+ url: `https://pubmed.ncbi.nlm.nih.gov/${d.uid}/`,
58
+ };
59
+ });
60
+ }
61
+ export async function fetchPubMedArticles(ids) {
62
+ if (ids.length === 0)
63
+ return [];
64
+ const [summaries, xml] = await Promise.all([
65
+ summarisePubMed(ids),
66
+ fetchText(`${BASE}/efetch.fcgi?${qs({
67
+ db: "pubmed",
68
+ id: ids.join(","),
69
+ rettype: "abstract",
70
+ retmode: "xml",
71
+ ...commonParams(),
72
+ })}`, "application/xml"),
73
+ ]);
74
+ const byPmid = parsePubMedXml(xml);
75
+ return summaries.map((s) => ({
76
+ ...s,
77
+ abstract: byPmid.get(s.pmid)?.abstract ?? "",
78
+ meshTerms: byPmid.get(s.pmid)?.mesh ?? [],
79
+ }));
80
+ }
81
+ /** Minimal, dependency-free extraction of abstracts and MeSH terms from PubMed XML. */
82
+ export function parsePubMedXml(xml) {
83
+ const out = new Map();
84
+ const articles = xml.split(/<PubmedArticle[\s>]/).slice(1);
85
+ for (const art of articles) {
86
+ const pmid = art.match(/<PMID[^>]*>(\d+)<\/PMID>/)?.[1];
87
+ if (!pmid)
88
+ continue;
89
+ const parts = [];
90
+ for (const m of art.matchAll(/<AbstractText([^>]*)>([\s\S]*?)<\/AbstractText>/g)) {
91
+ const label = m[1].match(/Label="([^"]+)"/)?.[1];
92
+ const text = decodeEntities(stripTags(m[2])).trim();
93
+ if (text)
94
+ parts.push(label ? `${label}: ${text}` : text);
95
+ }
96
+ const mesh = [...art.matchAll(/<DescriptorName[^>]*>([\s\S]*?)<\/DescriptorName>/g)].map((m) => decodeEntities(stripTags(m[1])).trim());
97
+ out.set(pmid, { abstract: parts.join("\n\n"), mesh });
98
+ }
99
+ return out;
100
+ }
101
+ function stripTags(s) {
102
+ return s.replace(/<[^>]+>/g, "");
103
+ }
104
+ function decodeEntities(s) {
105
+ return s
106
+ .replace(/&lt;/g, "<")
107
+ .replace(/&gt;/g, ">")
108
+ .replace(/&quot;/g, '"')
109
+ .replace(/&apos;/g, "'")
110
+ .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
111
+ .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
112
+ .replace(/&amp;/g, "&");
113
+ }
114
+ /**
115
+ * Labels a paper by study design using PubMed publication-type tags.
116
+ * This is a design label, NOT a quality appraisal.
117
+ */
118
+ export function designLabel(pubTypes) {
119
+ const t = pubTypes.map((p) => p.toLowerCase());
120
+ const has = (x) => t.some((p) => p.includes(x));
121
+ if (has("meta-analysis"))
122
+ return { label: "Meta-analysis", rank: 1 };
123
+ if (has("systematic review"))
124
+ return { label: "Systematic review", rank: 2 };
125
+ if (has("randomized controlled trial"))
126
+ return { label: "Randomised controlled trial", rank: 3 };
127
+ if (has("clinical trial"))
128
+ return { label: "Clinical trial (other)", rank: 4 };
129
+ if (has("observational study") || has("comparative study"))
130
+ return { label: "Observational/comparative", rank: 5 };
131
+ if (has("practice guideline") || has("guideline"))
132
+ return { label: "Guideline", rank: 2 };
133
+ if (has("review"))
134
+ return { label: "Narrative review", rank: 6 };
135
+ if (has("case reports"))
136
+ return { label: "Case report", rank: 7 };
137
+ return { label: "Other / primary research", rank: 6 };
138
+ }
139
+ export function formatAuthors(authors, max = 3) {
140
+ if (authors.length === 0)
141
+ return "";
142
+ if (authors.length <= max)
143
+ return authors.join(", ");
144
+ return `${authors.slice(0, max).join(", ")} et al.`;
145
+ }
@@ -0,0 +1,72 @@
1
+ // ClinicalTrials.gov API v2 (https://clinicaltrials.gov/data-api/api).
2
+ import { fetchJson, qs } from "../http.js";
3
+ const BASE = "https://clinicaltrials.gov/api/v2/studies";
4
+ export const TRIAL_STATUSES = [
5
+ "RECRUITING",
6
+ "NOT_YET_RECRUITING",
7
+ "ACTIVE_NOT_RECRUITING",
8
+ "ENROLLING_BY_INVITATION",
9
+ "COMPLETED",
10
+ "TERMINATED",
11
+ "WITHDRAWN",
12
+ "SUSPENDED",
13
+ ];
14
+ function toSummary(study) {
15
+ const p = study?.protocolSection ?? {};
16
+ const id = p.identificationModule ?? {};
17
+ const status = p.statusModule ?? {};
18
+ const design = p.designModule ?? {};
19
+ const locs = p.contactsLocationsModule?.locations ?? [];
20
+ return {
21
+ nctId: id.nctId ?? "",
22
+ title: id.briefTitle ?? id.officialTitle ?? "",
23
+ status: status.overallStatus ?? "",
24
+ phases: design.phases ?? [],
25
+ studyType: design.studyType ?? "",
26
+ conditions: p.conditionsModule?.conditions ?? [],
27
+ interventions: (p.armsInterventionsModule?.interventions ?? []).map((i) => i.type ? `${i.name} (${i.type.toLowerCase()})` : i.name),
28
+ sponsor: p.sponsorCollaboratorsModule?.leadSponsor?.name ?? "",
29
+ startDate: status.startDateStruct?.date ?? "",
30
+ enrollment: design.enrollmentInfo?.count,
31
+ countries: [...new Set(locs.map((l) => l.country).filter(Boolean))],
32
+ hasResults: Boolean(study?.hasResults),
33
+ url: `https://clinicaltrials.gov/study/${id.nctId ?? ""}`,
34
+ };
35
+ }
36
+ export async function searchTrials(opts) {
37
+ const url = `${BASE}?${qs({
38
+ "query.term": opts.query,
39
+ "query.cond": opts.condition,
40
+ "query.intr": opts.intervention,
41
+ "query.locn": opts.country,
42
+ "filter.overallStatus": opts.statuses?.length ? opts.statuses.join(",") : undefined,
43
+ pageSize: Math.min(opts.max ?? 10, 50),
44
+ countTotal: "true",
45
+ format: "json",
46
+ })}`;
47
+ const data = await fetchJson(url);
48
+ return { total: data.totalCount, trials: (data.studies ?? []).map(toSummary) };
49
+ }
50
+ export async function getTrial(nctId) {
51
+ const id = nctId.trim().toUpperCase();
52
+ if (!/^NCT\d{8}$/.test(id)) {
53
+ throw new Error(`"${nctId}" is not a valid NCT ID (expected NCT followed by 8 digits).`);
54
+ }
55
+ const study = await fetchJson(`${BASE}/${id}?${qs({ format: "json" })}`);
56
+ const p = study?.protocolSection ?? {};
57
+ const elig = p.eligibilityModule ?? {};
58
+ return {
59
+ ...toSummary(study),
60
+ summary: p.descriptionModule?.briefSummary ?? "",
61
+ eligibility: elig.eligibilityCriteria ?? "",
62
+ minAge: elig.minimumAge,
63
+ maxAge: elig.maximumAge,
64
+ sex: elig.sex,
65
+ primaryOutcomes: (p.outcomesModule?.primaryOutcomes ?? []).map((o) => o.timeFrame ? `${o.measure} (time frame: ${o.timeFrame})` : o.measure),
66
+ locations: (p.contactsLocationsModule?.locations ?? []).map((l) => ({
67
+ facility: l.facility ?? "",
68
+ city: l.city ?? "",
69
+ country: l.country ?? "",
70
+ })),
71
+ };
72
+ }
@@ -0,0 +1,81 @@
1
+ // UniProt REST API (https://www.uniprot.org/help/api).
2
+ import { fetchJson, qs } from "../http.js";
3
+ const BASE = "https://rest.uniprot.org/uniprotkb";
4
+ function proteinName(e) {
5
+ const d = e?.proteinDescription ?? {};
6
+ return (d.recommendedName?.fullName?.value ??
7
+ d.submissionNames?.[0]?.fullName?.value ??
8
+ d.alternativeNames?.[0]?.fullName?.value ??
9
+ "");
10
+ }
11
+ function toSummary(e) {
12
+ const acc = e?.primaryAccession ?? "";
13
+ return {
14
+ accession: acc,
15
+ entryName: e?.uniProtkbId ?? "",
16
+ reviewed: String(e?.entryType ?? "").toLowerCase().includes("reviewed") &&
17
+ !String(e?.entryType ?? "").toLowerCase().includes("unreviewed"),
18
+ proteinName: proteinName(e),
19
+ genes: (e?.genes ?? []).map((g) => g.geneName?.value).filter(Boolean),
20
+ organism: e?.organism?.scientificName ?? "",
21
+ length: e?.sequence?.length,
22
+ url: `https://www.uniprot.org/uniprotkb/${acc}/entry`,
23
+ };
24
+ }
25
+ export async function searchProteins(opts) {
26
+ const parts = [`(${opts.query.trim()})`];
27
+ if (opts.organismTaxId)
28
+ parts.push(`(organism_id:${opts.organismTaxId})`);
29
+ if (opts.reviewedOnly)
30
+ parts.push("(reviewed:true)");
31
+ const url = `${BASE}/search?${qs({
32
+ query: parts.join(" AND "),
33
+ format: "json",
34
+ size: Math.min(opts.max ?? 10, 50),
35
+ fields: "accession,id,protein_name,gene_names,organism_name,length,reviewed",
36
+ })}`;
37
+ const data = await fetchJson(url);
38
+ return (data.results ?? []).map(toSummary);
39
+ }
40
+ const KEEP_XREFS = new Set(["PDB", "Ensembl", "HGNC", "MIM", "Reactome", "STRING", "AlphaFoldDB", "GeneID"]);
41
+ export async function getProtein(accession) {
42
+ const acc = accession.trim().toUpperCase();
43
+ if (!/^[A-Z0-9]{6,10}(-\d+)?$/.test(acc)) {
44
+ throw new Error(`"${accession}" does not look like a UniProt accession (e.g. P38398).`);
45
+ }
46
+ const e = await fetchJson(`${BASE}/${acc}.json`);
47
+ const comments = e?.comments ?? [];
48
+ const texts = (type) => comments
49
+ .filter((c) => c.commentType === type)
50
+ .flatMap((c) => (c.texts ?? []).map((t) => t.value))
51
+ .filter(Boolean);
52
+ const subcell = comments
53
+ .filter((c) => c.commentType === "SUBCELLULAR LOCATION")
54
+ .flatMap((c) => (c.subcellularLocations ?? []).map((s) => s.location?.value))
55
+ .filter(Boolean);
56
+ const diseases = comments
57
+ .filter((c) => c.commentType === "DISEASE" && c.disease)
58
+ .map((c) => ({
59
+ name: c.disease.diseaseId ?? c.disease.acronym ?? "",
60
+ description: c.disease.description ?? "",
61
+ }));
62
+ const xrefs = [];
63
+ const seen = new Map();
64
+ for (const x of e?.uniProtKBCrossReferences ?? []) {
65
+ if (!KEEP_XREFS.has(x.database))
66
+ continue;
67
+ const n = seen.get(x.database) ?? 0;
68
+ if (n >= 5)
69
+ continue;
70
+ seen.set(x.database, n + 1);
71
+ xrefs.push({ db: x.database, id: x.id });
72
+ }
73
+ return {
74
+ ...toSummary(e),
75
+ function: texts("FUNCTION"),
76
+ subcellularLocation: [...new Set(subcell)],
77
+ diseases,
78
+ keywords: (e?.keywords ?? []).map((k) => k.name).filter(Boolean),
79
+ crossRefs: xrefs,
80
+ };
81
+ }
package/dist/tools.js ADDED
@@ -0,0 +1,273 @@
1
+ // Tool implementations. Each returns Markdown text that the AI client reads and cites.
2
+ import { designLabel, fetchPubMedArticles, formatAuthors, searchPubMed, summarisePubMed, } from "./sources/pubmed.js";
3
+ import { getTrial, searchTrials } from "./sources/trials.js";
4
+ import { getProtein, searchProteins } from "./sources/uniprot.js";
5
+ import { lookupGene } from "./sources/ensembl.js";
6
+ import { toBibtex, toRis, truncate } from "./format.js";
7
+ export const FREE_ARTICLE_LIMIT = 5;
8
+ export const PRO_ARTICLE_LIMIT = 50;
9
+ const SPECIES_TAXID = {
10
+ homo_sapiens: 9606,
11
+ mus_musculus: 10090,
12
+ rattus_norvegicus: 10116,
13
+ danio_rerio: 7955,
14
+ drosophila_melanogaster: 7227,
15
+ saccharomyces_cerevisiae: 559292,
16
+ };
17
+ const FOOTER = "_Data retrieved live from public databases. Summaries are for research use and are not medical advice._";
18
+ // ---------- Free tools ----------
19
+ export async function toolSearchPubMed(a) {
20
+ const { total, ids } = await searchPubMed(a.query, {
21
+ max: a.max_results ?? 10,
22
+ sort: a.sort,
23
+ fromYear: a.from_year,
24
+ toYear: a.to_year,
25
+ });
26
+ if (ids.length === 0)
27
+ return `No PubMed results for "${a.query}". Try broader terms or remove year filters.`;
28
+ const items = await summarisePubMed(ids);
29
+ const lines = items.map((p, i) => {
30
+ const d = designLabel(p.pubTypes).label;
31
+ return `${i + 1}. **${p.title}** — ${formatAuthors(p.authors)} _${p.journal}_ (${p.year}). Design tag: ${d}. PMID [${p.pmid}](${p.url})${p.doi ? `, DOI ${p.doi}` : ""}`;
32
+ });
33
+ return [
34
+ `### PubMed: "${a.query}"`,
35
+ `Showing ${items.length} of ${total.toLocaleString("en")} matches (${a.sort === "pub_date" ? "newest first" : "by relevance"}).`,
36
+ "",
37
+ ...lines,
38
+ "",
39
+ "Use get_pubmed_articles with these PMIDs to read abstracts.",
40
+ ].join("\n");
41
+ }
42
+ export async function toolGetPubMedArticles(a, isPro) {
43
+ const limit = isPro ? PRO_ARTICLE_LIMIT : FREE_ARTICLE_LIMIT;
44
+ const clean = [...new Set(a.pmids.map((p) => p.trim().replace(/^PMID:?\s*/i, "")))].filter((p) => /^\d{1,9}$/.test(p));
45
+ if (clean.length === 0)
46
+ return "No valid PMIDs given. PMIDs are numbers such as 31234567.";
47
+ const used = clean.slice(0, limit);
48
+ const arts = await fetchPubMedArticles(used);
49
+ const blocks = arts.map((p) => [
50
+ `#### ${p.title}`,
51
+ `${formatAuthors(p.authors, 6)} — _${p.journal}_, ${p.pubDate}. PMID [${p.pmid}](${p.url})${p.doi ? ` · DOI ${p.doi}` : ""}`,
52
+ `Design tag: ${designLabel(p.pubTypes).label}${p.meshTerms.length ? ` · MeSH: ${p.meshTerms.slice(0, 8).join("; ")}` : ""}`,
53
+ "",
54
+ p.abstract ? p.abstract : "_No abstract available in PubMed._",
55
+ ].join("\n"));
56
+ const note = clean.length > used.length
57
+ ? `\n\n> Returned ${used.length} of ${clean.length} requested. ${isPro ? "" : `The free tier reads up to ${FREE_ARTICLE_LIMIT} articles per call; Pro reads up to ${PRO_ARTICLE_LIMIT}.`}`
58
+ : "";
59
+ return blocks.join("\n\n---\n\n") + note + `\n\n${FOOTER}`;
60
+ }
61
+ export async function toolSearchTrials(a) {
62
+ if (!a.query && !a.condition && !a.intervention) {
63
+ return "Give at least one of: query, condition or intervention.";
64
+ }
65
+ const { total, trials } = await searchTrials({
66
+ query: a.query,
67
+ condition: a.condition,
68
+ intervention: a.intervention,
69
+ country: a.country,
70
+ statuses: a.status,
71
+ max: a.max_results ?? 10,
72
+ });
73
+ if (trials.length === 0)
74
+ return "No matching trials on ClinicalTrials.gov. Try fewer filters.";
75
+ const lines = trials.map((t, i) => `${i + 1}. **${t.title}** — [${t.nctId}](${t.url}) · ${t.status}${t.phases.length ? ` · ${t.phases.join("/")}` : ""} · ${t.studyType}` +
76
+ `\n Conditions: ${truncate(t.conditions.join("; "), 160) || "n/a"} · Interventions: ${truncate(t.interventions.join("; "), 160) || "n/a"}` +
77
+ `\n Sponsor: ${t.sponsor || "n/a"} · Start: ${t.startDate || "n/a"}${t.enrollment ? ` · Enrolment: ${t.enrollment}` : ""}${t.countries.length ? ` · Countries: ${truncate(t.countries.join(", "), 120)}` : ""}${t.hasResults ? " · Results posted" : ""}`);
78
+ return [
79
+ "### ClinicalTrials.gov results",
80
+ total !== undefined ? `Showing ${trials.length} of ${total.toLocaleString("en")} matching studies.` : "",
81
+ "",
82
+ ...lines,
83
+ ]
84
+ .filter((l) => l !== "")
85
+ .join("\n");
86
+ }
87
+ export async function toolGetTrial(a) {
88
+ const t = await getTrial(a.nct_id);
89
+ const locs = t.locations.slice(0, 15).map((l) => `- ${[l.facility, l.city, l.country].filter(Boolean).join(", ")}`);
90
+ return [
91
+ `### ${t.title}`,
92
+ `[${t.nctId}](${t.url}) · ${t.status}${t.phases.length ? ` · ${t.phases.join("/")}` : ""} · ${t.studyType} · Sponsor: ${t.sponsor || "n/a"}`,
93
+ `Start: ${t.startDate || "n/a"}${t.enrollment ? ` · Enrolment: ${t.enrollment}` : ""}${t.hasResults ? " · Results posted" : ""}`,
94
+ "",
95
+ `**Conditions:** ${t.conditions.join("; ") || "n/a"}`,
96
+ `**Interventions:** ${t.interventions.join("; ") || "n/a"}`,
97
+ "",
98
+ "**Summary**",
99
+ t.summary || "n/a",
100
+ "",
101
+ "**Primary outcomes**",
102
+ ...(t.primaryOutcomes.length ? t.primaryOutcomes.map((o) => `- ${o}`) : ["- n/a"]),
103
+ "",
104
+ `**Eligibility** (age ${t.minAge ?? "n/a"} to ${t.maxAge ?? "n/a"}, sex: ${t.sex ?? "n/a"})`,
105
+ truncate(t.eligibility || "n/a", 4000),
106
+ "",
107
+ `**Locations** (${t.locations.length} total${t.locations.length > 15 ? ", first 15 shown" : ""})`,
108
+ ...(locs.length ? locs : ["- n/a"]),
109
+ "",
110
+ FOOTER,
111
+ ].join("\n");
112
+ }
113
+ export async function toolSearchProteins(a) {
114
+ const res = await searchProteins({
115
+ query: a.query,
116
+ organismTaxId: a.organism_tax_id,
117
+ reviewedOnly: a.reviewed_only ?? true,
118
+ max: a.max_results ?? 10,
119
+ });
120
+ if (res.length === 0)
121
+ return `No UniProt entries for "${a.query}". Try reviewed_only=false or a different organism.`;
122
+ return [
123
+ `### UniProt: "${a.query}"`,
124
+ "",
125
+ ...res.map((p, i) => `${i + 1}. **${p.proteinName || p.entryName}** — [${p.accession}](${p.url}) (${p.entryName}) · Genes: ${p.genes.join(", ") || "n/a"} · ${p.organism}${p.length ? ` · ${p.length} aa` : ""} · ${p.reviewed ? "Reviewed (Swiss-Prot)" : "Unreviewed (TrEMBL)"}`),
126
+ ].join("\n");
127
+ }
128
+ export async function toolGetProtein(a) {
129
+ const p = await getProtein(a.accession);
130
+ return [
131
+ `### ${p.proteinName || p.entryName} (${p.accession})`,
132
+ `[UniProt entry](${p.url}) · ${p.entryName} · Genes: ${p.genes.join(", ") || "n/a"} · ${p.organism}${p.length ? ` · ${p.length} aa` : ""} · ${p.reviewed ? "Reviewed" : "Unreviewed"}`,
133
+ "",
134
+ "**Function**",
135
+ ...(p.function.length ? p.function.map((f) => truncate(f, 1500)) : ["n/a"]),
136
+ "",
137
+ `**Subcellular location:** ${p.subcellularLocation.join("; ") || "n/a"}`,
138
+ "",
139
+ "**Disease associations**",
140
+ ...(p.diseases.length ? p.diseases.map((d) => `- ${d.name}: ${truncate(d.description, 300)}`) : ["- None annotated"]),
141
+ "",
142
+ `**Keywords:** ${p.keywords.slice(0, 20).join(", ") || "n/a"}`,
143
+ `**Cross-references:** ${p.crossRefs.map((x) => `${x.db}:${x.id}`).join(", ") || "n/a"}`,
144
+ ].join("\n");
145
+ }
146
+ export async function toolLookupGene(a) {
147
+ const g = await lookupGene(a.symbol_or_id, a.species ?? "homo_sapiens");
148
+ return [
149
+ `### ${g.symbol} (${g.ensemblId})`,
150
+ `${g.description || "No description"}`,
151
+ `Species: ${g.species} · Biotype: ${g.biotype} · Location: ${g.location || "n/a"} (${g.assembly || "assembly n/a"})`,
152
+ g.canonicalTranscript ? `Canonical transcript: ${g.canonicalTranscript}` : "",
153
+ `[Ensembl gene page](${g.url})`,
154
+ ]
155
+ .filter(Boolean)
156
+ .join("\n");
157
+ }
158
+ // ---------- Pro tools ----------
159
+ const HIGH_LEVEL_FILTER = '(meta-analysis[pt] OR systematic review[pt] OR randomized controlled trial[pt] OR practice guideline[pt] OR guideline[pt])';
160
+ export async function toolEvidencePack(a) {
161
+ const max = Math.min(a.max_papers ?? 15, 40);
162
+ const query = a.high_level_only ? `(${a.topic}) AND ${HIGH_LEVEL_FILTER}` : a.topic;
163
+ const [{ total, ids }, trialsRes] = await Promise.all([
164
+ searchPubMed(query, { max, fromYear: a.from_year }),
165
+ a.include_trials === false
166
+ ? Promise.resolve({ total: 0, trials: [] })
167
+ : searchTrials({ query: a.topic, max: 8 }).catch(() => ({ total: undefined, trials: [] })),
168
+ ]);
169
+ const arts = ids.length ? await fetchPubMedArticles(ids) : [];
170
+ const ranked = arts
171
+ .map((p) => ({ p, d: designLabel(p.pubTypes) }))
172
+ .sort((x, y) => x.d.rank - y.d.rank || Number(y.p.year || 0) - Number(x.p.year || 0));
173
+ const counts = new Map();
174
+ for (const r of ranked)
175
+ counts.set(r.d.label, (counts.get(r.d.label) ?? 0) + 1);
176
+ const table = [
177
+ "| # | Study design (PubMed tag) | Year | Title | Ref |",
178
+ "|---|---|---|---|---|",
179
+ ...ranked.map((r, i) => `| ${i + 1} | ${r.d.label} | ${r.p.year || "n/a"} | ${truncate(r.p.title.replace(/\|/g, "/"), 110)} | [${i + 1}] |`),
180
+ ];
181
+ const keyFindings = ranked.slice(0, 8).map((r, i) => {
182
+ const abs = r.p.abstract;
183
+ const concl = abs.match(/(?:CONCLUSIONS?|INTERPRETATION|FINDINGS|RESULTS)[^:]*:\s*([\s\S]+?)(?:\n\n|$)/i)?.[1] ?? abs;
184
+ return `[${i + 1}] ${truncate(concl.replace(/\s+/g, " "), 450) || "_No abstract available._"}`;
185
+ });
186
+ const refs = ranked.map((r, i) => `[${i + 1}] ${formatAuthors(r.p.authors)} ${r.p.title} _${r.p.journal}_. ${r.p.year}.${r.p.doi ? ` doi:${r.p.doi}.` : ""} PMID: ${r.p.pmid}. ${r.p.url}`);
187
+ const trials = trialsRes.trials.map((t) => `- [${t.nctId}](${t.url}) ${t.title} — ${t.status}${t.phases.length ? `, ${t.phases.join("/")}` : ""}${t.sponsor ? `, ${t.sponsor}` : ""}`);
188
+ return [
189
+ `## Evidence pack: ${a.topic}`,
190
+ `PubMed matches: ${total.toLocaleString("en")} · Papers analysed: ${ranked.length}${a.high_level_only ? " (meta-analyses, systematic reviews, RCTs and guidelines only)" : ""}${a.from_year ? ` · From ${a.from_year}` : ""}`,
191
+ `Design mix: ${[...counts.entries()].map(([k, v]) => `${k} ×${v}`).join(", ") || "n/a"}`,
192
+ "",
193
+ "### Evidence map (strongest study designs first)",
194
+ ...table,
195
+ "",
196
+ "### Key findings from abstracts (verbatim excerpts, for synthesis)",
197
+ ...keyFindings,
198
+ "",
199
+ ...(a.include_trials === false
200
+ ? []
201
+ : ["### Related clinical trials", ...(trials.length ? trials : ["- None found"]), ""]),
202
+ "### References",
203
+ ...refs,
204
+ "",
205
+ "> Design labels come from PubMed publication-type tags. They describe study design only and are not a quality or risk-of-bias appraisal.",
206
+ FOOTER,
207
+ ].join("\n");
208
+ }
209
+ export async function toolGeneDossier(a) {
210
+ const species = a.species ?? "homo_sapiens";
211
+ const taxId = SPECIES_TAXID[species];
212
+ const gene = await lookupGene(a.gene, species);
213
+ const symbol = gene.symbol || a.gene;
214
+ const [proteins, papers, trials] = await Promise.all([
215
+ searchProteins({ query: `gene_exact:${symbol}`, organismTaxId: taxId, reviewedOnly: true, max: 3 }).catch(() => []),
216
+ searchPubMed(`${symbol}[tiab]${species === "homo_sapiens" ? " AND humans[mh]" : ""}`, {
217
+ max: Math.min(a.max_papers ?? 8, 20),
218
+ sort: "relevance",
219
+ }).then((r) => summarisePubMed(r.ids)).catch(() => []),
220
+ species === "homo_sapiens"
221
+ ? searchTrials({ query: symbol, max: 5 }).then((r) => r.trials).catch(() => [])
222
+ : Promise.resolve([]),
223
+ ]);
224
+ const protein = proteins[0] ? await getProtein(proteins[0].accession).catch(() => undefined) : undefined;
225
+ return [
226
+ `## Gene dossier: ${symbol}`,
227
+ "",
228
+ "### Genomic context (Ensembl)",
229
+ `${gene.description || "n/a"} · ${gene.ensemblId} · ${gene.biotype} · ${gene.location} (${gene.assembly}) · [Ensembl](${gene.url})`,
230
+ "",
231
+ "### Protein (UniProt, reviewed)",
232
+ protein
233
+ ? [
234
+ `**${protein.proteinName}** — [${protein.accession}](${protein.url}) · ${protein.length ?? "?"} aa`,
235
+ `Function: ${truncate(protein.function.join(" "), 900) || "n/a"}`,
236
+ `Location: ${protein.subcellularLocation.join("; ") || "n/a"}`,
237
+ `Diseases: ${protein.diseases.map((d) => d.name).join("; ") || "none annotated"}`,
238
+ `Cross-refs: ${protein.crossRefs.map((x) => `${x.db}:${x.id}`).join(", ") || "n/a"}`,
239
+ ].join("\n")
240
+ : "No reviewed UniProt entry found.",
241
+ "",
242
+ "### Key literature (PubMed)",
243
+ ...(papers.length
244
+ ? papers.map((p, i) => `${i + 1}. ${p.title} — _${p.journal}_ (${p.year}). [PMID ${p.pmid}](${p.url})`)
245
+ : ["None found"]),
246
+ "",
247
+ ...(species === "homo_sapiens"
248
+ ? [
249
+ "### Clinical trials mentioning this gene",
250
+ ...(trials.length ? trials.map((t) => `- [${t.nctId}](${t.url}) ${t.title} — ${t.status}`) : ["- None found"]),
251
+ "",
252
+ ]
253
+ : []),
254
+ FOOTER,
255
+ ].join("\n");
256
+ }
257
+ export async function toolExportCitations(a) {
258
+ const clean = [...new Set(a.pmids.map((p) => p.trim().replace(/^PMID:?\s*/i, "")))].filter((p) => /^\d{1,9}$/.test(p));
259
+ if (clean.length === 0)
260
+ return "No valid PMIDs given.";
261
+ const items = [];
262
+ for (let i = 0; i < Math.min(clean.length, 200); i += 100) {
263
+ items.push(...(await summarisePubMed(clean.slice(i, i + 100))));
264
+ }
265
+ const body = a.format === "bibtex" ? toBibtex(items) : toRis(items);
266
+ return [
267
+ `${items.length} citation(s) in ${a.format === "bibtex" ? "BibTeX" : "RIS"} format${clean.length > 200 ? " (first 200 only)" : ""}. Save as a .${a.format === "bibtex" ? "bib" : "ris"} file to import into Zotero, EndNote or Mendeley.`,
268
+ "",
269
+ "```" + (a.format === "bibtex" ? "bibtex" : ""),
270
+ body,
271
+ "```",
272
+ ].join("\n");
273
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "biodata-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "MCP server that lets Claude, Cursor and other AI clients search PubMed, ClinicalTrials.gov, UniProt and Ensembl, with cited evidence packs.",
5
+ "type": "module",
6
+ "bin": {
7
+ "biodata-mcp": "dist/index.js"
8
+ },
9
+ "main": "dist/index.js",
10
+ "files": [
11
+ "dist",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "scripts": {
16
+ "build": "tsc",
17
+ "start": "node dist/index.js",
18
+ "prepublishOnly": "npm run build",
19
+ "test": "npm run build && node --test test/tools.test.mjs test/protocol.test.mjs",
20
+ "keys:init": "node scripts/keygen.mjs init",
21
+ "keys:issue": "node scripts/keygen.mjs issue"
22
+ },
23
+ "keywords": [
24
+ "mcp",
25
+ "model-context-protocol",
26
+ "pubmed",
27
+ "clinicaltrials",
28
+ "uniprot",
29
+ "ensembl",
30
+ "bioinformatics",
31
+ "biomedical",
32
+ "claude"
33
+ ],
34
+ "license": "SEE LICENSE IN LICENSE",
35
+ "author": "Root 7 (Pty) Ltd <hello@root7.co.za>",
36
+ "homepage": "https://github.com/kramdayal-create/biodata-mcp#readme",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/kramdayal-create/biodata-mcp.git"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/kramdayal-create/biodata-mcp/issues",
43
+ "email": "hello@root7.co.za"
44
+ },
45
+ "mcpName": "io.github.kramdayal-create/biodata-mcp",
46
+ "engines": {
47
+ "node": ">=18.17"
48
+ },
49
+ "dependencies": {
50
+ "@modelcontextprotocol/sdk": "^1.32.1",
51
+ "zod": "^4.6.7"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^22.0.0",
55
+ "typescript": "^5.6.0"
56
+ }
57
+ }