From b8f6258a289113388fd5c9bd39f0f3a91fd662cf Mon Sep 17 00:00:00 2001 From: maoyu Mao <153364649+Presisitence@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:07:47 +0800 Subject: [PATCH 1/9] Add plugin bio-research-forge --- .../Presisitence/bio-research-forge/mcp.json | 23 +++++++++++++++++++ .../bio-research-forge/plugin.json | 23 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 plugins/Presisitence/bio-research-forge/mcp.json create mode 100644 plugins/Presisitence/bio-research-forge/plugin.json diff --git a/plugins/Presisitence/bio-research-forge/mcp.json b/plugins/Presisitence/bio-research-forge/mcp.json new file mode 100644 index 0000000..417e5d5 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/mcp.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", + "mcpServers": { + "public-bio-api": { + "type": "stdio", + "command": "node", + "args": ["${PLUGIN_ROOT}/mcp/public-bio-api.mjs"], + "cwd": "${PLUGIN_ROOT}" + }, + "rna-figure": { + "type": "stdio", + "command": "node", + "args": ["${PLUGIN_ROOT}/mcp/rna-figure.mjs"], + "cwd": "${PLUGIN_ROOT}" + }, + "local-bio-tools": { + "type": "stdio", + "command": "node", + "args": ["${PLUGIN_ROOT}/mcp/local-bio-tools.mjs"], + "cwd": "${PLUGIN_ROOT}" + } + } +} diff --git a/plugins/Presisitence/bio-research-forge/plugin.json b/plugins/Presisitence/bio-research-forge/plugin.json new file mode 100644 index 0000000..7d0e6aa --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/plugin.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "bio-research-forge", + "version": "0.1.0", + "description": "Vendor-neutral life-science Agent Plugin: public bio APIs, local RNA figures, safe molecular tools, and independent review.", + "author": { + "name": "Presisitence", + "url": "https://github.com/Presisitence" + }, + "homepage": "https://github.com/Presisitence/bio-research-forge", + "repository": "https://github.com/Presisitence/bio-research-forge", + "license": "AGPL-3.0-or-later", + "keywords": [ + "minimax-code", + "plugin", + "mcp", + "life-science", + "bioinformatics", + "rnaseq", + "uniprot", + "ncbi" + ] +} From b7dabd2dfb10ca38ee11d2328c8bf6d0c03f6a56 Mon Sep 17 00:00:00 2001 From: maoyu Mao <153364649+Presisitence@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:08:29 +0800 Subject: [PATCH 2/9] Add plugin bio-research-forge --- .../bio-research-forge/ATTRIBUTION.md | 25 ++++++ .../bio-research-forge/PRIVACY.md | 28 +++++++ .../Presisitence/bio-research-forge/README.md | 78 +++++++++++++++++++ .../tests/local-tools-protocol-smoke.mjs | 15 ++++ .../bio-research-forge/tests/mcp-client.mjs | 52 +++++++++++++ .../tests/privacy-boundary.mjs | 46 +++++++++++ .../tests/protocol-smoke.mjs | 25 ++++++ .../tests/rna-figure-protocol-smoke.mjs | 15 ++++ 8 files changed, 284 insertions(+) create mode 100644 plugins/Presisitence/bio-research-forge/ATTRIBUTION.md create mode 100644 plugins/Presisitence/bio-research-forge/PRIVACY.md create mode 100644 plugins/Presisitence/bio-research-forge/README.md create mode 100644 plugins/Presisitence/bio-research-forge/tests/local-tools-protocol-smoke.mjs create mode 100644 plugins/Presisitence/bio-research-forge/tests/mcp-client.mjs create mode 100644 plugins/Presisitence/bio-research-forge/tests/privacy-boundary.mjs create mode 100644 plugins/Presisitence/bio-research-forge/tests/protocol-smoke.mjs create mode 100644 plugins/Presisitence/bio-research-forge/tests/rna-figure-protocol-smoke.mjs diff --git a/plugins/Presisitence/bio-research-forge/ATTRIBUTION.md b/plugins/Presisitence/bio-research-forge/ATTRIBUTION.md new file mode 100644 index 0000000..afffaf2 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/ATTRIBUTION.md @@ -0,0 +1,25 @@ +# Attribution and source boundaries + +## DAWN Science + +- Project: DAWN Science, +- Audited revision: `5f909a5b6370c05046b0b0fd527bbf2ce6de1189` +- License: GNU Affero General Public License v3.0 or later +- Material used: high-level role boundaries and research-workbench discipline from the public `agents/` roster and bundled reproducibility skill; provenance, verification, and review concepts described in the public documentation. +- Treatment here: rewritten and reorganized as vendor-neutral Agent Skills; no DAWN desktop runtime, UI, dependency tree, or bundled application code is included. + +The AGPL license in this repository applies to the resulting plugin distribution. DAWN Science remains copyright its contributors. + +## Private local configuration and author materials + +Private local DSH configuration was inspected only to identify desired capability classes and exclusion boundaries. No private DSH module, private database, organism-specific private portal, credential, path, or dataset is redistributed. + +The RNA-figure and local-tool layers were independently implemented for this plugin after inspecting the capability names in the user's local `rna-bio` and `tools-bio` modules. Their hard-coded executable paths, private helper assumptions, local datasets, and source code were not copied into the reusable plugin. + +A user-provided presentation and a local corpus of graduate theses were used only to abstract generic Introduction/Discussion reasoning patterns. Those files, their figures, and their wording are not included. The distilled rules emphasize argument structure rather than copied prose. + +## Public data services + +The plugin calls third-party public APIs but does not redistribute their databases. Users remain responsible for each provider's current terms, attribution requirements, rate limits, and data licenses. Source URLs are returned with every query and listed in the public database skill. + +PyMOL, SnapGene, Cytoscape, Fiji/ImageJ, R, and their packages are optional third-party installations and are not redistributed. Their names identify interoperable software only. The plugin detects and invokes an existing installation under the user's license; it includes no code or assets from those products. diff --git a/plugins/Presisitence/bio-research-forge/PRIVACY.md b/plugins/Presisitence/bio-research-forge/PRIVACY.md new file mode 100644 index 0000000..13ff9d9 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/PRIVACY.md @@ -0,0 +1,28 @@ +# Privacy and scope policy + +## Never include or transmit + +- private experimental measurements, sequencing data, expression matrices, assemblies, annotations, identifiers, or sample metadata; +- user-specific genome or transcriptome databases; +- private credentials, tokens, cookies, internal hostnames, or absolute paths from a contributor's machine; +- dedicated pepper portals, pepper datasets, or species-specific private helpers; +- local theses, presentations, manuscripts, or copied passages from them. + +## Allowed + +- user-selected files inside the active task, processed locally under the user's ordinary authorization; +- local rendering of a user-selected RNA table or molecular structure, with outputs written only to the requested local directory; +- opening an existing compatible file in SnapGene, Cytoscape, or Fiji only after the user explicitly requests that desktop action; +- public, documented, read-only biological APIs on the server allowlist; +- the general Sol Genomics Network resource, limited to public generic metadata and excluding pepper-specific operations; +- generic writing and review heuristics distilled from private reference material without redistributing the source files or wording. + +## Network behavior + +`mcp/public-bio-api.mjs` accepts named operations rather than arbitrary URLs. It does not crawl local files. Each network response records the public endpoint and retrieval time. The server limits result size and blocks queries containing excluded private-resource terms or pepper-specific species terms. + +`mcp/rna-figure.mjs` and `mcp/local-bio-tools.mjs` are local-only. They do not transmit input files. Tool discovery occurs at runtime; reusable source files contain no contributor-specific absolute executable paths. The PyMOL bridge exposes fixed rendering presets rather than arbitrary commands, and desktop tools are never installed automatically. + +## Publication checklist + +Before publishing a release, run `node tests/privacy-boundary.mjs`. Then inspect the git diff for unexpected binary files, archives, datasets, absolute Windows paths, credentials, and source-document text. diff --git a/plugins/Presisitence/bio-research-forge/README.md b/plugins/Presisitence/bio-research-forge/README.md new file mode 100644 index 0000000..bb7ea27 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/README.md @@ -0,0 +1,78 @@ +# bio-research-forge + +Evidence-first life-science workbench for MiniMax Code. The Plugin ships twelve Agent Skills +plus three local stdio MCP servers: public biological APIs (with provenance), RNA result figures +(PNG/PDF + plotted data), and bounded local molecular tools (PyMOL render / SnapGene / Cytoscape / Fiji). + +It does not bundle genomes, expression matrices, credentials, or species-specific private portals. +Private tables stay on the user's machine. Public queries are allowlisted and read-only. +This package is the portable Agent Plugins 1.0 subset; it does not include Codex marketplace +adapters, hooks, custom agents, LSP, Apps, OAuth, or TUI extensions. + +Standalone source: https://github.com/Presisitence/bio-research-forge + +## Try it + +```text +Look up Arabidopsis FLC in UniProt and NCBI. Then, using my local DEG table deg.csv +(columns gene, log2FoldChange, padj), draw a volcano plot (padj < 0.05, |log2FC| > 1) +and show the PNG in the conversation. +``` + +```text +用公共 API 查拟南芥 FLC 的 UniProt / NCBI 记录,再用我本地的 deg.csv +(列 gene, log2FoldChange, padj)画火山图,padj < 0.05 且 |log2FC| > 1,并在对话里预览 PNG。 +``` + +Expected result: the agent calls `bio_api_query` (UniProt / NCBI) then `rna_figure_create` +(`plot_type="volcano"`). API replies include the source URL and retrieval time. The local table +is not uploaded. Success writes `.png`, `.pdf`, and `.plot-data.csv`; the PNG +path is meant for inline preview. Missing R packages return a status error rather than a crash. + +For a design or manuscript request, `bio-research-orchestrator` routes to specialist Skills +(`experimental-design-gate`, `manuscript-argument`, `evidence-review`, …) and labels evidence as +direct data / external / candidate / hypothesis. + +## Requirements + +- Node.js 18+ on PATH (`mcp.json` starts each server with `node` and `cwd: ${PLUGIN_ROOT}`). +- Optional `NCBI_API_KEY` in the environment to raise NCBI rate limits. No key is shipped. +- Optional R with `Rscript` on PATH, or `RSCRIPT_EXE`, plus `jsonlite`, `ggplot2`, `pheatmap` + (and `ggrepel` for volcano labels). Needed only for `rna_figure_create`. +- Optional local installs of PyMOL, SnapGene, Cytoscape, or Fiji (or `PYMOL_EXE` / + `SNAPGENE_EXE` / `CYTOSCAPE_EXE` / `FIJI_EXE`). The bridge never installs software. +- Windows, macOS, and Linux. + +## Data and network + +`public-bio-api` contacts named public scholarly APIs only. Arbitrary URLs, local files, +credentials, and pepper-specific queries are rejected: + +- `eutils.ncbi.nlm.nih.gov` +- `rest.uniprot.org` +- `www.ebi.ac.uk` (InterPro, Europe PMC) +- `rest.ensembl.org` +- `alphafold.ebi.ac.uk` +- `data.rcsb.org` +- `string-db.org` +- `jaspar.elixir.no` +- `solgenomics.net` (generic BrAPI crop-name metadata only) + +`rna-figure` and `local-bio-tools` are local-only. User CSVs and structure files are not +transmitted. No telemetry. No credentials in the package. + +## Skills and MCP + +Skills (frontmatter `name` matches each directory): `bio-research-orchestrator`, +`public-bio-databases`, `experimental-design-gate`, `omics-workflow`, `rna-figure-workflow`, +`quantitative-research`, `local-bio-toolkit`, `secure-compute-routing`, `manuscript-argument`, +`scientific-figure-delivery`, `reproducible-analysis`, `evidence-review`. + +MCP tools: `bio_api_catalog` / `bio_api_query` / `bio_api_health`; `rna_figure_status` / +`rna_figure_create`; `local_bio_tool_status` / `pymol_render` / `local_bio_open`. + +## License + +AGPL-3.0-or-later. See [LICENSE](LICENSE) and [ATTRIBUTION.md](ATTRIBUTION.md). +This Plugin keeps the upstream source license; it is not relicensed to MIT. +Public databases and optional desktop tools have their own terms. diff --git a/plugins/Presisitence/bio-research-forge/tests/local-tools-protocol-smoke.mjs b/plugins/Presisitence/bio-research-forge/tests/local-tools-protocol-smoke.mjs new file mode 100644 index 0000000..19c69f1 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/tests/local-tools-protocol-smoke.mjs @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import { startServer, toolText } from './mcp-client.mjs'; + +const server = startServer('./mcp/local-bio-tools.mjs'); +try { + const initialized = await server.request('initialize', { protocolVersion: '2024-11-05' }); + assert.equal(initialized.result.serverInfo.name, 'local-bio-tools'); + const listed = await server.request('tools/list'); + assert.deepEqual(listed.result.tools.map((tool) => tool.name), ['local_bio_tool_status', 'pymol_render', 'local_bio_open']); + const statusMessage = await server.request('tools/call', { name: 'local_bio_tool_status', arguments: {} }); + const status = JSON.parse(toolText(statusMessage)); + assert.equal(status.localOnly, true); + assert.deepEqual(status.tools.map((tool) => tool.id), ['pymol', 'snapgene', 'cytoscape', 'fiji']); + console.log('local-tools-protocol-smoke: ok'); +} finally { server.close(); } diff --git a/plugins/Presisitence/bio-research-forge/tests/mcp-client.mjs b/plugins/Presisitence/bio-research-forge/tests/mcp-client.mjs new file mode 100644 index 0000000..0f99a0f --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/tests/mcp-client.mjs @@ -0,0 +1,52 @@ +import { spawn } from 'node:child_process'; +import readline from 'node:readline'; + +export function startServer(serverPath = './mcp/public-bio-api.mjs', env = {}) { + const child = spawn(process.execPath, [serverPath], { + cwd: new URL('..', import.meta.url), + env: { ...process.env, ...env }, + stdio: ['pipe', 'pipe', 'inherit'], + }); + const pending = new Map(); + const lines = readline.createInterface({ input: child.stdout, crlfDelay: Infinity }); + lines.on('line', (line) => { + const message = JSON.parse(line); + const waiter = pending.get(message.id); + if (waiter) { + pending.delete(message.id); + waiter.resolve(message); + } + }); + child.on('exit', (code) => { + for (const waiter of pending.values()) waiter.reject(new Error(`MCP server exited with code ${code}`)); + pending.clear(); + }); + + let nextId = 1; + function request(method, params = {}) { + const id = nextId++; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + pending.delete(id); + reject(new Error(`Timed out waiting for ${method}`)); + }, 60_000); + pending.set(id, { + resolve: (message) => { clearTimeout(timer); resolve(message); }, + reject: (error) => { clearTimeout(timer); reject(error); }, + }); + child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`); + }); + } + + return { + child, + request, + close() { child.stdin.end(); child.kill(); }, + }; +} + +export function toolText(message) { + const text = message?.result?.content?.[0]?.text; + if (typeof text !== 'string') throw new Error(`Missing MCP text result: ${JSON.stringify(message)}`); + return text; +} diff --git a/plugins/Presisitence/bio-research-forge/tests/privacy-boundary.mjs b/plugins/Presisitence/bio-research-forge/tests/privacy-boundary.mjs new file mode 100644 index 0000000..b25bbe4 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/tests/privacy-boundary.mjs @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict'; +import { readFile, readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { startServer, toolText } from './mcp-client.mjs'; + +const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); + +async function filesUnder(dir) { + const found = []; + for (const entry of await readdir(dir, { withFileTypes: true })) { + if (entry.name === '.git' || entry.name === 'node_modules') continue; + const full = path.join(dir, entry.name); + if (entry.isDirectory()) found.push(...await filesUnder(full)); + else found.push(full); + } + return found; +} + +const self = fileURLToPath(import.meta.url); +const textFiles = (await filesUnder(ROOT)).filter((file) => file !== self && !/\.(?:svg|png|jpg|jpeg|gif|pdf|docx|pptx)$/i.test(file)); +const forbidden = [ + /[G-Z]:\\/i, + /C:\\Users\\[^\\]+/i, + /pepper-hub/i, + /zsg_id_map/i, + /尊辣|张树刚/i, + /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/, +]; +for (const file of textFiles) { + const content = await readFile(file, 'utf8'); + for (const rule of forbidden) assert(!rule.test(content), `${path.relative(ROOT, file)} matched ${rule}`); +} + +const server = startServer(); +try { + const blocked = await server.request('tools/call', { + name: 'bio_api_query', + arguments: { source: 'ensembl', operation: 'lookup-symbol', species: 'capsicum_annuum', id: 'Example1' }, + }); + assert.equal(blocked.result.isError, true); + assert.match(toolText(blocked), /public-data boundary/i); + console.log('privacy-boundary: ok'); +} finally { + server.close(); +} diff --git a/plugins/Presisitence/bio-research-forge/tests/protocol-smoke.mjs b/plugins/Presisitence/bio-research-forge/tests/protocol-smoke.mjs new file mode 100644 index 0000000..cbd9684 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/tests/protocol-smoke.mjs @@ -0,0 +1,25 @@ +import assert from 'node:assert/strict'; +import { startServer, toolText } from './mcp-client.mjs'; + +const server = startServer(); +try { + const initialized = await server.request('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1' } }); + assert.equal(initialized.result.serverInfo.name, 'public-bio-api'); + + const listed = await server.request('tools/list'); + assert.deepEqual(listed.result.tools.map((tool) => tool.name), ['bio_api_catalog', 'bio_api_query', 'bio_api_health']); + + const catalogMessage = await server.request('tools/call', { name: 'bio_api_catalog', arguments: {} }); + const catalog = JSON.parse(toolText(catalogMessage)); + assert.equal(catalog.sources.length, 10); + assert(catalog.sources.every((source) => source.docs.startsWith('https://'))); + + const healthMessage = await server.request('tools/call', { name: 'bio_api_health', arguments: {} }); + const health = JSON.parse(toolText(healthMessage)); + assert.equal(health.status, 'healthy'); + assert.equal(health.publicOnly, true); + assert.equal(health.localFilesRead, false); + console.log('protocol-smoke: ok'); +} finally { + server.close(); +} diff --git a/plugins/Presisitence/bio-research-forge/tests/rna-figure-protocol-smoke.mjs b/plugins/Presisitence/bio-research-forge/tests/rna-figure-protocol-smoke.mjs new file mode 100644 index 0000000..8f4ed43 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/tests/rna-figure-protocol-smoke.mjs @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import { startServer, toolText } from './mcp-client.mjs'; + +const server = startServer('./mcp/rna-figure.mjs'); +try { + const initialized = await server.request('initialize', { protocolVersion: '2024-11-05' }); + assert.equal(initialized.result.serverInfo.name, 'rna-figure'); + const listed = await server.request('tools/list'); + assert.deepEqual(listed.result.tools.map((tool) => tool.name), ['rna_figure_status', 'rna_figure_create']); + const statusMessage = await server.request('tools/call', { name: 'rna_figure_status', arguments: {} }); + const status = JSON.parse(toolText(statusMessage)); + assert.equal(typeof status.ready, 'boolean'); + assert.equal(status.script, true); + console.log('rna-figure-protocol-smoke: ok'); +} finally { server.close(); } From 8f92d2c083348ffc0462443cdc2737f3629fcadd Mon Sep 17 00:00:00 2001 From: maoyu Mao <153364649+Presisitence@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:08:53 +0800 Subject: [PATCH 3/9] Add plugin bio-research-forge --- .../skills/bio-research-orchestrator/SKILL.md | 41 +++++++++++++++++++ .../references/routing.md | 19 +++++++++ .../skills/experimental-design-gate/SKILL.md | 35 ++++++++++++++++ .../skills/quantitative-research/SKILL.md | 24 +++++++++++ .../skills/rna-figure-workflow/SKILL.md | 34 +++++++++++++++ .../references/input-contracts.md | 13 ++++++ .../scientific-figure-delivery/SKILL.md | 35 ++++++++++++++++ .../references/delivery-contract.md | 14 +++++++ .../skills/secure-compute-routing/SKILL.md | 37 +++++++++++++++++ 9 files changed, 252 insertions(+) create mode 100644 plugins/Presisitence/bio-research-forge/skills/bio-research-orchestrator/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/bio-research-orchestrator/references/routing.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/experimental-design-gate/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/quantitative-research/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/rna-figure-workflow/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/rna-figure-workflow/references/input-contracts.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/scientific-figure-delivery/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/scientific-figure-delivery/references/delivery-contract.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/secure-compute-routing/SKILL.md diff --git a/plugins/Presisitence/bio-research-forge/skills/bio-research-orchestrator/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/bio-research-orchestrator/SKILL.md new file mode 100644 index 0000000..f03ec3e --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/bio-research-orchestrator/SKILL.md @@ -0,0 +1,41 @@ +--- +name: bio-research-orchestrator +description: Coordinate a life-science research request that spans design, public databases, omics, statistics, writing, figures, reproducibility, or independent review. Use for multi-stage research work; do not use for a single narrow lookup. +--- + +# Bio Research Orchestrator + +Turn a broad request into a traceable research workflow without mixing evidence levels or private resources. + +## Start contract + +Before analysis, state: + +1. the biological question in one sentence; +2. the primary endpoint and experimental unit; +3. the falsifiable claim; +4. the available evidence and what it cannot establish; +5. the requested deliverables and final review gate. + +If the materials cannot answer the question, issue `No-Go` or `Revise-and-Go`. Do not hide a design failure by adding downstream analyses. + +## Routing + +Read [references/routing.md](references/routing.md) and load only the specialist skills needed. Keep responsibilities separate. When delegation is available and the user has requested multi-agent work, assign bounded roles with explicit inputs, outputs, and acceptance criteria. A production role must not self-certify its own result when an independent review role is available. + +## Non-negotiable boundary + +Read [../../PRIVACY.md](../../PRIVACY.md). Use only user-authorized workspace files and named public APIs. Never import a private genome/transcriptome database, private experimental dataset, dedicated pepper portal, credential, or machine-specific path into a reusable artifact. + +## Evidence ledger + +For every conclusion, label the strongest support as one of: + +- `Direct data`: observed or computed from supplied data; +- `External evidence`: verified public record or paper; +- `Candidate evidence`: association, prediction, enrichment, network, docking, or model importance; +- `Hypothesis`: a proposed explanation or next test. + +## Completion gate + +Do not say the work is complete until deliverables exist, commands/tests are recorded, failures are disclosed, and `evidence-review` has produced a verdict for high-stakes outputs. Return the important result in the conversation; files are supporting artifacts, not a substitute for the answer. diff --git a/plugins/Presisitence/bio-research-forge/skills/bio-research-orchestrator/references/routing.md b/plugins/Presisitence/bio-research-forge/skills/bio-research-orchestrator/references/routing.md new file mode 100644 index 0000000..0aa2e3e --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/bio-research-orchestrator/references/routing.md @@ -0,0 +1,19 @@ +# Specialist routing + +| Need | Skill | Required handoff | +|---|---|---| +| Question-design fit, controls, sample size | `experimental-design-gate` | decision, design diagram, failure criteria | +| Public gene/protein/structure/literature records | `public-bio-databases` | exact query, URL, retrieval time, evidence limit | +| Sequencing or omics | `omics-workflow` | input contract, QC gates, design matrix, outputs | +| RNA volcano, PCA, heatmap, boxplot, enrichment dotplot | `rna-figure-workflow` | source table, columns, thresholds, PNG/PDF/data preview | +| Statistical inference or prediction | `quantitative-research` | estimand, model, diagnostics, sensitivity | +| PyMOL, SnapGene, Cytoscape, or Fiji | `local-bio-toolkit` | detected tool, permitted local action, output/launch status | +| Local, HPC, or cloud execution choice | `secure-compute-routing` | data classification, transfer boundary, job manifest | +| Introduction or Discussion | `manuscript-argument` | claim-evidence map, section logic, missing citations | +| Publication figure | `scientific-figure-delivery` | source table, code, export files, inline preview | +| Re-runnable pipeline | `reproducible-analysis` | environment, parameters, seeds, clean-run evidence | +| Final audit | `evidence-review` | independent report and verdict | + +Run independent branches in parallel only when their inputs do not depend on each other. Merge by shared identifiers and evidence, not by averaging prose. + +For each handoff specify: task, permitted inputs, excluded inputs, expected files, acceptance tests, and stopping condition. diff --git a/plugins/Presisitence/bio-research-forge/skills/experimental-design-gate/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/experimental-design-gate/SKILL.md new file mode 100644 index 0000000..6ef7393 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/experimental-design-gate/SKILL.md @@ -0,0 +1,35 @@ +--- +name: experimental-design-gate +description: Audit whether biological materials, sampling, controls, replication, and measurements can answer a proposed question before experiments or analysis. Use for study planning and Go/No-Go decisions. +--- + +# Experimental Design Gate + +## Define before optimizing + +Write the biological question, experimental unit, primary endpoint, minimum meaningful effect, intervention/contrast, and falsifiable hypothesis. Distinguish biological from technical replication. + +## Audit + +Check: + +- material and model-system relevance; +- controls, randomization, blocking, blinding, and batch balance; +- nesting, repeated measures, pairing, and independence; +- sample-size justification using a defensible effect range or simulation; +- measurement timing, dynamic range, failure thresholds, and missing-data handling; +- whether the planned statistic estimates the biological quantity of interest. + +## Decision + +Return one of: + +- `Go`: the design can test the claim; +- `Revise-and-Go`: named changes are required before proceeding; +- `No-Go`: the current materials or design cannot identify the claimed effect. + +Do not rescue a No-Go by adding omics, enrichment, machine learning, or more figures. State the smallest change that would alter the decision. + +## Deliverable + +Provide a design map, control table, sample-size assumptions, analysis skeleton, failure criteria, and records to preserve. Separate confirmatory endpoints from exploratory measurements. diff --git a/plugins/Presisitence/bio-research-forge/skills/quantitative-research/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/quantitative-research/SKILL.md new file mode 100644 index 0000000..e89a27e --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/quantitative-research/SKILL.md @@ -0,0 +1,24 @@ +--- +name: quantitative-research +description: Design or review statistical, mixed-model, Bayesian, or machine-learning analyses for life-science data. Use when the main risk is estimand, dependence, model choice, diagnostics, leakage, or uncertainty. +--- + +# Quantitative Research + +## First specify + +State the response scale, experimental unit, estimand, sampling/dependence structure, planned contrast, missingness, and whether the goal is explanation, estimation, prediction, or discovery. + +## Model contract + +Before fitting, record candidate model(s), formula, distribution/link, random or correlation structure, assumptions, diagnostics, comparison rule, and fallback. Match the effective sample size to the treatment unit, not the number of rows. + +## Required reporting + +Report estimates, effect sizes, intervals, sample counts, model diagnostics, multiplicity handling, sensitivity analysis, and limitations. A p value or accuracy score alone is incomplete. + +For predictive work, keep preprocessing inside resampling folds, split by subject/site/time when required, keep the test set untouched, compare with a simple baseline, report calibration and uncertainty, and label feature importance as association rather than mechanism. + +For Bayesian work, document priors, prior predictive checks, convergence, effective sample size, divergences, posterior predictive checks, and prior sensitivity. + +Never change endpoints, exclusions, transformations, or models repeatedly to obtain significance. Exploratory analysis must remain labeled exploratory. diff --git a/plugins/Presisitence/bio-research-forge/skills/rna-figure-workflow/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/rna-figure-workflow/SKILL.md new file mode 100644 index 0000000..9993b8a --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/rna-figure-workflow/SKILL.md @@ -0,0 +1,34 @@ +--- +name: rna-figure-workflow +description: Create and audit common RNA-seq result figures locally, including volcano, PCA, heatmap, expression boxplot, and enrichment dotplot, with PNG/PDF delivery and inline conversation preview. Use for RNA result plotting from user-selected tables; do not use private bundled datasets. +--- + +# RNA Figure Workflow + +Use the bundled `rna-figure` MCP for a standard R-based plot when its input contract fits. Read [references/input-contracts.md](references/input-contracts.md) before calling it. + +## Scope + +- Direct plots from an existing differential-expression, expression, count, or enrichment table. +- Standard deliverables: PNG preview, PDF publication file, and the exact plotted-data CSV. +- Local processing only. Never upload the table or import it into this reusable plugin. + +This skill does not silently perform differential expression, invent biological replicates, or treat enrichment as mechanistic proof. Route a full counts-to-DE workflow through `omics-workflow`, then use this skill for figures. + +## Figure contract + +Before drawing, identify the biological conclusion, experimental unit, comparison, relevant columns, transformation, thresholds, and whether the table contains adjusted P values. Stop if sample identity, replicate structure, or the requested comparison is ambiguous. + +Use `rna_figure_status` first. Then call `rna_figure_create` with an explicit plot type and output directory. Keep default thresholds only when they match the analysis contract; otherwise pass the documented values. + +## Delivery + +After generation: + +1. inspect the PNG for clipping, misleading scales, illegible labels, and unexpected sample groupings; +2. show the PNG directly in the conversation with its absolute path; +3. link the PDF and plotted-data CSV; +4. state the source table, columns, transformation, thresholds, and row/gene selection; +5. use `evidence-review` for submission-facing figures. + +Never make the user open a side-panel file merely to judge the figure. diff --git a/plugins/Presisitence/bio-research-forge/skills/rna-figure-workflow/references/input-contracts.md b/plugins/Presisitence/bio-research-forge/skills/rna-figure-workflow/references/input-contracts.md new file mode 100644 index 0000000..e389b43 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/rna-figure-workflow/references/input-contracts.md @@ -0,0 +1,13 @@ +# RNA figure input contracts + +| Plot | Required content | Typical automatic columns | Important checks | +|---|---|---|---| +| Volcano | effect size and adjusted P value | `log2FoldChange`, `padj` | verify contrast direction and zero/NA handling | +| PCA | genes by numeric sample columns | first column gene ID | raw counts may be log2(x+1); metadata sample names must match exactly | +| Heatmap | genes by numeric sample columns | first column gene ID | top genes are selected by variance and row z-scored | +| Expression boxplot | long table with group and value | `group`, `value` | observations must be biological units, not technical pseudo-replicates | +| Enrichment dotplot | term, gene ratio, count, adjusted P | `Description`, `GeneRatio`, `Count`, `padj` | enrichment is candidate-level evidence and needs a valid background universe | + +Use the `columns` argument whenever automatic names do not match. Use `metadata_path` for PCA grouping; its default keys are `sample` and `group`. + +The plotting tool writes `.png`, `.pdf`, and `.plot-data.csv`. It never overwrites the input table. diff --git a/plugins/Presisitence/bio-research-forge/skills/scientific-figure-delivery/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/scientific-figure-delivery/SKILL.md new file mode 100644 index 0000000..714d296 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/scientific-figure-delivery/SKILL.md @@ -0,0 +1,35 @@ +--- +name: scientific-figure-delivery +description: Create, revise, or audit publication-grade life-science figures with source-data traceability, export QA, and a PNG preview shown directly in the agent conversation. Use for manuscript figures, not dashboards or decorative infographics. +--- + +# Scientific Figure Delivery + +Read [references/delivery-contract.md](references/delivery-contract.md). + +## Figure contract + +Before drawing, state the one-sentence conclusion, evidence chain, primary comparison, experimental unit, n, uncertainty/statistic, target dimensions, and export formats. If no backend is explicit, ask `Python or R?` and use only the selected backend for generation, preview, export, and QA. + +## Integrity + +- Never alter or omit data to improve appearance. +- Show distributions or individual observations when scientifically appropriate. +- Define every error bar and statistical mark. +- Use restrained, colorblind-safe palettes and legible final-size typography. +- Keep labels, numbers, and panel order consistent with the source table and manuscript. +- Preserve the generation code, input table, environment, and key parameters with the figure. + +## Conversation-first delivery + +Always render a final PNG preview and display it in the answer using an absolute path: + +```markdown +![Figure preview](/absolute/path/to/final-preview.png) +``` + +Also link the editable/vector and publication files. Do not force the user to open a side-panel file just to judge the figure. + +## Final QA + +Inspect the rendered image at actual output size, verify clipping and font embedding, validate SVG/PDF/TIFF metadata, and run `evidence-review` for submission-facing multi-panel figures. diff --git a/plugins/Presisitence/bio-research-forge/skills/scientific-figure-delivery/references/delivery-contract.md b/plugins/Presisitence/bio-research-forge/skills/scientific-figure-delivery/references/delivery-contract.md new file mode 100644 index 0000000..6ca130f --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/scientific-figure-delivery/references/delivery-contract.md @@ -0,0 +1,14 @@ +# Figure delivery contract + +Deliver a coherent set: + +- `figure.`: editable or vector master; +- `figure.tiff`: journal raster when requested, at the required physical size and resolution; +- `figure-preview.png`: conversation preview; +- generation code in the selected backend; +- source-data table or a documented pointer to it; +- short README or metadata block with conclusion, n, statistics, parameters, software versions, and hashes. + +The PNG preview is required even when the journal file is PDF/TIFF. The preview and publication export must come from the same final rendering state. + +For multi-panel figures, assign one message per panel and one synthesis message for the whole figure. Remove redundant legends and table-like gridlines. Aesthetics may clarify evidence but must not change its meaning. diff --git a/plugins/Presisitence/bio-research-forge/skills/secure-compute-routing/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/secure-compute-routing/SKILL.md new file mode 100644 index 0000000..f8d693a --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/secure-compute-routing/SKILL.md @@ -0,0 +1,37 @@ +--- +name: secure-compute-routing +description: Decide whether a life-science computation should run locally, on a controlled HPC over SSH, or on an external cloud GPU based on data sensitivity, scale, cost, and reproducibility. Use before moving data or launching remote work. +--- + +# Secure Compute Routing + +## Classify first + +Label every input as `public`, `controlled/private`, or `credentialed`. Record approximate size, required software, compute/memory/GPU need, expected runtime, and output size. + +## Default routing + +- Public data: local, controlled HPC, or an approved cloud service may be considered. +- Controlled/private data: local or user-controlled HPC over SSH by default. +- Credentials: never embed in scripts, prompts, logs, archives, or repository files. +- External cloud GPU: do not upload or launch until the user has approved the provider, estimated cost, exact transferred files, retention policy, and deletion/return plan. + +Do not treat a user's request to analyze data as permission to send it to an external service. + +## Execution contract + +Before launch, produce: + +1. runtime target and reason; +2. data-transfer manifest and excluded files; +3. environment/container specification; +4. command, resources, wall time, retry limit, and stopping condition; +5. log, heartbeat, checkpoint, and failure handling; +6. output validation and checksum plan; +7. return/synchronization plan that does not overwrite source data. + +Use SSH to execute on a controlled HPC without installing an agent unless the user explicitly requests and approves it. Keep large intermediate data near the compute environment; transfer only required inputs and final artifacts. + +## Completion + +Report actual host class, job ID when available, environment, exit status, validated outputs, costs if external, and failed checks. A submitted job is not a completed analysis. From c37f879d5704ec4a41f95f9741e82feb36d40169 Mon Sep 17 00:00:00 2001 From: maoyu Mao <153364649+Presisitence@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:09:17 +0800 Subject: [PATCH 4/9] Add plugin bio-research-forge --- .../skills/evidence-review/SKILL.md | 25 +++++++++++++ .../references/review-contract.md | 33 +++++++++++++++++ .../skills/local-bio-toolkit/SKILL.md | 31 ++++++++++++++++ .../skills/manuscript-argument/SKILL.md | 30 ++++++++++++++++ .../references/introduction-discussion.md | 36 +++++++++++++++++++ .../skills/omics-workflow/SKILL.md | 27 ++++++++++++++ .../skills/public-bio-databases/SKILL.md | 31 ++++++++++++++++ .../references/api-catalog.md | 16 +++++++++ .../skills/reproducible-analysis/SKILL.md | 27 ++++++++++++++ 9 files changed, 256 insertions(+) create mode 100644 plugins/Presisitence/bio-research-forge/skills/evidence-review/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/evidence-review/references/review-contract.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/local-bio-toolkit/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/manuscript-argument/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/manuscript-argument/references/introduction-discussion.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/omics-workflow/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/public-bio-databases/SKILL.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/public-bio-databases/references/api-catalog.md create mode 100644 plugins/Presisitence/bio-research-forge/skills/reproducible-analysis/SKILL.md diff --git a/plugins/Presisitence/bio-research-forge/skills/evidence-review/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/evidence-review/SKILL.md new file mode 100644 index 0000000..8209ef9 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/evidence-review/SKILL.md @@ -0,0 +1,25 @@ +--- +name: evidence-review +description: Independently review a life-science manuscript, analysis, figure package, or repository for claim support, citation validity, numeric traceability, figure-code-data consistency, reproducibility, and privacy. Use as a final gate, not as author self-approval. +--- + +# Evidence Review + +Read [references/review-contract.md](references/review-contract.md). Review the artifacts and acceptance criteria, not the producer's confidence or narrative. + +## Review layers + +1. `Scientific`: question, design, controls, experimental unit, and causal strength. +2. `Citation`: existence, bibliographic correctness, primary-source preference, and semantic support for the exact clause. +3. `Numbers`: every sample size, percentage, effect, interval, p value, and identifier traced to source data or output. +4. `Figures`: source table, code, labels, statistics, legends, and manuscript text agree. +5. `Reproducibility`: clean rerun, versions, parameters, seeds, failures, and environment evidence. +6. `Privacy`: no private dataset, credential, local path, or excluded organism-specific resource entered a reusable package. + +## Independence rule + +If the reviewer participated in producing an artifact, disclose that conflict and perform only a provisional check. For a consequential gate, use a fresh review context or independent agent when available. + +## Verdict + +Return exactly one: `PASS`, `PASS WITH REQUIRED REVISIONS`, or `BLOCK`. A PASS requires evidence for each required layer; silence is not evidence. diff --git a/plugins/Presisitence/bio-research-forge/skills/evidence-review/references/review-contract.md b/plugins/Presisitence/bio-research-forge/skills/evidence-review/references/review-contract.md new file mode 100644 index 0000000..80e855f --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/evidence-review/references/review-contract.md @@ -0,0 +1,33 @@ +# Review contract + +## Required inputs + +- artifact or exact file set under review; +- intended claim and audience; +- acceptance criteria or target journal requirements; +- available source data, code, environment, and citation library; +- declared scope exclusions. + +## Evidence matrix + +| ID | Claim/artifact | Required evidence | Observed evidence | Status | Required action | +|---|---|---|---|---|---| + +Status is `verified`, `partially verified`, `unsupported`, `contradicted`, or `not assessable`. + +## Figure-code-data check + +For each figure, verify: final filename and hash; generation script; input table; filters and transformations; panel labels; group labels and units; n and error definition; statistical annotation; legend; manuscript values. Regenerate when feasible and compare output. + +## Citation check + +Verify DOI/title/authors/year, open the source, identify the passage/result that supports the claim, and note whether the support is direct or inferential. A related paper that does not support the clause fails. + +## Report + +1. outcome and scope; +2. blocking findings first, each with file/line/figure evidence; +3. claim and number traceability gaps; +4. reproducibility and privacy results; +5. residual risk; +6. verdict and exact revisions required for re-review. diff --git a/plugins/Presisitence/bio-research-forge/skills/local-bio-toolkit/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/local-bio-toolkit/SKILL.md new file mode 100644 index 0000000..b4f60b6 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/local-bio-toolkit/SKILL.md @@ -0,0 +1,31 @@ +--- +name: local-bio-toolkit +description: Detect and selectively use local life-science desktop or structural tools, including safe PyMOL rendering and explicit file opening in SnapGene, Cytoscape, or Fiji. Use when a user asks to work with these installed applications; never install tools silently or accept arbitrary commands. +--- + +# Local Bio Toolkit + +Use the bundled `local-bio-tools` MCP. This layer is deliberately small and capability-based: PyMOL renders structures; SnapGene opens sequence/vector files; Cytoscape opens network files; Fiji opens microscopy images. + +## Selection rule + +| Need | Tool | Allowed action | +|---|---|---| +| Produce a molecular-structure image | PyMOL | headless render with a fixed visual preset | +| Inspect an existing construct or sequence record | SnapGene | open a compatible local file after an explicit user request | +| Inspect an existing biological network | Cytoscape | open a compatible local file after an explicit user request | +| Inspect an existing microscopy image | Fiji/ImageJ | open a compatible local file after an explicit user request | + +Run `local_bio_tool_status` before acting. If a tool is absent, report the missing capability and the supported environment-variable override; do not install, download, or substitute software without direction. + +## Safety boundary + +- Accept only an existing user-selected file and a format on the allowlist. +- Do not execute arbitrary PyMOL code, macros, plugins, shell fragments, or application arguments. +- Do not launch a graphical desktop application unless the user explicitly asked to open it. +- Do not modify the source file. Save PyMOL output only to the requested PNG path. +- Processing stays local; no file is transmitted to a website or public API. + +## Conversation delivery + +For PyMOL output, visually inspect the generated PNG and show it directly in the conversation. Explain representation, coloring, background, and structural evidence limits. A rendered model does not establish binding, function, or experimental structure quality. diff --git a/plugins/Presisitence/bio-research-forge/skills/manuscript-argument/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/manuscript-argument/SKILL.md new file mode 100644 index 0000000..528a218 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/manuscript-argument/SKILL.md @@ -0,0 +1,30 @@ +--- +name: manuscript-argument +description: Draft or restructure life-science Introduction and Discussion sections from supplied claims, results, figures, and verified literature. Use for argument construction; do not invent evidence, citations, or causal strength. +--- + +# Manuscript Argument + +Read [references/introduction-discussion.md](references/introduction-discussion.md) and select the section-specific pattern. + +## Evidence intake + +Build a claim-evidence table before prose: + +| Claim | Direct result | External support | Boundary | Missing citation/test | +|---|---|---|---|---| + +If a key row lacks support, leave a clear placeholder or narrow the claim. Do not generate a plausible-looking citation. + +## Drafting rules + +- One paragraph should perform one argumentative job. +- Lead each paragraph with its function, then evidence, interpretation, and transition. +- Separate what the study shows, what it suggests, and what remains untested. +- Use prior work to create a comparison or unresolved problem, not a citation list. +- Match causal verbs to the design and evidence. +- Keep Introduction results minimal; keep Discussion methods minimal unless a limitation depends on them. + +## QA + +After drafting, reverse-outline the paragraphs, map every number and citation to a source, check that the final sentence answers the opening problem, and send the section to `evidence-review` when submission-facing. diff --git a/plugins/Presisitence/bio-research-forge/skills/manuscript-argument/references/introduction-discussion.md b/plugins/Presisitence/bio-research-forge/skills/manuscript-argument/references/introduction-discussion.md new file mode 100644 index 0000000..9066579 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/manuscript-argument/references/introduction-discussion.md @@ -0,0 +1,36 @@ +# Introduction and Discussion playbook + +This playbook is a generic abstraction from an author-provided annotated presentation and a private graduate-thesis corpus. No source document or passage is redistributed. + +## Introduction: narrowing argument + +1. `Significance`: define the biological problem and why the unresolved part matters. +2. `Mechanistic baseline`: state the consensus model needed to understand the gap. +3. `Specific limitation`: identify what existing models, systems, or applications cannot explain or achieve. +4. `Contrast`: use one or two relevant prior models to expose the difference, not to inventory the literature. +5. `Question and strategy`: state the question, system, decisive comparison, and primary readout. +6. `Contribution`: state what class of uncertainty the study resolves, without overstating results. + +A common strong thesis pattern is `field background -> focused mechanism/family -> unresolved gap -> study objective and technical route`. Compress the background until every paragraph is necessary for the study question. + +## Discussion: expanding interpretation + +1. `Principal advance`: answer the research question with the strongest supported claim. +2. `Comparison-difference-innovation`: compare with the closest mechanism, identify the difference, then explain the new conceptual contribution. +3. `Evidence chain`: connect molecular or cellular evidence to phenotype and possible application only as far as the data allow. +4. `Problem-solution loop`: return to the limitation introduced earlier and show precisely which result resolves it. +5. `Alternatives`: address conflicting or uneven results and state plausible alternatives as hypotheses. +6. `Boundary`: name limitations, missing controls, and the decisive next experiment. +7. `Synthesis`: close with the general insight and realistic application horizon. + +Useful logical moves from the annotated material include `mechanism -> application`, `past failure -> missing component -> tested solution`, and `unresolved structure/function question -> next experiment`. These are argument forms, not reusable sentences. + +## Claim-strength vocabulary + +| Evidence | Prefer | Avoid unless directly justified | +|---|---|---| +| observational association | associated with, correlated with | controls, drives, causes | +| perturbation with phenotype | contributes to, is required for | is sufficient for, is the mechanism | +| rescue/complementation | supports a causal role | proves the entire pathway | +| prediction/network/enrichment | prioritizes, suggests, is consistent with | binds, regulates, mediates | +| direct biochemical/structural test | interacts/binds under stated conditions | universal in vivo mechanism | diff --git a/plugins/Presisitence/bio-research-forge/skills/omics-workflow/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/omics-workflow/SKILL.md new file mode 100644 index 0000000..1ff4530 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/omics-workflow/SKILL.md @@ -0,0 +1,27 @@ +--- +name: omics-workflow +description: Plan, audit, or interpret public or user-authorized sequencing and omics workflows, including bulk RNA-seq, single-cell, amplicon, metagenomic, variant, and metabolomic analyses. Use only after design and metadata fit are checked. +--- + +# Omics Workflow + +## Intake contract + +Identify assay, platform, experimental unit, biological replicates, groups, batches, pairing, reference/annotation version, raw/processed inputs, and primary biological contrast. Stop if group and batch are fully confounded or replication cannot support inference. + +## Stage gates + +1. `Raw QC`: integrity, depth, quality, contamination, adapters, duplication, mapping/assignment expectations. +2. `Metadata`: unique sample IDs, factor levels, units, missingness, batch and subject structure. +3. `Quantification`: versioned reference, parameters, multi-mapping policy, feature definition. +4. `Exploration`: sample-level PCA/MDS, library size, outliers, and batch patterns without deleting samples silently. +5. `Inference`: explicit design matrix and contrasts; multiple-testing control; effect sizes with uncertainty. +6. `Interpretation`: correct background universe, annotation version, redundancy control, and evidence-level language. +7. `Delivery`: source tables, code, environment, QC report, exclusions, and failed checks. + +## Domain red lines + +- Do not treat cells as biological replicates; use sample-aware inference or pseudobulk where appropriate. +- Treat microbiome abundance as compositional and evaluate sparsity and prevalence. +- Do not infer mechanism from enrichment, network centrality, classifier importance, or differential abundance alone. +- Never overwrite raw data or package user data into a reusable plugin. diff --git a/plugins/Presisitence/bio-research-forge/skills/public-bio-databases/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/public-bio-databases/SKILL.md new file mode 100644 index 0000000..906e45c --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/public-bio-databases/SKILL.md @@ -0,0 +1,31 @@ +--- +name: public-bio-databases +description: Query public biological databases for genes, proteins, domains, structures, literature, networks, motifs, or general Solanaceae metadata through the bundled allowlisted MCP. Use for evidence lookup; never route private or pepper-specific data through it. +--- + +# Public Bio Databases + +Use the `public-bio-api` MCP rather than inventing URLs or scraping private portals. + +## Workflow + +1. Call `bio_api_catalog` to select a source and read its evidence limit. +2. Translate the question into a precise identifier or search expression. +3. Call `bio_api_query` with the smallest useful result limit. +4. Record the exact source URL, retrieval time, identifiers, release/header metadata when present, and empty/failed responses. +5. Cross-check high-impact claims with a second independent source or primary literature. + +Read [references/api-catalog.md](references/api-catalog.md) for source selection. + +## Interpretation rules + +- Database annotation is evidence, not truth by authority; record evidence codes and record versions when available. +- Sequence similarity alone does not prove one-to-one orthology or conserved biological function. +- STRING edges are functional associations, not automatically physical binding. +- Predicted structures require coverage and confidence inspection and do not establish mechanism. +- Motif matches are candidate regulatory sites, not occupancy or regulation proof. +- Search results are discovery aids; read the paper before citing it as support. + +## Privacy boundary + +Do not submit credentials, local paths, private identifiers, or excluded species-specific terms. Do not work around an MCP refusal. If a public source lacks a verified unauthenticated API, report that limit instead of scraping it. diff --git a/plugins/Presisitence/bio-research-forge/skills/public-bio-databases/references/api-catalog.md b/plugins/Presisitence/bio-research-forge/skills/public-bio-databases/references/api-catalog.md new file mode 100644 index 0000000..789bf7c --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/public-bio-databases/references/api-catalog.md @@ -0,0 +1,16 @@ +# Public API catalog + +| Source | Best for | Key caution | Documentation | +|---|---|---|---| +| NCBI E-utilities | identifier and literature/sequence index search | respect rate limits; record database and query | | +| UniProt REST | protein records and annotations | distinguish reviewed and unreviewed records | | +| InterPro API | protein families, domains, and sites | domain presence constrains function but rarely identifies mechanism | | +| Ensembl REST | public genome annotation lookup | record species and stable ID/version | | +| AlphaFold DB API | predicted protein structures | inspect pLDDT/PAE, coverage, disorder, and oligomeric assumptions | | +| RCSB PDB Data API | deposited structure metadata | inspect experimental method, resolution, construct, and assembly | | +| Europe PMC REST | literature discovery | a search hit is not verified claim support | | +| STRING API | functional association networks | combined scores mix evidence channels | | +| JASPAR REST | transcription-factor binding profiles | sequence matches require experimental validation | | +| SGN public BrAPI metadata | general Solanaceae-resource metadata | public generic metadata only; dedicated pepper operations are excluded | | + +The API server is an access layer, not a redistribution of these databases. Check current provider terms before high-volume use. diff --git a/plugins/Presisitence/bio-research-forge/skills/reproducible-analysis/SKILL.md b/plugins/Presisitence/bio-research-forge/skills/reproducible-analysis/SKILL.md new file mode 100644 index 0000000..e8899c6 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/skills/reproducible-analysis/SKILL.md @@ -0,0 +1,27 @@ +--- +name: reproducible-analysis +description: Turn a life-science analysis into a cleanly rerunnable workflow with protected raw data, centralized parameters, fixed seeds, environment capture, provenance, and verified outputs. Use for publication or handoff-quality analysis. +--- + +# Reproducible Analysis + +## Invariants + +- Raw data are read-only; transformed data go to a separate location. +- Paths are project-relative in shared code and configurable at the boundary. +- Parameters and thresholds are centralized and recorded. +- Every stochastic operation has an explicit seed. +- Software, reference database, annotation, and model versions are captured. +- Each output records its inputs, command/config, creation time, and checksum. + +## Workflow + +1. Define inputs, expected outputs, parameters, environment, and resource requirements. +2. Add preflight checks for files, schema, identifiers, sample counts, and free space. +3. Run from a clean process in documented order. +4. Capture stdout/stderr with bounded logs and preserve non-zero exits. +5. Verify output schema, row/sample counts, hashes, and scientific invariants. +6. Rerun from clean state; compare deterministic outputs exactly and stochastic outputs under declared tolerances. +7. Produce a run manifest and disclose partial or failed steps. + +Notebook state is not rerun evidence. A visible figure is not proof that the final code and source data agree. Use `evidence-review` for the final consistency check. From 148ea3d5924ff0668ee4ddc050e3d0a1ccfd1c06 Mon Sep 17 00:00:00 2001 From: maoyu Mao <153364649+Presisitence@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:10:58 +0800 Subject: [PATCH 5/9] Add plugin bio-research-forge --- .../Presisitence/bio-research-forge/LICENSE | 661 ++++++++++++++++++ 1 file changed, 661 insertions(+) create mode 100644 plugins/Presisitence/bio-research-forge/LICENSE diff --git a/plugins/Presisitence/bio-research-forge/LICENSE b/plugins/Presisitence/bio-research-forge/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. From e643f6bae5ad1550076a3279cee89e3e68d4b2af Mon Sep 17 00:00:00 2001 From: maoyu Mao <153364649+Presisitence@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:11:32 +0800 Subject: [PATCH 6/9] Add plugin bio-research-forge --- .../bio-research-forge/mcp/public-bio-api.mjs | 405 ++++++++++++++++++ 1 file changed, 405 insertions(+) create mode 100644 plugins/Presisitence/bio-research-forge/mcp/public-bio-api.mjs diff --git a/plugins/Presisitence/bio-research-forge/mcp/public-bio-api.mjs b/plugins/Presisitence/bio-research-forge/mcp/public-bio-api.mjs new file mode 100644 index 0000000..25cf4b9 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/mcp/public-bio-api.mjs @@ -0,0 +1,405 @@ +#!/usr/bin/env node + +import readline from 'node:readline'; + +const SERVER = { name: 'public-bio-api', version: '0.1.0' }; +const MAX_RESPONSE_BYTES = 250_000; +const DEFAULT_TIMEOUT_MS = 45_000; + +const SOURCES = { + ncbi: { + label: 'NCBI E-utilities', + category: 'literature-and-sequence', + operations: ['search'], + docs: 'https://www.ncbi.nlm.nih.gov/books/NBK25501/', + base: 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/', + notes: 'Read-only ESearch. Without an API key, callers should remain at or below 3 requests/second.', + }, + uniprot: { + label: 'UniProt REST API', + category: 'protein', + operations: ['search'], + docs: 'https://rest.uniprot.org/', + base: 'https://rest.uniprot.org/', + notes: 'Protein records and annotations. Query provenance and returned release headers should be retained.', + }, + interpro: { + label: 'InterPro API', + category: 'protein-domain', + operations: ['search', 'protein-entries'], + docs: 'https://www.ebi.ac.uk/interpro/api/', + base: 'https://www.ebi.ac.uk/interpro/api/', + notes: 'Protein families, domains, and sites. Results are evidence, not automatic functional proof.', + }, + ensembl: { + label: 'Ensembl REST', + category: 'genome', + operations: ['lookup-id', 'lookup-symbol'], + docs: 'https://rest.ensembl.org/', + base: 'https://rest.ensembl.org/', + notes: 'Public genome annotation lookup. Record species and stable identifier version where available.', + }, + alphafold: { + label: 'AlphaFold Protein Structure Database API', + category: 'structure', + operations: ['prediction'], + docs: 'https://alphafold.ebi.ac.uk/api-docs', + base: 'https://alphafold.ebi.ac.uk/api/', + notes: 'Predicted structures. Confidence and coverage must be reported; a prediction is not experimental validation.', + }, + rcsb: { + label: 'RCSB PDB Data API', + category: 'structure', + operations: ['entry'], + docs: 'https://data.rcsb.org/', + base: 'https://data.rcsb.org/rest/v1/core/', + notes: 'Experimentally deposited structure metadata. Inspect method, resolution, construct, and biological assembly.', + }, + europepmc: { + label: 'Europe PMC REST API', + category: 'literature', + operations: ['search'], + docs: 'https://europepmc.org/RestfulWebService', + base: 'https://www.ebi.ac.uk/europepmc/webservices/rest/', + notes: 'Literature discovery. Search hits must be read and checked before being used to support a claim.', + }, + string: { + label: 'STRING API', + category: 'network', + operations: ['network'], + docs: 'https://string-db.org/help/api/', + base: 'https://string-db.org/api/', + notes: 'Functional association network. Scores and text mining are not direct physical-interaction proof.', + }, + jaspar: { + label: 'JASPAR REST API', + category: 'regulatory', + operations: ['matrix', 'matrix-search'], + docs: 'https://jaspar.elixir.no/api/v1/docs/', + base: 'https://jaspar.elixir.no/api/v1/', + notes: 'Curated transcription-factor binding profiles. Motif matches are candidates, not occupancy evidence.', + }, + sgn: { + label: 'Sol Genomics Network public BrAPI metadata', + category: 'solanaceae-resource', + operations: ['common-crop-names'], + docs: 'https://solgenomics.net/brapi/v2/commoncropnames', + base: 'https://solgenomics.net/brapi/v2/', + notes: 'Generic public Solanaceae-resource metadata only. Pepper-specific operations are intentionally blocked.', + }, +}; + +const TOOLS = [ + { + name: 'bio_api_catalog', + description: 'List the public biological API allowlist, supported operations, evidence limits, and documentation URLs. No network request is made.', + inputSchema: { + type: 'object', + additionalProperties: false, + properties: { + category: { type: 'string', description: 'Optional category filter.' }, + }, + }, + }, + { + name: 'bio_api_query', + description: 'Run one read-only, bounded query against a named public biological API. Arbitrary URLs, local files, private resources, and pepper-specific queries are blocked. The result includes the exact source URL and retrieval time.', + inputSchema: { + type: 'object', + additionalProperties: false, + properties: { + source: { type: 'string', enum: Object.keys(SOURCES) }, + operation: { type: 'string' }, + query: { type: 'string' }, + id: { type: 'string' }, + species: { type: 'string' }, + database: { type: 'string' }, + identifiers: { type: 'array', items: { type: 'string' }, maxItems: 20 }, + fields: { type: 'array', items: { type: 'string' }, maxItems: 20 }, + limit: { type: 'integer', minimum: 1, maximum: 50 }, + }, + required: ['source', 'operation'], + }, + }, + { + name: 'bio_api_health', + description: 'Report server health and optionally perform a small live request to one public source. This never reads local research files.', + inputSchema: { + type: 'object', + additionalProperties: false, + properties: { + live: { type: 'boolean', default: false }, + source: { type: 'string', enum: Object.keys(SOURCES) }, + }, + }, + }, +]; + +function rpcSend(message) { + process.stdout.write(`${JSON.stringify(message)}\n`); +} + +function rpcResult(id, result) { + rpcSend({ jsonrpc: '2.0', id, result }); +} + +function rpcError(id, code, message, data) { + rpcSend({ jsonrpc: '2.0', id, error: { code, message, ...(data === undefined ? {} : { data }) } }); +} + +function textResult(value, isError = false) { + const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2); + return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) }; +} + +function positiveInt(value, fallback, max = 50) { + const parsed = Number(value); + if (!Number.isInteger(parsed) || parsed < 1) return fallback; + return Math.min(parsed, max); +} + +function requiredText(value, label) { + const text = typeof value === 'string' ? value.trim() : ''; + if (text === '') throw new Error(`${label} is required`); + return text; +} + +function safeToken(value, label, pattern = /^[A-Za-z0-9_.:-]+$/) { + const text = requiredText(value, label); + if (!pattern.test(text)) throw new Error(`${label} contains unsupported characters`); + return text; +} + +function assertPublicScope(args) { + const serialized = JSON.stringify(args || {}); + const banned = [ + /pepper/i, + /capsicum/i, + /capana/i, + /zunla/i, + /zhangshugang/i, + /\bcaz\d+/i, + /(?:[A-Za-z]:\\|\/Users\/|\/home\/)/, + /(?:api[_-]?key|token|password)\s*[:=]/i, + ]; + if (banned.some((rule) => rule.test(serialized))) { + throw new Error('Query blocked by the public-data boundary: private paths, credentials, and pepper-specific resources are not allowed.'); + } +} + +function urlFor(args) { + const source = requiredText(args.source, 'source'); + const operation = requiredText(args.operation, 'operation'); + const entry = SOURCES[source]; + if (!entry) throw new Error(`Unsupported source: ${source}`); + if (!entry.operations.includes(operation)) { + throw new Error(`Unsupported operation for ${source}: ${operation}. Allowed: ${entry.operations.join(', ')}`); + } + + const limit = positiveInt(args.limit, 10); + let url; + if (source === 'ncbi') { + const database = safeToken(args.database || 'gene', 'database', /^[A-Za-z0-9_-]+$/); + const query = requiredText(args.query, 'query'); + url = new URL('esearch.fcgi', entry.base); + url.searchParams.set('db', database); + url.searchParams.set('term', query); + url.searchParams.set('retmode', 'json'); + url.searchParams.set('retmax', String(limit)); + if (process.env.NCBI_API_KEY) url.searchParams.set('api_key', process.env.NCBI_API_KEY); + } else if (source === 'uniprot') { + url = new URL('uniprotkb/search', entry.base); + url.searchParams.set('query', requiredText(args.query, 'query')); + url.searchParams.set('format', 'json'); + url.searchParams.set('size', String(limit)); + if (Array.isArray(args.fields) && args.fields.length > 0) { + url.searchParams.set('fields', args.fields.map((field) => safeToken(field, 'field', /^[A-Za-z0-9_,-]+$/)).join(',')); + } + } else if (source === 'interpro' && operation === 'search') { + url = new URL('entry/interpro/', entry.base); + url.searchParams.set('search', requiredText(args.query, 'query')); + url.searchParams.set('page_size', String(limit)); + } else if (source === 'interpro') { + const id = safeToken(args.id, 'UniProt accession'); + url = new URL(`protein/uniprot/${encodeURIComponent(id)}/entry/interpro/`, entry.base); + url.searchParams.set('page_size', String(limit)); + } else if (source === 'ensembl' && operation === 'lookup-id') { + const id = safeToken(args.id, 'stable identifier'); + url = new URL(`lookup/id/${encodeURIComponent(id)}`, entry.base); + url.searchParams.set('content-type', 'application/json'); + } else if (source === 'ensembl') { + const species = safeToken(args.species, 'species', /^[A-Za-z0-9_]+$/); + const symbol = safeToken(args.id, 'symbol', /^[A-Za-z0-9_.-]+$/); + url = new URL(`lookup/symbol/${encodeURIComponent(species)}/${encodeURIComponent(symbol)}`, entry.base); + url.searchParams.set('content-type', 'application/json'); + } else if (source === 'alphafold') { + const accession = safeToken(args.id, 'UniProt accession'); + url = new URL(`prediction/${encodeURIComponent(accession)}`, entry.base); + } else if (source === 'rcsb') { + const pdbId = safeToken(args.id, 'PDB identifier', /^[A-Za-z0-9]{4}$/).toUpperCase(); + url = new URL(`entry/${pdbId}`, entry.base); + } else if (source === 'europepmc') { + url = new URL('search', entry.base); + url.searchParams.set('query', requiredText(args.query, 'query')); + url.searchParams.set('format', 'json'); + url.searchParams.set('pageSize', String(limit)); + } else if (source === 'string') { + const identifiers = Array.isArray(args.identifiers) ? args.identifiers : []; + if (identifiers.length === 0) throw new Error('identifiers is required'); + const clean = identifiers.map((id) => safeToken(id, 'identifier', /^[A-Za-z0-9_.:-]+$/)); + const species = safeToken(args.species, 'species taxonomy identifier', /^[0-9]+$/); + url = new URL('json/network', entry.base); + url.searchParams.set('identifiers', clean.join('\r')); + url.searchParams.set('species', species); + url.searchParams.set('limit', String(limit)); + } else if (source === 'jaspar' && operation === 'matrix') { + const id = safeToken(args.id, 'matrix identifier', /^[A-Za-z0-9_.-]+$/); + url = new URL(`matrix/${encodeURIComponent(id)}/`, entry.base); + } else if (source === 'jaspar') { + url = new URL('matrix/', entry.base); + url.searchParams.set('search', requiredText(args.query, 'query')); + url.searchParams.set('page_size', String(limit)); + } else if (source === 'sgn') { + url = new URL('commoncropnames', entry.base); + url.searchParams.set('pageSize', String(limit)); + } else { + throw new Error(`No request builder for ${source}/${operation}`); + } + return { source, operation, entry, url }; +} + +function scrubExcludedSpecies(value) { + if (Array.isArray(value)) { + return value + .filter((item) => !/\b(?:pepper|capsicum)\b/i.test(typeof item === 'string' ? item : JSON.stringify(item))) + .map(scrubExcludedSpecies); + } + if (value && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, scrubExcludedSpecies(item)])); + } + return value; +} + +async function fetchJson(url, timeoutMs = DEFAULT_TIMEOUT_MS) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetch(url, { + method: 'GET', + signal: controller.signal, + headers: { + accept: 'application/json', + 'user-agent': `${SERVER.name}/${SERVER.version}`, + }, + }); + const body = await response.text(); + if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}: ${body.slice(0, 1000)}`); + if (Buffer.byteLength(body, 'utf8') > MAX_RESPONSE_BYTES) { + throw new Error(`Response exceeded ${MAX_RESPONSE_BYTES} bytes. Narrow the query or lower limit.`); + } + let data; + try { data = JSON.parse(body); } catch { throw new Error(`Expected JSON but received: ${body.slice(0, 500)}`); } + return { data, headers: Object.fromEntries([...response.headers.entries()].filter(([key]) => /^(content-type|etag|last-modified|x-|link)/i.test(key))) }; + } finally { + clearTimeout(timer); + } +} + +function catalog(category) { + return Object.entries(SOURCES) + .filter(([, source]) => !category || source.category === category) + .map(([id, source]) => ({ id, ...source })); +} + +async function query(args) { + assertPublicScope(args); + const built = urlFor(args); + const received = await fetchJson(built.url); + const data = built.source === 'sgn' ? scrubExcludedSpecies(received.data) : received.data; + return { + source: built.source, + label: built.entry.label, + operation: built.operation, + retrievedAt: new Date().toISOString(), + sourceUrl: built.url.toString(), + documentation: built.entry.docs, + evidenceNote: built.entry.notes, + responseHeaders: received.headers, + data, + }; +} + +async function health(args = {}) { + const base = { + status: 'healthy', + server: SERVER, + node: process.version, + publicOnly: true, + arbitraryUrlsAllowed: false, + localFilesRead: false, + sources: Object.keys(SOURCES), + }; + if (!args.live) return base; + const source = args.source || 'ncbi'; + const probes = { + ncbi: { source: 'ncbi', operation: 'search', database: 'gene', query: 'FLC[sym] AND Arabidopsis thaliana[orgn]', limit: 1 }, + uniprot: { source: 'uniprot', operation: 'search', query: 'gene_exact:FLC AND organism_id:3702', fields: ['accession', 'id'], limit: 1 }, + interpro: { source: 'interpro', operation: 'search', query: 'NB-ARC', limit: 1 }, + ensembl: { source: 'ensembl', operation: 'lookup-symbol', species: 'arabidopsis_thaliana', id: 'FLC' }, + alphafold: { source: 'alphafold', operation: 'prediction', id: 'Q9C5Y0' }, + rcsb: { source: 'rcsb', operation: 'entry', id: '4G0F' }, + europepmc: { source: 'europepmc', operation: 'search', query: 'plant immunity', limit: 1 }, + string: { source: 'string', operation: 'network', identifiers: ['AT5G10140'], species: '3702', limit: 1 }, + jaspar: { source: 'jaspar', operation: 'matrix-search', query: 'WRKY', limit: 1 }, + sgn: { source: 'sgn', operation: 'common-crop-names', limit: 10 }, + }; + if (!probes[source]) throw new Error(`Unsupported source: ${source}`); + const result = await query(probes[source]); + return { ...base, live: { source, ok: true, sourceUrl: result.sourceUrl, retrievedAt: result.retrievedAt } }; +} + +async function callTool(name, args) { + if (name === 'bio_api_catalog') return textResult({ generatedAt: new Date().toISOString(), sources: catalog(args?.category) }); + if (name === 'bio_api_query') { + try { return textResult(await query(args || {})); } + catch (error) { return textResult(error instanceof Error ? error.message : String(error), true); } + } + if (name === 'bio_api_health') { + try { return textResult(await health(args || {})); } + catch (error) { return textResult(error instanceof Error ? error.message : String(error), true); } + } + return textResult(`Unknown tool: ${name}`, true); +} + +async function handle(message) { + if (!message || message.jsonrpc !== '2.0' || typeof message.method !== 'string') return; + const { id, method, params } = message; + if (id === undefined || id === null) return; + try { + if (method === 'initialize') { + rpcResult(id, { + protocolVersion: params?.protocolVersion || '2024-11-05', + capabilities: { tools: {} }, + serverInfo: SERVER, + }); + } else if (method === 'ping') { + rpcResult(id, {}); + } else if (method === 'tools/list') { + rpcResult(id, { tools: TOOLS }); + } else if (method === 'tools/call') { + rpcResult(id, await callTool(params?.name, params?.arguments)); + } else { + rpcError(id, -32601, `Method not found: ${method}`); + } + } catch (error) { + rpcError(id, -32603, error instanceof Error ? error.message : String(error)); + } +} + +const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); +input.on('line', (line) => { + const trimmed = line.trim(); + if (trimmed === '') return; + try { void handle(JSON.parse(trimmed)); } + catch (error) { rpcError(null, -32700, error instanceof Error ? error.message : String(error)); } +}); From 304e4494d7c7c0321507707c5ac2b7dffb2a18dc Mon Sep 17 00:00:00 2001 From: maoyu Mao <153364649+Presisitence@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:12:01 +0800 Subject: [PATCH 7/9] Add plugin bio-research-forge --- .../mcp/local-bio-tools.mjs | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 plugins/Presisitence/bio-research-forge/mcp/local-bio-tools.mjs diff --git a/plugins/Presisitence/bio-research-forge/mcp/local-bio-tools.mjs b/plugins/Presisitence/bio-research-forge/mcp/local-bio-tools.mjs new file mode 100644 index 0000000..b132b6f --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/mcp/local-bio-tools.mjs @@ -0,0 +1,192 @@ +#!/usr/bin/env node + +import { execFileSync, spawn } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import readline from 'node:readline'; + +const SERVER = { name: 'local-bio-tools', version: '0.1.0' }; +const TOOL_INFO = { + pymol: { name: 'PyMOL', mode: 'headless-render', formats: ['pdb', 'cif', 'mmcif', 'mol2', 'sdf', 'pse'] }, + snapgene: { name: 'SnapGene', mode: 'open-existing-file', formats: ['dna', 'gb', 'gbk', 'genbank', 'fasta', 'fa', 'ape'] }, + cytoscape: { name: 'Cytoscape', mode: 'open-existing-file', formats: ['cys', 'xgmml', 'sif', 'graphml', 'cyjs'] }, + fiji: { name: 'Fiji/ImageJ', mode: 'open-existing-file', formats: ['tif', 'tiff', 'png', 'jpg', 'jpeg', 'lif', 'czi', 'nd2', 'ome'] }, +}; + +const TOOLS = [ + { + name: 'local_bio_tool_status', + description: 'Detect the selected local biology tools (PyMOL, SnapGene, Cytoscape, Fiji) without installing or launching them.', + inputSchema: { type: 'object', additionalProperties: false, properties: { tool: { type: 'string', enum: Object.keys(TOOL_INFO) } } }, + }, + { + name: 'pymol_render', + description: 'Render an existing local molecular structure to a PNG with a safe preset. No arbitrary PyMOL command or script is accepted.', + inputSchema: { + type: 'object', additionalProperties: false, + properties: { + input_path: { type: 'string' }, output_path: { type: 'string' }, + representation: { type: 'string', enum: ['cartoon', 'surface', 'sticks', 'cartoon-and-sticks'], default: 'cartoon-and-sticks' }, + color: { type: 'string', enum: ['spectrum', 'chain', 'secondary-structure'], default: 'spectrum' }, + background: { type: 'string', enum: ['white', 'black', 'transparent'], default: 'white' }, + width: { type: 'integer', minimum: 400, maximum: 5000, default: 1800 }, + height: { type: 'integer', minimum: 400, maximum: 5000, default: 1400 }, + }, + required: ['input_path', 'output_path'], + }, + }, + { + name: 'local_bio_open', + description: 'Open one existing, format-compatible local file in SnapGene, Cytoscape, or Fiji. Use only when the user explicitly asks to open the desktop application.', + inputSchema: { + type: 'object', additionalProperties: false, + properties: { tool: { type: 'string', enum: ['snapgene', 'cytoscape', 'fiji'] }, file_path: { type: 'string' } }, + required: ['tool', 'file_path'], + }, + }, +]; + +function send(message) { process.stdout.write(`${JSON.stringify(message)}\n`); } +function rpcResult(id, value) { send({ jsonrpc: '2.0', id, result: value }); } +function rpcError(id, code, message) { send({ jsonrpc: '2.0', id, error: { code, message } }); } +function textResult(value, isError = false) { return { content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }], ...(isError ? { isError: true } : {}) }; } + +function commandPath(name) { + try { + const command = process.platform === 'win32' ? 'where.exe' : 'which'; + return execFileSync(command, [name], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).split(/\r?\n/).map((x) => x.trim()).find(Boolean) || null; + } catch { return null; } +} + +function driveRoots() { + if (process.platform !== 'win32') return ['/']; + try { + return execFileSync('powershell.exe', ['-NoProfile', '-Command', '(Get-PSDrive -PSProvider FileSystem).Root'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }) + .split(/\r?\n/).map((x) => x.trim()).filter((x) => /^[A-Za-z]:\\$/.test(x)); + } catch { return ['C:\\']; } +} + +function firstExisting(candidates) { return candidates.filter(Boolean).find((candidate) => existsSync(candidate)) || null; } +function childrenMatching(parent, fileName) { + try { return readdirSync(parent, { withFileTypes: true }).filter((x) => x.isDirectory()).map((x) => path.join(parent, x.name, fileName)); } + catch { return []; } +} + +function discover() { + const roots = driveRoots(); + const pf = [process.env.ProgramFiles, process.env['ProgramFiles(x86)'], process.env.LOCALAPPDATA].filter(Boolean); + const pymol = firstExisting([ + process.env.PYMOL_EXE, commandPath('pymol'), commandPath('PyMOLWin.exe'), + ...roots.flatMap((root) => [ + path.join(root, 'conda', 'miconda', 'envs', 'pymol', 'Scripts', 'pymol.exe'), + path.join(root, 'miniconda3', 'envs', 'pymol', 'Scripts', 'pymol.exe'), + path.join(root, 'anaconda3', 'envs', 'pymol', 'Scripts', 'pymol.exe'), + ]), + ...pf.flatMap((root) => [path.join(root, 'PyMOL', 'PyMOLWin.exe'), path.join(root, 'Schrodinger', 'PyMOL2', 'PyMOLWin.exe')]), + ]); + const snapgene = firstExisting([ + process.env.SNAPGENE_EXE, commandPath('SnapGene.exe'), + ...roots.map((root) => path.join(root, 'Tools', 'SnapGene', 'SnapGene.exe')), + ...pf.map((root) => path.join(root, 'SnapGene', 'SnapGene.exe')), + ]); + const cytoscape = firstExisting([ + process.env.CYTOSCAPE_EXE, commandPath('Cytoscape.exe'), + ...roots.flatMap((root) => childrenMatching(path.join(root, 'Tools', 'cytoscape'), 'Cytoscape.exe')), + ...pf.flatMap((root) => childrenMatching(root, path.join('Cytoscape', 'Cytoscape.exe'))), + ]); + const fiji = firstExisting([ + process.env.FIJI_EXE, commandPath('ImageJ-win64.exe'), commandPath('ImageJ'), + ...roots.map((root) => path.join(root, 'Tools', 'Fiji.app', 'ImageJ-win64.exe')), + ...pf.flatMap((root) => [path.join(root, 'Fiji.app', 'ImageJ-win64.exe'), path.join(root, 'Fiji', 'ImageJ-win64.exe')]), + ]); + return { pymol, snapgene, cytoscape, fiji }; +} + +function status(tool) { + const found = discover(); + const ids = tool ? [tool] : Object.keys(TOOL_INFO); + return { + generatedAt: new Date().toISOString(), localOnly: true, installsSoftware: false, + tools: ids.map((id) => ({ id, ...TOOL_INFO[id], installed: Boolean(found[id]), executable: found[id] })), + }; +} + +function existingCompatibleFile(value, tool) { + if (typeof value !== 'string' || !path.isAbsolute(value) || !existsSync(value)) throw new Error('file path must be an existing absolute path'); + const ext = path.extname(value).slice(1).toLowerCase(); + if (!TOOL_INFO[tool].formats.includes(ext)) throw new Error(`${TOOL_INFO[tool].name} does not accept .${ext} through this bridge`); + return path.resolve(value); +} +function runProcess(exe, args, timeout = 180000) { + return new Promise((resolve, reject) => { + const child = spawn(exe, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; let stderr = ''; + const timer = setTimeout(() => { child.kill(); reject(new Error(`Process timed out after ${timeout} ms`)); }, timeout); + child.stdout.on('data', (chunk) => { stdout += chunk; }); child.stderr.on('data', (chunk) => { stderr += chunk; }); + child.on('error', (err) => { clearTimeout(timer); reject(err); }); + child.on('close', (code) => { clearTimeout(timer); code === 0 ? resolve({ stdout, stderr }) : reject(new Error((stderr || stdout || `Process exited with ${code}`).slice(-4000))); }); + }); +} + +async function pymolRender(args) { + const exe = discover().pymol; + if (!exe) throw new Error('PyMOL was not found. Set PYMOL_EXE or add it to PATH. No installation was attempted.'); + const input = existingCompatibleFile(args.input_path, 'pymol'); + if (typeof args.output_path !== 'string' || !path.isAbsolute(args.output_path) || !/\.png$/i.test(args.output_path)) throw new Error('output_path must be an absolute .png path'); + const output = path.resolve(args.output_path); + const representation = args.representation || 'cartoon-and-sticks'; + const color = args.color || 'spectrum'; const background = args.background || 'white'; + const width = Math.max(400, Math.min(5000, Number(args.width) || 1800)); const height = Math.max(400, Math.min(5000, Number(args.height) || 1400)); + mkdirSync(path.dirname(output), { recursive: true }); + const tmp = mkdtempSync(path.join(os.tmpdir(), 'bio-pymol-')); + const script = path.join(tmp, 'render.pml'); + const commands = ['reinitialize', 'python', `cmd.load(${JSON.stringify(input)}, "structure")`, 'python end', 'hide everything, all']; + if (representation === 'cartoon') commands.push('show cartoon, polymer.protein'); + if (representation === 'surface') commands.push('show surface, all'); + if (representation === 'sticks') commands.push('show sticks, all'); + if (representation === 'cartoon-and-sticks') commands.push('show cartoon, polymer.protein', 'show sticks, organic'); + if (color === 'spectrum') commands.push('spectrum count, rainbow, all'); + if (color === 'chain') commands.push('util.cbc("all")'); + if (color === 'secondary-structure') commands.push('color marine, ss h', 'color gold, ss s', 'color grey70, ss l'); + commands.push(`bg_color ${background === 'transparent' ? 'white' : background}`); + commands.push(`set ray_opaque_background, ${background === 'transparent' ? 'off' : 'on'}`, 'set antialias, 2', 'orient all', `ray ${width}, ${height}`, 'python', `cmd.png(${JSON.stringify(output)}, dpi=300)`, 'python end', 'quit'); + writeFileSync(script, `${commands.join('\n')}\n`, 'utf8'); + try { + const executed = await runProcess(exe, ['-cq', '-r', script]); + if (!existsSync(output)) throw new Error(`PyMOL completed without producing the requested PNG. Output: ${(executed.stderr || executed.stdout).slice(-1500)}`); + return { tool: 'pymol', input, png: output, representation, color, background, localOnly: true, previewInstruction: `Display the PNG inline: ![PyMOL render](${output})` }; + } finally { rmSync(tmp, { recursive: true, force: true }); } +} + +function openLocal(args) { + const id = args?.tool; if (!['snapgene', 'cytoscape', 'fiji'].includes(id)) throw new Error('tool must be snapgene, cytoscape, or fiji'); + const exe = discover()[id]; if (!exe) throw new Error(`${TOOL_INFO[id].name} was not found. No installation was attempted.`); + const file = existingCompatibleFile(args.file_path, id); + const child = spawn(exe, [file], { detached: true, stdio: 'ignore', windowsHide: true }); child.unref(); + return { tool: id, launched: true, file, localOnly: true, note: 'The existing file was opened; the bridge did not edit or export it.' }; +} + +async function callTool(name, args) { + try { + if (name === 'local_bio_tool_status') return textResult(status(args?.tool)); + if (name === 'pymol_render') return textResult(await pymolRender(args || {})); + if (name === 'local_bio_open') return textResult(openLocal(args || {})); + return textResult(`Unknown tool: ${name}`, true); + } catch (err) { return textResult(err instanceof Error ? err.message : String(err), true); } +} + +async function handle(message) { + if (!message || message.jsonrpc !== '2.0' || message.id == null) return; + const { id, method, params } = message; + if (method === 'initialize') rpcResult(id, { protocolVersion: params?.protocolVersion || '2024-11-05', capabilities: { tools: {} }, serverInfo: SERVER }); + else if (method === 'ping') rpcResult(id, {}); + else if (method === 'tools/list') rpcResult(id, { tools: TOOLS }); + else if (method === 'tools/call') rpcResult(id, await callTool(params?.name, params?.arguments)); + else rpcError(id, -32601, `Method not found: ${method}`); +} + +readline.createInterface({ input: process.stdin, crlfDelay: Infinity }).on('line', (line) => { + if (!line.trim()) return; + try { void handle(JSON.parse(line)); } catch (err) { rpcError(null, -32700, err instanceof Error ? err.message : String(err)); } +}); From d022291a0c84d6354c5d00d3b9a130ec0897c63b Mon Sep 17 00:00:00 2001 From: maoyu Mao <153364649+Presisitence@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:12:22 +0800 Subject: [PATCH 8/9] Add plugin bio-research-forge --- .../bio-research-forge/mcp/rna-figure.mjs | 197 ++++++++++++++++++ 1 file changed, 197 insertions(+) create mode 100644 plugins/Presisitence/bio-research-forge/mcp/rna-figure.mjs diff --git a/plugins/Presisitence/bio-research-forge/mcp/rna-figure.mjs b/plugins/Presisitence/bio-research-forge/mcp/rna-figure.mjs new file mode 100644 index 0000000..cc08099 --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/mcp/rna-figure.mjs @@ -0,0 +1,197 @@ +#!/usr/bin/env node + +import { spawn } from 'node:child_process'; +import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import readline from 'node:readline'; +import { execFileSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const SERVER = { name: 'rna-figure', version: '0.1.0' }; +const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const SCRIPT = path.join(ROOT, 'scripts', 'rna-figure.R'); +const TYPES = ['volcano', 'pca', 'heatmap', 'expression-boxplot', 'enrichment-dotplot']; + +const TOOLS = [ + { + name: 'rna_figure_status', + description: 'Check the local R plotting runtime and required packages without reading research data.', + inputSchema: { type: 'object', additionalProperties: false, properties: {} }, + }, + { + name: 'rna_figure_create', + description: 'Create a publication-oriented RNA result figure locally as PNG and PDF. The tool never uploads the input. After creation, display the returned PNG path in the conversation.', + inputSchema: { + type: 'object', additionalProperties: false, + properties: { + plot_type: { type: 'string', enum: TYPES }, + input_path: { type: 'string', description: 'Absolute path to a CSV/TSV table explicitly selected by the user.' }, + output_dir: { type: 'string', description: 'Existing or creatable local output directory.' }, + output_name: { type: 'string', pattern: '^[A-Za-z0-9._-]+$', default: 'rna-figure' }, + metadata_path: { type: 'string', description: 'Optional PCA metadata CSV/TSV with sample and group columns.' }, + columns: { + type: 'object', additionalProperties: false, + properties: { + gene: { type: 'string' }, x: { type: 'string' }, y: { type: 'string' }, label: { type: 'string' }, + group: { type: 'string' }, facet: { type: 'string' }, term: { type: 'string' }, size: { type: 'string' }, color: { type: 'string' }, sample: { type: 'string' }, + }, + }, + options: { + type: 'object', additionalProperties: false, + properties: { + alpha: { type: 'number', exclusiveMinimum: 0, maximum: 1, default: 0.05 }, + lfc: { type: 'number', minimum: 0, default: 1 }, + top_n: { type: 'integer', minimum: 1, maximum: 500, default: 30 }, + label_n: { type: 'integer', minimum: 0, maximum: 50, default: 10 }, + width: { type: 'number', minimum: 3, maximum: 20, default: 7 }, + height: { type: 'number', minimum: 3, maximum: 20, default: 5.5 }, + dpi: { type: 'integer', minimum: 150, maximum: 1200, default: 300 }, + transform: { type: 'string', enum: ['auto', 'none', 'log2'], default: 'auto' }, + }, + }, + }, + required: ['plot_type', 'input_path', 'output_dir'], + }, + }, +]; + +function send(message) { process.stdout.write(`${JSON.stringify(message)}\n`); } +function result(id, value) { send({ jsonrpc: '2.0', id, result: value }); } +function error(id, code, message) { send({ jsonrpc: '2.0', id, error: { code, message } }); } +function textResult(value, isError = false) { + return { content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }], ...(isError ? { isError: true } : {}) }; +} + +function commandPath(name) { + try { + const command = process.platform === 'win32' ? 'where.exe' : 'which'; + return execFileSync(command, [name], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).split(/\r?\n/).map((x) => x.trim()).find(Boolean) || null; + } catch { return null; } +} + +function registryR() { + if (process.platform !== 'win32') return null; + for (const key of ['HKCU\\SOFTWARE\\R-core\\R', 'HKLM\\SOFTWARE\\R-core\\R']) { + try { + const value = execFileSync('reg.exe', ['query', key, '/v', 'InstallPath'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); + const match = value.match(/InstallPath\s+REG_SZ\s+(.+)$/mi); + if (match) { + const candidate = path.join(match[1].trim(), 'bin', 'Rscript.exe'); + if (existsSync(candidate)) return candidate; + } + } catch { /* continue */ } + } + return null; +} + +function driveRoots() { + if (process.platform !== 'win32') return ['/']; + try { + return execFileSync('powershell.exe', ['-NoProfile', '-Command', '(Get-PSDrive -PSProvider FileSystem).Root'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }) + .split(/\r?\n/).map((x) => x.trim()).filter((x) => /^[A-Za-z]:\\$/.test(x)); + } catch { return ['C:\\']; } +} + +function versionedR() { + for (const root of driveRoots()) { + for (const parent of [path.join(root, 'AI_IDE'), path.join(root, 'Program Files', 'R')]) { + try { + const candidates = readdirSync(parent, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && /^R[-_]?\d/i.test(entry.name)) + .map((entry) => path.join(parent, entry.name, 'bin', 'Rscript.exe')); + const hit = candidates.find((candidate) => existsSync(candidate)); + if (hit) return hit; + } catch { /* continue */ } + } + } + return null; +} + +function rscriptPath() { + const candidates = [process.env.RSCRIPT_EXE, commandPath('Rscript'), registryR(), versionedR()].filter(Boolean); + return candidates.find((candidate) => existsSync(candidate)) || null; +} + +function run(exe, args, timeout = 180000) { + return new Promise((resolve, reject) => { + const child = spawn(exe, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; let stderr = ''; + const timer = setTimeout(() => { child.kill(); reject(new Error(`Process timed out after ${timeout} ms`)); }, timeout); + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + child.on('error', (err) => { clearTimeout(timer); reject(err); }); + child.on('close', (code) => { + clearTimeout(timer); + if (code === 0) resolve({ stdout, stderr }); + else reject(new Error((stderr || stdout || `Process exited with ${code}`).slice(-4000))); + }); + }); +} + +async function status() { + const exe = rscriptPath(); + if (!exe) return { ready: false, rscript: null, script: existsSync(SCRIPT), packages: {}, reason: 'Rscript not found. Set RSCRIPT_EXE or add Rscript to PATH.' }; + const probe = await run(exe, ['--vanilla', '-e', "p<-c('jsonlite','ggplot2','pheatmap','ggrepel');cat(paste(p,vapply(p,requireNamespace,logical(1),quietly=TRUE),sep='='),sep='\\n')"], 30000); + const packages = Object.fromEntries(probe.stdout.split(/\r?\n/).filter((line) => line.includes('=')).map((line) => { const [k, v] = line.trim().split('='); return [k, v === 'TRUE']; })); + return { ready: Boolean(packages.jsonlite && packages.ggplot2 && packages.pheatmap), rscript: exe, script: existsSync(SCRIPT), packages }; +} + +function absoluteExistingFile(value, label) { + if (typeof value !== 'string' || !path.isAbsolute(value) || !existsSync(value)) throw new Error(`${label} must be an existing absolute path`); + if (!/\.(csv|tsv|txt)$/i.test(value)) throw new Error(`${label} must be CSV, TSV, or TXT`); + return path.resolve(value); +} + +async function createFigure(args) { + const runtime = await status(); + if (!runtime.ready) throw new Error(`RNA plotting runtime is not ready: ${JSON.stringify(runtime)}`); + if (!TYPES.includes(args?.plot_type)) throw new Error(`Unsupported plot_type: ${args?.plot_type}`); + const inputPath = absoluteExistingFile(args.input_path, 'input_path'); + const outputDir = path.resolve(String(args.output_dir || '')); + if (!path.isAbsolute(outputDir)) throw new Error('output_dir must be an absolute path'); + const outputName = args.output_name || 'rna-figure'; + if (!/^[A-Za-z0-9._-]+$/.test(outputName)) throw new Error('output_name contains unsupported characters'); + const metadataPath = args.metadata_path ? absoluteExistingFile(args.metadata_path, 'metadata_path') : null; + const tmp = mkdtempSync(path.join(os.tmpdir(), 'bio-rna-')); + const configPath = path.join(tmp, 'config.json'); + const config = { + plot_type: args.plot_type, input_path: inputPath, output_dir: outputDir, output_name: outputName, + metadata_path: metadataPath, columns: args.columns || {}, options: args.options || {}, + }; + writeFileSync(configPath, JSON.stringify(config), 'utf8'); + try { + const executed = await run(runtime.rscript, ['--vanilla', SCRIPT, configPath]); + const lines = executed.stdout.split(/\r?\n/).filter(Boolean); + const payloadLine = [...lines].reverse().find((line) => line.startsWith('RNA_FIGURE_RESULT=')); + if (!payloadLine) throw new Error(`R did not return a result manifest: ${(executed.stderr || executed.stdout).slice(-2000)}`); + const payload = JSON.parse(payloadLine.slice('RNA_FIGURE_RESULT='.length)); + for (const key of ['png', 'pdf', 'plot_data']) if (!existsSync(payload[key])) throw new Error(`Expected output missing: ${payload[key]}`); + return { ...payload, localOnly: true, previewInstruction: `Display the PNG inline: ![RNA figure](${payload.png})`, runtime: { rscript: runtime.rscript, packages: runtime.packages } }; + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +} + +async function callTool(name, args) { + try { + if (name === 'rna_figure_status') return textResult(await status()); + if (name === 'rna_figure_create') return textResult(await createFigure(args || {})); + return textResult(`Unknown tool: ${name}`, true); + } catch (err) { return textResult(err instanceof Error ? err.message : String(err), true); } +} + +async function handle(message) { + if (!message || message.jsonrpc !== '2.0' || message.id == null) return; + const { id, method, params } = message; + if (method === 'initialize') result(id, { protocolVersion: params?.protocolVersion || '2024-11-05', capabilities: { tools: {} }, serverInfo: SERVER }); + else if (method === 'ping') result(id, {}); + else if (method === 'tools/list') result(id, { tools: TOOLS }); + else if (method === 'tools/call') result(id, await callTool(params?.name, params?.arguments)); + else error(id, -32601, `Method not found: ${method}`); +} + +readline.createInterface({ input: process.stdin, crlfDelay: Infinity }).on('line', (line) => { + if (!line.trim()) return; + try { void handle(JSON.parse(line)); } catch (err) { error(null, -32700, err instanceof Error ? err.message : String(err)); } +}); From 05cd20787ee3c1bf16aa8c35a6b0683b2eb34c82 Mon Sep 17 00:00:00 2001 From: maoyu Mao <153364649+Presisitence@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:12:46 +0800 Subject: [PATCH 9/9] Add plugin bio-research-forge --- .../bio-research-forge/scripts/rna-figure.R | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 plugins/Presisitence/bio-research-forge/scripts/rna-figure.R diff --git a/plugins/Presisitence/bio-research-forge/scripts/rna-figure.R b/plugins/Presisitence/bio-research-forge/scripts/rna-figure.R new file mode 100644 index 0000000..050384c --- /dev/null +++ b/plugins/Presisitence/bio-research-forge/scripts/rna-figure.R @@ -0,0 +1,119 @@ +#!/usr/bin/env Rscript + +suppressPackageStartupMessages({ + library(jsonlite) + library(ggplot2) +}) + +args <- commandArgs(trailingOnly = TRUE) +if (length(args) != 1L) stop("Expected one JSON configuration path") +cfg <- jsonlite::fromJSON(args[[1]], simplifyVector = FALSE) + +pick <- function(df, explicit = NULL, choices = character()) { + if (!is.null(explicit) && nzchar(explicit) && explicit %in% names(df)) return(explicit) + hit <- choices[choices %in% names(df)] + if (length(hit)) hit[[1]] else NULL +} +read_table <- function(file) { + sep <- if (grepl("\\.csv$", file, ignore.case = TRUE)) "," else "\t" + read.delim(file, sep = sep, header = TRUE, check.names = FALSE, stringsAsFactors = FALSE, quote = '"', comment.char = "") +} +ratio_number <- function(x) { + x <- as.character(x) + vapply(x, function(z) { + if (grepl("/", z, fixed = TRUE)) { q <- strsplit(z, "/", fixed = TRUE)[[1]]; return(as.numeric(q[[1]]) / as.numeric(q[[2]])) } + as.numeric(z) + }, numeric(1)) +} +theme_pub <- function() theme_classic(base_size = 11, base_family = "sans") + theme(axis.title = element_text(face = "bold"), legend.title = element_text(face = "bold"), plot.title = element_text(face = "bold"), strip.background = element_rect(fill = "#EEF4F1", colour = NA)) +save_plot <- function(p, png, pdf, width, height, dpi) { + ggsave(png, p, width = width, height = height, dpi = dpi, bg = "white") + ggsave(pdf, p, width = width, height = height, device = cairo_pdf, bg = "white") +} + +dir.create(cfg$output_dir, recursive = TRUE, showWarnings = FALSE) +prefix <- file.path(cfg$output_dir, cfg$output_name) +png <- paste0(prefix, ".png") +pdf <- paste0(prefix, ".pdf") +plot_data_path <- paste0(prefix, ".plot-data.csv") +df <- read_table(cfg$input_path) +if (!nrow(df)) stop("Input table has no rows") +cols <- cfg$columns +opt <- cfg$options +alpha <- ifelse(is.null(opt$alpha), 0.05, as.numeric(opt$alpha)) +lfc <- ifelse(is.null(opt$lfc), 1, as.numeric(opt$lfc)) +top_n <- ifelse(is.null(opt$top_n), 30L, as.integer(opt$top_n)) +label_n <- ifelse(is.null(opt$label_n), 10L, as.integer(opt$label_n)) +width <- ifelse(is.null(opt$width), 7, as.numeric(opt$width)) +height <- ifelse(is.null(opt$height), 5.5, as.numeric(opt$height)) +dpi <- ifelse(is.null(opt$dpi), 300L, as.integer(opt$dpi)) +transform <- ifelse(is.null(opt$transform), "auto", opt$transform) + +if (cfg$plot_type == "volcano") { + xcol <- pick(df, cols$x, c("log2FoldChange", "log2FC", "logFC", "effect")) + ycol <- pick(df, cols$y, c("padj", "FDR", "adj.P.Val", "pvalue", "PValue")) + labcol <- pick(df, cols$label, c("gene", "gene_id", "Gene", "ID", names(df)[[1]])) + if (is.null(xcol) || is.null(ycol)) stop("Volcano plot requires fold-change and adjusted-p columns") + out <- data.frame(label = as.character(df[[labcol]]), effect = as.numeric(df[[xcol]]), p = pmax(as.numeric(df[[ycol]]), .Machine$double.xmin)) + out$status <- ifelse(out$p < alpha & out$effect >= lfc, "Up", ifelse(out$p < alpha & out$effect <= -lfc, "Down", "Not significant")) + out$neglog10p <- -log10(out$p) + out$show_label <- "" + idx <- head(order(out$p, -abs(out$effect), na.last = NA), label_n) + out$show_label[idx] <- out$label[idx] + p <- ggplot(out, aes(effect, neglog10p, colour = status)) + geom_point(alpha = 0.75, size = 1.8) + + geom_vline(xintercept = c(-lfc, lfc), linetype = 2, colour = "grey45") + geom_hline(yintercept = -log10(alpha), linetype = 2, colour = "grey45") + + scale_colour_manual(values = c(Down = "#3B75AF", `Not significant` = "#B8B8B8", Up = "#D8574C")) + labs(x = "log2 fold change", y = "-log10 adjusted P", colour = NULL, title = "Differential expression") + theme_pub() + if (label_n > 0 && requireNamespace("ggrepel", quietly = TRUE)) p <- p + ggrepel::geom_text_repel(aes(label = show_label), max.overlaps = Inf, size = 3, box.padding = 0.25, show.legend = FALSE) +} else if (cfg$plot_type %in% c("pca", "heatmap")) { + gene_col <- pick(df, cols$gene, c("gene", "gene_id", "Gene", "ID", names(df)[[1]])) + numeric_cols <- names(df)[vapply(df, is.numeric, logical(1))] + if (length(numeric_cols) < 2) stop("PCA/heatmap requires at least two numeric sample columns") + mat <- as.matrix(df[numeric_cols]); storage.mode(mat) <- "numeric" + rownames(mat) <- make.unique(as.character(df[[gene_col]])) + if (transform == "log2" || (transform == "auto" && all(mat >= 0, na.rm = TRUE) && max(mat, na.rm = TRUE) > 50)) mat <- log2(mat + 1) + vars <- apply(mat, 1, var, na.rm = TRUE); keep <- head(order(vars, decreasing = TRUE, na.last = NA), min(top_n, nrow(mat))) + if (cfg$plot_type == "pca") { + fit <- prcomp(t(mat[keep, , drop = FALSE]), center = TRUE, scale. = TRUE) + variance <- 100 * fit$sdev^2 / sum(fit$sdev^2) + out <- data.frame(sample = rownames(fit$x), PC1 = fit$x[, 1], PC2 = fit$x[, 2], group = "Samples", check.names = FALSE) + if (!is.null(cfg$metadata_path)) { + meta <- read_table(cfg$metadata_path) + sample_col <- pick(meta, cols$sample, c("sample", "sample_name", "Sample", names(meta)[[1]])) + group_col <- pick(meta, cols$group, c("group", "group_name", "Group", "condition")) + if (!is.null(sample_col) && !is.null(group_col)) out$group <- as.character(meta[[group_col]][match(out$sample, meta[[sample_col]])]) + } + p <- ggplot(out, aes(PC1, PC2, colour = group, label = sample)) + geom_hline(yintercept = 0, colour = "grey90") + geom_vline(xintercept = 0, colour = "grey90") + geom_point(size = 3.2) + + labs(x = sprintf("PC1 (%.1f%%)", variance[[1]]), y = sprintf("PC2 (%.1f%%)", variance[[2]]), colour = NULL, title = "Sample-level PCA") + theme_pub() + if (requireNamespace("ggrepel", quietly = TRUE)) p <- p + ggrepel::geom_text_repel(size = 3, show.legend = FALSE) + } else { + out <- t(scale(t(mat[keep, , drop = FALSE]))) + out[!is.finite(out)] <- 0 + png(png, width = width, height = height, units = "in", res = dpi, bg = "white") + pheatmap::pheatmap(out, border_color = NA, cluster_rows = TRUE, cluster_cols = TRUE, fontsize = 8, main = sprintf("Top %d variable genes (row z-score)", nrow(out)), color = colorRampPalette(c("#315B9A", "#F7F7F7", "#C6413A"))(101)) + dev.off() + cairo_pdf(pdf, width = width, height = height) + pheatmap::pheatmap(out, border_color = NA, cluster_rows = TRUE, cluster_cols = TRUE, fontsize = 8, main = sprintf("Top %d variable genes (row z-score)", nrow(out)), color = colorRampPalette(c("#315B9A", "#F7F7F7", "#C6413A"))(101)) + dev.off() + out <- data.frame(gene = rownames(out), out, check.names = FALSE) + } +} else if (cfg$plot_type == "expression-boxplot") { + xcol <- pick(df, cols$x, c("group", "condition", "treatment")); ycol <- pick(df, cols$y, c("value", "expression", "abundance")); facetcol <- pick(df, cols$facet, c("gene", "feature")) + if (is.null(xcol) || is.null(ycol)) stop("Expression boxplot requires x/group and y/value columns") + out <- data.frame(group = as.factor(df[[xcol]]), value = as.numeric(df[[ycol]]), feature = if (is.null(facetcol)) "Expression" else as.character(df[[facetcol]])) + p <- ggplot(out, aes(group, value, fill = group)) + geom_boxplot(width = 0.62, outlier.shape = NA, alpha = 0.7) + geom_jitter(width = 0.12, size = 1.5, alpha = 0.75) + + scale_fill_brewer(palette = "Set2") + labs(x = NULL, y = "Expression", fill = NULL, title = "Expression distribution") + theme_pub() + theme(legend.position = "none") + if (length(unique(out$feature)) > 1) p <- p + facet_wrap(~feature, scales = "free_y") +} else if (cfg$plot_type == "enrichment-dotplot") { + termcol <- pick(df, cols$term, c("Description", "Term", "term", "pathway")); xcol <- pick(df, cols$x, c("GeneRatio", "gene_ratio", "RichFactor", "ratio")); sizecol <- pick(df, cols$size, c("Count", "count", "GeneCount")); colorcol <- pick(df, cols$color, c("padj", "p.adjust", "FDR", "pvalue")); facetcol <- pick(df, cols$facet, c("Category", "category", "Ontology")) + if (any(vapply(list(termcol, xcol, sizecol, colorcol), is.null, logical(1)))) stop("Enrichment dotplot requires term, ratio, count, and adjusted-p columns") + out <- data.frame(term = as.character(df[[termcol]]), ratio = ratio_number(df[[xcol]]), count = as.numeric(df[[sizecol]]), padj = pmax(as.numeric(df[[colorcol]]), .Machine$double.xmin), category = if (is.null(facetcol)) "Enrichment" else as.character(df[[facetcol]])) + out <- out[order(out$padj, -out$ratio), , drop = FALSE]; out <- head(out, min(top_n, nrow(out))); out$term <- factor(out$term, levels = rev(unique(out$term))) + p <- ggplot(out, aes(ratio, term, size = count, colour = -log10(padj))) + geom_point(alpha = 0.88) + scale_colour_viridis_c(option = "C", end = 0.92) + + labs(x = "Gene ratio", y = NULL, size = "Count", colour = "-log10 adj. P", title = "Functional enrichment") + theme_pub() + if (length(unique(out$category)) > 1) p <- p + facet_grid(category ~ ., scales = "free_y", space = "free_y") +} else stop("Unsupported plot type") + +if (cfg$plot_type != "heatmap") save_plot(p, png, pdf, width, height, dpi) +write.csv(out, plot_data_path, row.names = FALSE, fileEncoding = "UTF-8") +manifest <- list(plot_type = cfg$plot_type, png = normalizePath(png, winslash = "/", mustWork = TRUE), pdf = normalizePath(pdf, winslash = "/", mustWork = TRUE), plot_data = normalizePath(plot_data_path, winslash = "/", mustWork = TRUE), rows = nrow(out), generated_at = format(Sys.time(), tz = "UTC", usetz = TRUE)) +cat("RNA_FIGURE_RESULT=", jsonlite::toJSON(manifest, auto_unbox = TRUE), "\n", sep = "")