diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c0a94be1323010919b7cb28347b5292c858b85d4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install augustus via conda (e.g., from bioconda) +RUN conda install -c bioconda augustus -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY augustus_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/augustus_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/augustus_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/app/__pycache__/augustus_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/app/__pycache__/augustus_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..928f27c99c0dd5d8fc370a6efa720048f6f39438 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/app/__pycache__/augustus_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/app/augustus_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/app/augustus_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ada35adfe18bc95d0db30fe0ee9900a35bf1c03b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/app/augustus_server.py @@ -0,0 +1,149 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Literal + +# Assume mcp.tool is available in the execution environment. +# Since we are not importing it, we can define a dummy decorator +# to make the code syntactically valid. +class mcp: + def tool(func): + return func + +@mcp.tool +def augustus( + query_file: Path, + species: str, + strand: Literal["both", "forward", "backward"] = "both", + genemodel: Literal["partial", "intronless", "complete", "atleastone", "exactlyone"] = "partial", + outfile: Optional[Path] = None, + hints_file: Optional[Path] = None, + gff3: bool = False, + utr: bool = False, + singlestrand: bool = False, + protein: bool = True, + introns: bool = True, + start: bool = True, + stop: bool = True, + cds: bool = True, + codingseq: bool = False, + no_in_frame_stop: bool = False, + alternatives_from_evidence: bool = True, + alternatives_from_sampling: bool = False, + sample: Optional[int] = None, + keep_viterbi: bool = False, + no_prediction: bool = False, + progress: bool = False, + unique_gene_id: bool = False, + softmasking: bool = False, + extrinsic_cfg_file: Optional[Path] = None, + augustus_config_path: Optional[Path] = None, +) -> dict: + """ + Runs AUGUSTUS, a tool for gene prediction in eukaryotes. + + This tool predicts genes in a given input FASTA file (query_file) based on a species-specific model. + It supports various prediction models, extrinsic evidence (hints), and output formats. + """ + # 1. Input validation + if not query_file.is_file(): + raise FileNotFoundError(f"Input query file not found: {query_file}") + if hints_file and not hints_file.is_file(): + raise FileNotFoundError(f"Hints file not found: {hints_file}") + if extrinsic_cfg_file and not extrinsic_cfg_file.is_file(): + raise FileNotFoundError(f"Extrinsic config file not found: {extrinsic_cfg_file}") + if augustus_config_path and not augustus_config_path.is_dir(): + raise NotADirectoryError(f"AUGUSTUS_CONFIG_PATH is not a valid directory: {augustus_config_path}") + + # 2. Command construction + cmd = ["augustus"] + + # Add parameters + cmd.append(f"--species={species}") + cmd.append(f"--strand={strand}") + cmd.append(f"--genemodel={genemodel}") + + # Boolean flags with true/false values + if singlestrand: + cmd.append("--singlestrand=true") + if no_in_frame_stop: + cmd.append("--noInFrameStop=true") + if alternatives_from_evidence: + cmd.append("--alternatives-from-evidence=true") + if alternatives_from_sampling: + cmd.append("--alternatives-from-sampling=true") + if keep_viterbi: + cmd.append("--keep_viterbi=true") + if no_prediction: + cmd.append("--noprediction=true") + if progress: + cmd.append("--progress=true") + if unique_gene_id: + cmd.append("--uniqueGeneId=true") + + # Boolean flags with on/off values + cmd.append(f"--gff3={'on' if gff3 else 'off'}") + cmd.append(f"--UTR={'on' if utr else 'off'}") + cmd.append(f"--protein={'on' if protein else 'off'}") + cmd.append(f"--introns={'on' if introns else 'off'}") + cmd.append(f"--start={'on' if start else 'off'}") + cmd.append(f"--stop={'on' if stop else 'off'}") + cmd.append(f"--cds={'on' if cds else 'off'}") + cmd.append(f"--codingseq={'on' if codingseq else 'off'}") + + # Boolean flag with 1/0 value + if softmasking: + cmd.append("--softmasking=1") + + # Optional file/directory paths and other values + if hints_file: + cmd.append(f"--hintsfile={hints_file}") + if extrinsic_cfg_file: + cmd.append(f"--extrinsicCfgFile={extrinsic_cfg_file}") + if augustus_config_path: + cmd.append(f"--AUGUSTUS_CONFIG_PATH={augustus_config_path}") + if sample is not None: + cmd.append(f"--sample={sample}") + if outfile: + # Ensure parent directory exists for the output file + outfile.parent.mkdir(parents=True, exist_ok=True) + cmd.append(f"--outfile={outfile}") + + # Positional argument (must be last for some versions) + cmd.append(str(query_file)) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # 3. Subprocess execution + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + raise RuntimeError("augustus executable not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"AUGUSTUS execution failed with exit code {e.returncode}") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "AUGUSTUS execution failed.", + "return_code": e.returncode, + "output_files": [] + } + + # 4. Structured result return + output_files = [str(outfile)] if outfile else [] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/app/augustus_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/app/augustus_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f351cbde0ade42e095b4f9d6ff22291427f602 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/app/augustus_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_augustus/app/augustus_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_augustus' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..96daa1843cc7203f8a7a8124eaf3c24a918f5aa7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-augustus: + build: . + image: mcp-augustus:latest + container_name: mcp-augustus + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=augustus + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb14a584251a561e179beb4b9f7b966a7c3ea338 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - augustus + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_augustus/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e5911ad2d88b853011ea7cd0ab63108fd1b5fad0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bactopia via conda (e.g., from bioconda) +RUN conda install -c bioconda bactopia -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bactopia_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bactopia_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bactopia_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/__pycache__/bactopia_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/__pycache__/bactopia_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06994ba47a8a71f35230fa45590af5f4bf77d3e8 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/__pycache__/bactopia_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/bactopia_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/bactopia_server.py new file mode 100644 index 0000000000000000000000000000000000000000..971de3a08a00dca462b8c6272eb5f04cdae609e7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/bactopia_server.py @@ -0,0 +1,287 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import os + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bactopia' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def bactopia_run( + sample: str, + outdir: str, + datasets: str, + r1: Optional[str] = None, + r2: Optional[str] = None, + se: Optional[str] = None, + fastqs: Optional[str] = None, + accession: Optional[str] = None, + accessions: Optional[str] = None, + profile: str = "conda", + cpus: int = 2, + max_memory: int = 8, + resume: bool = False, +) -> dict: + """ + Run the main Bactopia analysis pipeline for a bacterial genome. + + Args: + sample: Name of the sample. + outdir: Directory to store output results. + datasets: Path to the Bactopia datasets directory. + r1: Path to forward reads (Paired-end). + r2: Path to reverse reads (Paired-end). + se: Path to single-end reads. + fastqs: Path to a FOFN (file-of-filenames) for multiple samples. + accession: A single ENA/SRA accession (e.g., SRX000000). + accessions: A file containing a list of ENA/SRA accessions. + profile: Nextflow profile to use (e.g., conda, docker, singularity). + cpus: Number of CPUs to allocate. + max_memory: Maximum memory in GB to allocate. + resume: Whether to resume a previous run. + """ + # Input validation + out_path = Path(outdir) + ds_path = Path(datasets) + + if not ds_path.exists(): + return {"error": f"Datasets directory not found at {datasets}"} + + cmd = ["bactopia", "--sample", sample, "--outdir", str(out_path), "--datasets", str(ds_path)] + + # Input source logic + if r1 and r2: + if not Path(r1).exists() or not Path(r2).exists(): + return {"error": "R1 or R2 file does not exist"} + cmd += ["--R1", r1, "--R2", r2] + elif se: + if not Path(se).exists(): + return {"error": "Single-end file does not exist"} + cmd += ["--SE", se] + elif fastqs: + if not Path(fastqs).exists(): + return {"error": "Fastqs list file does not exist"} + cmd += ["--fastqs", fastqs] + elif accession: + cmd += ["--accession", accession] + elif accessions: + if not Path(accessions).exists(): + return {"error": "Accessions list file does not exist"} + cmd += ["--accessions", accessions] + else: + return {"error": "No input source provided (R1/R2, SE, fastqs, accession, or accessions required)"} + + # Performance and Nextflow options + cmd += ["-profile", profile] + cmd += ["--max_cpus", str(cpus)] + cmd += ["--max_memory", f"{max_memory}.GB"] + + if resume: + cmd.append("-resume") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(out_path.absolute()) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def bactopia_prepare( + path: str, + recursive: bool = False, + extension: str = ".fastq.gz", + output_file: Optional[str] = None +) -> dict: + """ + Prepare a FASTQ list (FOFN) for Bactopia from a directory of sequencing files. + + Args: + path: Directory containing FASTQ files. + recursive: Search for FASTQs in subdirectories. + extension: File extension to look for. + output_file: Optional path to save the generated list. + """ + input_path = Path(path) + if not input_path.is_dir(): + return {"error": f"Path {path} is not a directory"} + + cmd = ["bactopia", "prepare", str(input_path), "--extension", extension] + if recursive: + cmd.append("--recursive") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_file: + out_p = Path(output_file) + out_p.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "File list generated and saved.", + "output_file": str(out_p.absolute()) + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def bactopia_search( + query: str, + limit: int = 10, + output_file: Optional[str] = None +) -> dict: + """ + Search for bacterial genome accessions in ENA/SRA. + + Args: + query: Search query (e.g., "Staphylococcus aureus"). + limit: Maximum number of results to return. + output_file: Optional path to save the accession list. + """ + cmd = ["bactopia", "search", query, "--limit", str(limit)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_file: + out_p = Path(output_file) + out_p.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": f"Search results saved to {output_file}", + "output_file": str(out_p.absolute()) + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def bactopia_datasets( + outdir: str, + species: Optional[str] = None, + include_genus: bool = False, + limit: int = 100 +) -> dict: + """ + Download and setup Bactopia datasets/databases. + + Args: + outdir: Directory to save the datasets. + species: Optional species name to download specific datasets (e.g., "Salmonella enterica"). + include_genus: Include genus-level datasets. + limit: Limit the number of genomes used for building datasets. + """ + out_path = Path(outdir) + cmd = ["bactopia", "datasets", "--outdir", str(out_path)] + + if species: + cmd += ["--species", species] + if include_genus: + cmd.append("--include_genus") + cmd += ["--limit", str(limit)] + + try: + # This can be a long-running process + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "datasets_path": str(out_path.absolute()) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def bactopia_tool( + tool_name: str, + bactopia_dir: str, + outdir: str, + profile: str = "conda", + cpus: int = 2, + extra_params: Optional[List[str]] = None +) -> dict: + """ + Run a Bactopia Tool (comparative analysis) on existing Bactopia outputs. + Common tools include: pangenome, roary, iqtree, pirate, summary, etc. + + Args: + tool_name: Name of the Bactopia Tool to run. + bactopia_dir: Directory containing previous Bactopia results. + outdir: Directory to store tool results. + profile: Nextflow profile to use. + cpus: Number of CPUs to allocate. + extra_params: List of additional command line arguments for the specific tool. + """ + b_path = Path(bactopia_dir) + o_path = Path(outdir) + + if not b_path.exists(): + return {"error": f"Bactopia results directory not found at {bactopia_dir}"} + + cmd = [ + "bactopia", tool_name, + "--bactopia", str(b_path), + "--outdir", str(o_path), + "-profile", profile, + "--max_cpus", str(cpus) + ] + + if extra_params: + cmd.extend(extra_params) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(o_path.absolute()) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/bactopia_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/bactopia_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..87fb3f1d46ef12075757bda1020e679c4ae91687 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/bactopia_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/app/bactopia_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bactopia' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a04d950e41fdad191ac66dc0500c2e96c5f67b4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bactopia: + build: . + image: mcp-bactopia:latest + container_name: mcp-bactopia + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bactopia + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9ca9e2ebbc38669cf74f285464c2bddc36a6ebe0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bactopia + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bactopia/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c3ee4e16c686152423e96c94fbde9fd5e62b1bfc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bcbio-nextgen via conda (e.g., from bioconda) +RUN conda install -c bioconda bcbio-nextgen -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bcbio-nextgen_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bcbio-nextgen_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bcbio-nextgen_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/app/__pycache__/bcbio-nextgen_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/app/__pycache__/bcbio-nextgen_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f51c028fd82dad9eb2d323113a402cf9786efb65 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/app/__pycache__/bcbio-nextgen_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/app/bcbio-nextgen_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/app/bcbio-nextgen_server.py new file mode 100644 index 0000000000000000000000000000000000000000..04d982a6ae846a6ec7eb6627779937a967d4b2ec --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/app/bcbio-nextgen_server.py @@ -0,0 +1,276 @@ +from typing import List, Optional, Dict, Any +import subprocess +from pathlib import Path +import os + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bcbio_nextgen' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def bcbio_nextgen_run( + config_file: str, + num_cores: int = 1, + parallel_type: str = "local", + scheduler: Optional[str] = None, + queue: Optional[str] = None, + resources: Optional[str] = None, + tag: Optional[str] = None, + workdir: Optional[str] = None, + timeout: int = 15, + retries: int = 0, +) -> Dict[str, Any]: + """ + Run a bcbio-nextgen analysis pipeline using a provided configuration file. + + Args: + config_file: Path to the YAML configuration file defining the analysis. + num_cores: Number of local cores to use for parallel execution. + parallel_type: Type of parallel execution (local, ipython, cluster, etc.). + scheduler: Scheduler for cluster execution (e.g., sge, slurm, torque, pbspro, lsf). + queue: Queue to submit jobs to on a cluster. + resources: Specific resource requirements for the scheduler (e.g., 'mem=16,vmem=20'). + tag: Optional tag to identify this specific run. + workdir: Directory to use for processing (defaults to current directory). + timeout: Time in minutes to wait for ipython cluster startup. + retries: Number of times to retry failed steps. + """ + config_path = Path(config_file) + if not config_path.exists(): + return {"error": f"Configuration file not found: {config_file}"} + + cmd = ["bcbio_nextgen.py", str(config_path.absolute())] + + cmd.extend(["-n", str(num_cores)]) + cmd.extend(["-t", parallel_type]) + + if scheduler: + cmd.extend(["-s", scheduler]) + if queue: + cmd.extend(["-q", queue]) + if resources: + cmd.extend(["-r", resources]) + if tag: + cmd.extend(["--tag", tag]) + if timeout != 15: + cmd.extend(["--timeout", str(timeout)]) + if retries > 0: + cmd.extend(["--retries", str(retries)]) + + # Handle working directory + original_dir = os.getcwd() + if workdir: + work_path = Path(workdir) + if not work_path.exists(): + work_path.mkdir(parents=True, exist_ok=True) + os.chdir(work_path) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + finally: + os.chdir(original_dir) + +@mcp.tool() +def bcbio_nextgen_template( + template_name: str, + metadata_csv: str, + input_files: List[str], + out_dir: Optional[str] = None, +) -> Dict[str, Any]: + """ + Create a bcbio-nextgen processing description from a template and input files. + + Args: + template_name: Name of the template to use (e.g., 'freebayes-variant', 'gatk-variant'). + metadata_csv: Path to a CSV file containing sample metadata. + input_files: List of paths to input BAM or FASTQ files. + out_dir: Directory to write the generated configuration (defaults to current directory). + """ + metadata_path = Path(metadata_csv) + if not metadata_path.exists(): + return {"error": f"Metadata file not found: {metadata_csv}"} + + # Validate input files + valid_inputs = [] + for f in input_files: + p = Path(f) + if p.exists(): + valid_inputs.append(str(p.absolute())) + else: + return {"error": f"Input file not found: {f}"} + + cmd = ["bcbio_nextgen.py", "-w", "template", template_name, str(metadata_path.absolute())] + cmd.extend(valid_inputs) + + # Handle output directory + original_dir = os.getcwd() + if out_dir: + out_path = Path(out_dir) + if not out_path.exists(): + out_path.mkdir(parents=True, exist_ok=True) + os.chdir(out_path) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success", + "info": "Configuration files generated in the output directory." + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + finally: + os.chdir(original_dir) + +@mcp.tool() +def bcbio_nextgen_upgrade( + tooldir: Optional[str] = None, + tools: bool = False, + data: bool = False, + genomes: Optional[List[str]] = None, + aligners: Optional[List[str]] = None, + cores: int = 1, +) -> Dict[str, Any]: + """ + Upgrade bcbio-nextgen software, third-party tools, or genome data. + + Args: + tooldir: Directory where tools are installed. + tools: If True, upgrade third-party software tools. + data: If True, upgrade/install genome data. + genomes: List of genome builds to install/upgrade (e.g., ['hg38', 'mm10']). + aligners: List of aligners to install data for (e.g., ['bwa', 'bowtie2']). + cores: Number of cores to use for data downloads and indexing. + """ + cmd = ["bcbio_nextgen.py", "upgrade"] + + if tooldir: + cmd.extend(["--tooldir", tooldir]) + if tools: + cmd.append("--tools") + if data: + cmd.append("--data") + + if genomes: + for g in genomes: + cmd.extend(["--genomes", g]) + + if aligners: + for a in aligners: + cmd.extend(["--aligners", a]) + + cmd.extend(["--cores", str(cores)]) + + try: + # Upgrades can take a long time, but we capture output + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def bcbio_nextgen_install( + install_path: str, + tooldir: str, + genomes: List[str], + aligners: List[str], + nodata: bool = False, + isolate: bool = False, +) -> Dict[str, Any]: + """ + Run the bcbio-nextgen installer script to set up the environment. + + Args: + install_path: Path to install bcbio-nextgen data and code. + tooldir: Path to install third-party software tools. + genomes: List of genome builds to install (e.g., ['hg38']). + aligners: List of aligners to prepare (e.g., ['bwa']). + nodata: If True, do not install genome data. + isolate: If True, install into an isolated environment. + """ + # Note: This assumes bcbio_nextgen_install.py is in the PATH or current directory + # In a real environment, users might need to download it first. + cmd = ["python", "bcbio_nextgen_install.py", install_path, "--tooldir=" + tooldir] + + for g in genomes: + cmd.extend(["--genomes", g]) + for a in aligners: + cmd.extend(["--aligners", a]) + + if nodata: + cmd.append("--nodata") + if isolate: + cmd.append("--isolate") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def bcbio_nextgen_version() -> Dict[str, Any]: + """ + Check the installed version of bcbio-nextgen. + """ + cmd = ["bcbio_nextgen.py", "--version"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "status": "failed" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/app/bcbio-nextgen_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/app/bcbio-nextgen_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cd2f4fe66afb0c59d2e4b1cf35cda65d7b7231c4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/app/bcbio-nextgen_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/app/bcbio-nextgen_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bcbio_nextgen' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..67a946efd6f123ca05819a74532a97d4f84baeee --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bcbio-nextgen: + build: . + image: mcp-bcbio-nextgen:latest + container_name: mcp-bcbio-nextgen + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bcbio-nextgen + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0fe9688f1cc6b35c7e0b9386c01415dc1e8fc3b1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bcbio-nextgen + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bcbio-nextgen/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..565ae50155b78f1d8b26241027d43a56a2b50f5a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bedops via conda (e.g., from bioconda) +RUN conda install -c bioconda bedops -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bedops_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bedops_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bedops_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/__pycache__/bedops_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/__pycache__/bedops_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..faca0a30995d9bf86d6f3e19101762cd249a9e0f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/__pycache__/bedops_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/bedops_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/bedops_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cd5c44bdbd40cb33dfe8f8d4ed493163ec742e35 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/bedops_server.py @@ -0,0 +1,827 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP decorator is commented out as per instructions +# import mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bedops' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def bedops_complement( + files: List[Path], + chop_to_limits: bool = False, + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Computes the complement of one or more BED files. + + This corresponds to the `bedops -c` or `bedops --complement` operation. + It finds the regions within chromosome boundaries that are not covered by + any intervals in the input file(s). + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + chop_to_limits: If True, chop complementary regions to chromosome limits + defined by the first input file (-L flag). + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the complement operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--complement") + if chop_to_limits: + cmd.append("-L") + + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops complement failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_difference( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Computes the difference between a reference BED file and one or more other BED files. + + This corresponds to the `bedops -d` or `bedops --difference` operation. + It returns regions from the first (reference) file that do not overlap + with any regions in the subsequent files. + + Args: + files: A list of two or more input BED/Starch files. The first file is + the reference. All files must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files (a reference and one other) must be provided for the difference operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--difference") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops difference failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_element_of( + files: List[Path], + overlap_criterion: str = "100%", + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Finds elements in the reference file that overlap other files by a specified amount. + + This corresponds to the `bedops -e` or `bedops --element-of` operation. + It returns elements from the first (reference) file that overlap elements + in any of the other files by at least the specified amount. + + Args: + files: A list of two or more input BED/Starch files. The first file is + the reference. All files must be sorted. + overlap_criterion: The required overlap, as base pairs (e.g., '1') or + percentage (e.g., '50%'). Defaults to '100%'. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' or 'S' format. The first (reference) + file is NOT padded with this operation. + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files (a reference and one other) must be provided for the element-of operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.extend(["--element-of", overlap_criterion]) + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops element-of failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_intersect( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Computes the intersection of two or more BED files. + + This corresponds to the `bedops -i` or `bedops --intersect` operation. + It returns regions that are common to all input files. + + Args: + files: A list of two or more input BED/Starch files. All files must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files must be provided for the intersect operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--intersect") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops intersect failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_merge( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Merges overlapping regions from one or more BED files. + + This corresponds to the `bedops -m` or `bedops --merge` operation. + It combines overlapping or adjacent intervals into a single, larger interval. + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the merge operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--merge") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops merge failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_not_element_of( + files: List[Path], + overlap_criterion: str = "100%", + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Finds elements in the reference file that DO NOT overlap other files by a specified amount. + + This corresponds to the `bedops -n` or `bedops --not-element-of` operation. + It is the inverse of the `element-of` operation. + + Args: + files: A list of two or more input BED/Starch files. The first file is + the reference. All files must be sorted. + overlap_criterion: The required overlap, as base pairs (e.g., '1') or + percentage (e.g., '50%'). Defaults to '100%'. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' or 'S' format. The first (reference) + file is NOT padded with this operation. + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files (a reference and one other) must be provided for the not-element-of operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.extend(["--not-element-of", overlap_criterion]) + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops not-element-of failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_partition( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Partitions the input BED file(s) into disjoint segments. + + This corresponds to the `bedops -p` or `bedops --partition` operation. + It breaks the input regions into non-overlapping segments, reporting each + new segment and which input files it came from. + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the partition operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--partition") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops partition failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_symmdiff( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Computes the symmetric difference of two or more BED files. + + This corresponds to the `bedops -s` or `bedops --symmdiff` operation. + It returns regions that are unique to any of the input files (i.e., not + present in their intersection). + + Args: + files: A list of two or more input BED/Starch files. All files must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files must be provided for the symmetric difference operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--symmdiff") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops symmdiff failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_everything( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Returns the union of all elements from input files without merging. + + This corresponds to the `bedops -u` or `bedops --everything` operation. + It effectively concatenates the input files while maintaining sort order + and preserving all original columns. + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the everything operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--everything") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops everything failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_chop( + files: List[Path], + bp: int = 1, + stagger: Optional[int] = None, + exclusive_chop: bool = False, + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Chops elements into fixed-size, potentially staggered sub-elements. + + This corresponds to the `bedops -w` or `bedops --chop` operation. + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + bp: The size in base pairs of each chopped element. Defaults to 1. + stagger: The stagger distance in nucleotides. If not set, no staggering is done. + exclusive_chop: If True, removes single-base elements that can result + from chopping (-x flag). + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the chop operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.extend(["--chop", str(bp)]) + if stagger is not None: + cmd.extend(["--stagger", str(stagger)]) + if exclusive_chop: + cmd.append("-x") + + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops chop failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/bedops_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/bedops_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..aa28e244d9d8ba5d3ab5d3ddf8565dd085fa8a85 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/bedops_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bedops' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..91a34e4d62a9ab6c006b5be2741a5942d0c66a8b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bedops: + build: . + image: mcp-bedops:latest + container_name: mcp-bedops + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bedops + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..11a313e56d9e8c3b984f027df03882228599fd59 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bedops + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedops/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d47f17c1c804642a5cab7ab14eee1ff11bbd3517 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install biobambam via conda (e.g., from bioconda) +RUN conda install -c bioconda biobambam -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/biobambam_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/biobambam_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/biobambam_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/app/__pycache__/biobambam_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/app/__pycache__/biobambam_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75c86fba09c25931446601430c1f0a1f8d39d546 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/app/__pycache__/biobambam_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/app/biobambam_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/app/biobambam_server.py new file mode 100644 index 0000000000000000000000000000000000000000..55e0b983a50a27522fe4a9a31e8d109d742535cf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/app/biobambam_server.py @@ -0,0 +1,497 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_biobambam' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def bamsort( + input_file: str, + output_file: str, + memory_limit: str = "1G", + tmp_prefix: Optional[str] = None, + create_index: bool = False, + index_filename: Optional[str] = None, + sort_order: str = "coordinate", + threads: int = 1, + compression_level: int = 1, + recalculate_md_nm: bool = False, + reference_file: Optional[str] = None, + verbose: bool = False, +) -> dict: + """ + Sorts BAM files by coordinate or query name using bamsort. + + Args: + input_file: Path to the input BAM file. + output_file: Path for the sorted output BAM file. + memory_limit: Main memory to use (e.g., '1G', '512M'). + tmp_prefix: Temporary file prefix. + create_index: Whether to create an index for the output BAM file. + index_filename: Name for the index file. + sort_order: Sort order ('coordinate' or 'queryname'). + threads: Number of threads to use. + compression_level: Compression level (0-9). + recalculate_md_nm: Recalculate MD and NM tags (requires reference). + reference_file: Reference FASTA file for MD/NM recalculation. + verbose: Enable verbose output. + """ + in_path = Path(input_file) + out_path = Path(output_file) + + if not in_path.exists(): + return {"error": f"Input file {input_file} does not exist"} + if sort_order not in ["coordinate", "queryname"]: + return {"error": "sort_order must be 'coordinate' or 'queryname'"} + if not (0 <= compression_level <= 9): + return {"error": "compression_level must be between 0 and 9"} + + cmd = ["bamsort", f"I={input_file}", f"O={output_file}"] + cmd.append(f"M={memory_limit}") + cmd.append(f"sortorder={sort_order}") + cmd.append(f"threads={threads}") + cmd.append(f"level={compression_level}") + + if tmp_prefix: cmd.append(f"T={tmp_prefix}") + if create_index: cmd.append("index=1") + if index_filename: cmd.append(f"indexfilename={index_filename}") + if recalculate_md_nm: + if not reference_file: + return {"error": "reference_file is required for recalculate_md_nm"} + cmd.append("calmd=1") + cmd.append(f"reference={reference_file}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd), "return_code": e.returncode} + +@mcp.tool() +def bammarkduplicates( + input_file: str, + output_file: str, + metrics_file: Optional[str] = None, + tmp_prefix: Optional[str] = None, + create_index: bool = False, + index_filename: Optional[str] = None, + remove_duplicates: bool = False, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Marks or removes duplicate reads in a coordinate-sorted BAM file. + + Args: + input_file: Input BAM file (must be coordinate sorted). + output_file: Output BAM file with duplicates marked. + metrics_file: Path for the output metrics file. + tmp_prefix: Temporary file prefix. + create_index: Create index for output BAM. + index_filename: Name for the index file. + remove_duplicates: Remove duplicate reads instead of marking. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bammarkduplicates", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + + if metrics_file: cmd.append(f"M={metrics_file}") + if tmp_prefix: cmd.append(f"T={tmp_prefix}") + if create_index: cmd.append("index=1") + if index_filename: cmd.append(f"indexfilename={index_filename}") + if remove_duplicates: cmd.append("rmdup=1") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + outputs = [output_file] + if metrics_file: outputs.append(metrics_file) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": outputs + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamsormadup( + input_file: str, + output_file: str, + tmp_prefix: Optional[str] = None, + memory_limit: str = "1G", + threads: int = 1, + compression_level: int = 1, + create_index: bool = False, + index_filename: Optional[str] = None, + remove_duplicates: bool = False, + verbose: bool = False, +) -> dict: + """ + Combined sorting and duplicate marking in a single pass. + + Args: + input_file: Input BAM file. + output_file: Output BAM file. + tmp_prefix: Temporary file prefix. + memory_limit: Memory limit. + threads: Number of threads. + compression_level: Compression level (0-9). + create_index: Create index for output. + index_filename: Index filename. + remove_duplicates: Remove duplicates. + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamsormadup", f"I={input_file}", f"O={output_file}"] + cmd.append(f"M={memory_limit}") + cmd.append(f"threads={threads}") + cmd.append(f"level={compression_level}") + + if tmp_prefix: cmd.append(f"T={tmp_prefix}") + if create_index: cmd.append("index=1") + if index_filename: cmd.append(f"indexfilename={index_filename}") + if remove_duplicates: cmd.append("rmdup=1") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamtofastq( + input_file: str, + fastq_1: str, + fastq_2: Optional[str] = None, + singles: Optional[str] = None, + orphans_1: Optional[str] = None, + orphans_2: Optional[str] = None, + collate: bool = False, + gzip: bool = False, + compression_level: int = 1, + reads_per_file: int = 0, + verbose: bool = False, +) -> dict: + """ + Converts BAM files to FASTQ format. + + Args: + input_file: Input BAM file. + fastq_1: Output FASTQ file (Read 1). + fastq_2: Output FASTQ file (Read 2). + singles: Output FASTQ for single-end reads. + orphans_1: Output FASTQ for orphan Read 1. + orphans_2: Output FASTQ for orphan Read 2. + collate: Collate reads by name before conversion. + gzip: Compress output with gzip. + compression_level: Gzip compression level (1-9). + reads_per_file: Split output into files with N reads (0 = no split). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamtofastq", f"filename={input_file}", f"F={fastq_1}"] + outputs = [fastq_1] + + if fastq_2: + cmd.append(f"F2={fastq_2}") + outputs.append(fastq_2) + if singles: + cmd.append(f"S={singles}") + outputs.append(singles) + if orphans_1: + cmd.append(f"O={orphans_1}") + outputs.append(orphans_1) + if orphans_2: + cmd.append(f"O2={orphans_2}") + outputs.append(orphans_2) + if collate: cmd.append("collate=1") + if gzip: cmd.append("gz=1") + if compression_level != 1: cmd.append(f"level={compression_level}") + if reads_per_file > 0: cmd.append(f"readsperfile={reads_per_file}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": outputs + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamcollate2( + input_file: str, + output_file: str, + tmp_prefix: Optional[str] = None, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Collates a BAM file by read name. + + Args: + input_file: Input BAM file. + output_file: Output collated BAM file. + tmp_prefix: Temporary file prefix. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamcollate2", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + if tmp_prefix: cmd.append(f"T={tmp_prefix}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamadapterclip( + input_file: str, + output_file: str, + threads: int = 1, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Clips adapter sequences from reads in a BAM file. + + Args: + input_file: Input BAM file. + output_file: Output clipped BAM file. + threads: Number of threads. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamadapterclip", f"I={input_file}", f"O={output_file}"] + cmd.append(f"threads={threads}") + cmd.append(f"level={compression_level}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamreset( + input_file: str, + output_file: str, + compression_level: int = 1, + reset_flags: bool = False, + verbose: bool = False, +) -> dict: + """ + Resets alignment information in a BAM file. + + Args: + input_file: Input BAM file. + output_file: Output reset BAM file. + compression_level: Compression level (0-9). + reset_flags: Reset flags to 0. + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamreset", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + if reset_flags: cmd.append("resetflags=1") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamchecksort( + input_file: str, + verbose: bool = False, +) -> dict: + """ + Checks if a BAM file is sorted. + + Args: + input_file: Input BAM file. + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamchecksort", f"I={input_file}"] + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "is_sorted": "sorted" in result.stdout.lower() or result.returncode == 0 + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd), "is_sorted": False} + +@mcp.tool() +def bamrecompress( + input_file: str, + output_file: str, + compression_level: int = 1, + threads: int = 1, + verbose: bool = False, +) -> dict: + """ + Recompresses a BAM file. + + Args: + input_file: Input BAM file. + output_file: Output recompressed BAM file. + compression_level: Compression level (0-9). + threads: Number of threads. + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamrecompress", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + cmd.append(f"threads={threads}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamfilterrg( + input_file: str, + output_file: str, + read_group: str, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Filters a BAM file by read group. + + Args: + input_file: Input BAM file. + output_file: Output filtered BAM file. + read_group: Read group ID to keep. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamfilterrg", f"I={input_file}", f"O={output_file}", f"rg={read_group}"] + cmd.append(f"level={compression_level}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamfillquery( + input_file: str, + output_file: str, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Fills query information in a BAM file. + + Args: + input_file: Input BAM file. + output_file: Output BAM file. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamfillquery", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8e560d0b9663f640ea501c160550b562e9866e2d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-biobambam: + build: . + image: mcp-biobambam:latest + container_name: mcp-biobambam + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=biobambam + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5f8302421154c86eee3b610322b5b4017bb7a7ae --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - biobambam + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biobambam/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f2d33b2efd16bce295e2841bac519b1b3633d42 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-affyio via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-affyio -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-affyio_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-affyio_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-affyio_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/__pycache__/bioconductor-affyio_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/__pycache__/bioconductor-affyio_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b25958990bdb849303bd7213bc9303cb1f9b731 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/__pycache__/bioconductor-affyio_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a112e2f88a04894436d2c0dab768f1c27c1d7002 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py @@ -0,0 +1,216 @@ +import subprocess +import json +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_affyio' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def affyio_read_celfile_header( + filename: str, + info: str = "full" +) -> Dict[str, Any]: + """ + Read the header information from an Affymetrix CEL file. + + Args: + filename: Path to the CEL file. + info: Level of information to extract ('full' or 'minimal'). + """ + file_path = Path(filename) + if not file_path.exists(): + return {"error": f"File not found: {filename}"} + + if info not in ["full", "minimal"]: + info = "full" + + # R script to extract header and convert to JSON + r_command = f""" + library(affyio) + library(jsonlite) + header <- read.celfile.header("{str(file_path)}", info="{info}") + cat(toJSON(header, auto_unbox = TRUE)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"read.celfile.header('{filename}')", + "header_data": json.loads(result.stdout), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + except json.JSONDecodeError: + return {"error": "Failed to parse R output", "raw_stdout": result.stdout} + +@mcp.tool() +def affyio_read_celfile( + filename: str, + output_csv: str, + intensity_only: bool = True +) -> Dict[str, Any]: + """ + Read an Affymetrix CEL file and export the intensity data to a CSV file. + + Args: + filename: Path to the CEL file. + output_csv: Path where the intensity data should be saved. + intensity_only: If True, only the intensity values are extracted. + """ + input_path = Path(filename) + output_path = Path(output_csv) + + if not input_path.exists(): + return {"error": f"Input file not found: {filename}"} + + intensity_val = "TRUE" if intensity_only else "FALSE" + + r_command = f""" + library(affyio) + data <- read.celfile("{str(input_path)}", intensity.only={intensity_val}) + # If intensity.only is TRUE, it returns a list with INTENSITY + # If FALSE, it returns a list with INTENSITY, MASKS, OUTLIERS + write.csv(data$INTENSITY, "{str(output_path)}") + """ + + try: + subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"read.celfile('{filename}')", + "status": "Success", + "output_file": str(output_path) + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stderr": e.stderr, + "stdout": e.stdout + } + +@mcp.tool() +def affyio_check_cdf_type( + filename: str +) -> Dict[str, Any]: + """ + Identify the type of an Affymetrix CDF file (e.g., text, binary, gzipped). + + Args: + filename: Path to the CDF file. + """ + file_path = Path(filename) + if not file_path.exists(): + return {"error": f"File not found: {filename}"} + + r_command = f""" + library(affyio) + type <- check.cdf.type("{str(file_path)}") + cat(type) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"check.cdf.type('{filename}')", + "cdf_type": result.stdout.strip(), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def affyio_read_cdffile_summary( + filename: str +) -> Dict[str, Any]: + """ + Read an Affymetrix CDF file and return a summary of its contents. + Note: Full CDF lists are extremely large; this tool returns structural metadata. + + Args: + filename: Path to the CDF file. + """ + file_path = Path(filename) + if not file_path.exists(): + return {"error": f"File not found: {filename}"} + + r_command = f""" + library(affyio) + library(jsonlite) + cdf_data <- read.cdffile.list("{str(file_path)}") + summary_info <- list( + filename = "{filename}", + num_probesets = length(cdf_data), + probeset_names = head(names(cdf_data), 10) + ) + cat(toJSON(summary_info, auto_unbox = TRUE)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"read.cdffile.list('{filename}')", + "summary": json.loads(result.stdout), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def affyio_get_package_version() -> Dict[str, Any]: + """ + Check the installed version of the affyio package and its dependencies. + """ + r_command = """ + library(affyio) + v <- as.character(packageVersion("affyio")) + cat(v) + """ + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "package": "affyio", + "version": result.stdout.strip(), + "r_version": subprocess.run(["Rscript", "--version"], capture_output=True, text=True).stderr.strip() + } + except subprocess.CalledProcessError as e: + return { + "error": "Could not determine package version. Ensure bioconductor-affyio is installed.", + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/bioconductor-affyio_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/bioconductor-affyio_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..75f4ae941515c6e589f889ff76ffc84a53e6e449 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/bioconductor-affyio_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_affyio' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ac239ca3a52d2c9c05317d88ee726fcd08573a94 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-affyio: + build: . + image: mcp-bioconductor-affyio:latest + container_name: mcp-bioconductor-affyio + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-affyio + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..486380658759a501811fc16c5f5101304cb08b26 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-affyio + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affyio/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8df3183e644dd3c5947b4c5585e2c942f6d7c80c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-annotate via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-annotate -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-annotate_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-annotate_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-annotate_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/app/__pycache__/bioconductor-annotate_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/app/__pycache__/bioconductor-annotate_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8d53accc655199c344c726554af23f3f9a1072a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/app/__pycache__/bioconductor-annotate_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e8aa22c0b818479e01d8ba4f0ce30f4cb61ba843 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py @@ -0,0 +1,141 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# The mcp.tool decorator is supplied by the MCP framework. +# It is aliased here for clarity and to allow for standalone code analysis. +class mcp: + """A dummy class to represent the MCP decorator for static analysis.""" + @staticmethod + def tool(func): + """A dummy decorator that returns the function unchanged.""" + return func + +@mcp.tool +def rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + vanilla: bool = False, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper for the Rscript interpreter, which is commonly + used to run bioinformatics scripts that rely on R packages from repositories + like CRAN or Bioconductor (e.g., for using bioconductor-annotate). + You must provide either a path to an R script file or a list of R expressions + to execute. + + Args: + script_file: Path to the R script file to be executed. + expressions: A list of R expressions to execute directly. Use this instead of script_file. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, enables verbose output, printing information on progress. + default_packages: A comma-separated string of package names to be loaded by default. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ. This provides a clean session. + If True, the individual flags (save, restore, etc.) are ignored. + save: If True, the workspace will be saved at the end of the session. Ignored if vanilla is True. + no_environ: If True, site and user environment files will not be read. Ignored if vanilla is True. + no_site_file: If True, the site-wide Rprofile will not be read. Ignored if vanilla is True. + no_init_file: If True, the user's R profile will not be read. Ignored if vanilla is True. + restore: If True, previously saved objects will be restored at startup. Ignored if vanilla is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not script_file and not expressions: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + if script_file and expressions: + raise ValueError("Cannot provide both 'script_file' and 'expressions' simultaneously.") + + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + cmd = ["Rscript"] + + if verbose: + cmd.append("--verbose") + + if default_packages: + cmd.append(f"--default-packages={default_packages}") + + if vanilla: + cmd.append("--vanilla") + else: + # These options are processed only if --vanilla is not used + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + + # Add script file or expressions to execute + if script_file: + cmd.append(str(script_file)) + elif expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + # Add trailing arguments for the R script + if script_args: + cmd.extend(script_args) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + logging.error("Rscript executable not found.") + return { + "error": "Rscript not found. Please ensure R is installed and in your PATH.", + "command_executed": command_executed, + "stdout": "", + "stderr": "Rscript executable not found.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the R script exits with a non-zero status code + logging.error(f"Rscript execution failed with exit code {e.returncode}") + return { + "error": f"Rscript execution failed with exit code {e.returncode}.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 4. Structured Result Return + # This wrapper cannot reliably determine output files generated by the user's script. + # The user is responsible for knowing and handling the script's output. + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..918995248372ba964c86e8818f1ecdaade4bf02c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_annotate' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5020838deb35bbae2bcb064ef99231a9f153e504 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-annotate: + build: . + image: mcp-bioconductor-annotate:latest + container_name: mcp-bioconductor-annotate + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-annotate + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca6f7fedcb6d13738028109983815bb7e6c4b8fd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-annotate + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotate/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1bfc36fcdba582407198bff96211ec04fd0c3b4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-banksy via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-banksy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-banksy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-banksy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-banksy_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/__pycache__/bioconductor-banksy_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/__pycache__/bioconductor-banksy_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3625a15a6051280903269963fd24bce3d1d49e58 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/__pycache__/bioconductor-banksy_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..abf9e0c8546a4f944ade77f3c371613f842c5032 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_server.py @@ -0,0 +1,667 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Note: The @mcp.tool() decorator is assumed to be available in the environment +# where this code will be run, as per the instructions "NO NEED to import mcp". + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_banksy' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def banksy_init_object( + input_seurat_rdata_path: Path, + output_banksy_rdata_path: Path, + assay: str = "Spatial", + verbose: bool = True, +) -> Dict[str, Any]: + """ + Initializes a BanksyObject from an existing Seurat object. + + This tool takes an RData file containing a Seurat object, converts it + into a BanksyObject, and saves the new BanksyObject to an RData file. + This is often the first step before running the BANKSY algorithm. + + Requires R and the 'banksy' and 'Seurat' R packages to be installed + and accessible in the environment. + + Args: + input_seurat_rdata_path: Path to the input .RData file containing a Seurat object. + output_banksy_rdata_path: Path where the new BanksyObject will be saved as an .RData file. + assay: Name of the assay in the Seurat object to use for spatial data. + verbose: If TRUE, print messages during execution. + + Returns: + A dictionary containing execution details: + - command_executed: The Rscript command and generated R script path. + - stdout: Standard output from the Rscript execution. + - stderr: Standard error from the Rscript execution. + - output_files: A list of paths to generated output files. + """ + # 1. Input validation + if not input_seurat_rdata_path.exists(): + raise FileNotFoundError(f"Input Seurat RData file not found: {input_seurat_rdata_path}") + if not input_seurat_rdata_path.is_file(): + raise ValueError(f"Input Seurat RData path is not a file: {input_seurat_rdata_path}") + if output_banksy_rdata_path.suffix.lower() != ".rdata": + raise ValueError(f"Output RData file must have a .RData extension: {output_banksy_rdata_path}") + if not assay: + raise ValueError("Assay name cannot be empty.") + + # Ensure output directory exists + output_banksy_rdata_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate R script content + r_script_content = f""" + # Load required packages + library(Seurat) + library(banksy) + + # Define input and output paths + input_obj_path <- "{input_seurat_rdata_path.as_posix()}" + output_obj_path <- "{output_banksy_rdata_path.as_posix()}" + + # Check if input file exists + if (!file.exists(input_obj_path)) {{ + stop(paste("Input RData file not found:", input_obj_path)) + }} + + # Load the object from RData. This approach handles cases where the object + # name inside the RData file is not known beforehand. + loaded_env <- new.env() + load(input_obj_path, envir = loaded_env) + + seurat_obj <- NULL + for (var_name in ls(loaded_env)) {{ + candidate <- get(var_name, envir = loaded_env) + if (inherits(candidate, "Seurat")) {{ + seurat_obj <- candidate + break + }} + }} + + if (is.null(seurat_obj)) {{ + stop("No Seurat object found in the input RData file.") + }} + + message("Initializing BanksyObject from Seurat object with parameters:") + message(paste(" assay:", "{assay}")) + message(paste(" verbose:", {str(verbose).upper()})) + + # Create BanksyObject + banksy_obj <- BanksyObject( + seurat_obj, + assay = "{assay}", + verbose = {str(verbose).upper()} + ) + + # Save the new BanksyObject. Renaming to 'obj' for consistency with other banksy tools. + obj <- banksy_obj + save(obj, file = output_obj_path) + + message(paste("BanksyObject saved to:", output_obj_path)) + """ + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + # 3. Subprocess execution + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + env=os.environ # Pass current environment to Rscript + ) + + stdout = process.stdout + stderr = process.stderr + + # 4. Error handling: Check for R-specific errors in stderr + if "Error" in stderr or "stop(" in stderr: + raise RuntimeError(f"R script execution failed. Stderr: {stderr}") + + if not output_banksy_rdata_path.exists(): + raise RuntimeError(f"Output file was not created by R script: {output_banksy_rdata_path}") + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_banksy_rdata_path)], + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Is R installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up temporary R script + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) + + +@mcp.tool() +def banksy_run_banksy( + input_rdata_path: Path, + output_rdata_path: Path, + k_neighbours: int = 10, + lambda_param: float = 0.1, # Renamed from 'lambda' to avoid Python keyword conflict + resolution: float = 0.8, + n_components: int = 2, + n_cores: int = 1, + verbose: bool = True, + seed: int = 123, +) -> Dict[str, Any]: + """ + Runs the core BANKSY algorithm on a Seurat or BanksyObject. + + This tool takes an RData file containing a Seurat or BanksyObject, + applies the BANKSY algorithm for spatial transcriptomics analysis, + and saves the updated object to a new RData file. + + Requires R and the 'banksy', 'Seurat', and 'future' R packages to be installed + and accessible in the environment. + + Args: + input_rdata_path: Path to the input .RData file containing a Seurat or BanksyObject. + output_rdata_path: Path where the updated Seurat/BanksyObject will be saved as an .RData file. + k_neighbours: Number of neighbours for spatial graph construction. + lambda_param: Weight of spatial information (lambda parameter). + resolution: Resolution parameter for clustering. + n_components: Number of components for dimensionality reduction (e.g., UMAP/tSNE). + n_cores: Number of cores to use for parallel processing. + verbose: If TRUE, print messages during execution. + seed: Random seed for reproducibility. + + Returns: + A dictionary containing execution details: + - command_executed: The Rscript command and generated R script path. + - stdout: Standard output from the Rscript execution. + - stderr: Standard error from the Rscript execution. + - output_files: A list of paths to generated output files. + """ + # 1. Input validation + if not input_rdata_path.exists(): + raise FileNotFoundError(f"Input RData file not found: {input_rdata_path}") + if not input_rdata_path.is_file(): + raise ValueError(f"Input RData path is not a file: {input_rdata_path}") + if output_rdata_path.suffix.lower() != ".rdata": + raise ValueError(f"Output RData file must have a .RData extension: {output_rdata_path}") + if k_neighbours <= 0: + raise ValueError("k_neighbours must be a positive integer.") + if not (0 <= lambda_param <= 1): + raise ValueError("lambda_param must be between 0 and 1.") + if resolution <= 0: + raise ValueError("resolution must be a positive float.") + if n_components <= 0: + raise ValueError("n_components must be a positive integer.") + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + + # Ensure output directory exists + output_rdata_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate R script content + r_script_content = f""" + # Load required packages + library(Seurat) + library(banksy) + library(future) # For parallel processing + + # Set up parallel processing if n_cores > 1 + if ({n_cores} > 1) {{ + plan("multisession", workers = {n_cores}) + }} else {{ + plan("sequential") + }} + + # Set random seed for reproducibility + set.seed({seed}) + + # Define input and output paths + input_obj_path <- "{input_rdata_path.as_posix()}" + output_obj_path <- "{output_rdata_path.as_posix()}" + + # Check if input file exists + if (!file.exists(input_obj_path)) {{ + stop(paste("Input RData file not found:", input_obj_path)) + }} + + # Load the object + loaded_env <- new.env() + load(input_obj_path, envir = loaded_env) + + obj <- NULL + for (var_name in ls(loaded_env)) {{ + candidate <- get(var_name, envir = loaded_env) + if (inherits(candidate, "Seurat") || inherits(candidate, "BanksyObject")) {{ + obj <- candidate + break + }} + }} + + if (is.null(obj)) {{ + stop("No Seurat or BanksyObject found in the input RData file.") + }} + + message("Running banksy with parameters:") + message(paste(" k_neighbours:", {k_neighbours})) + message(paste(" lambda:", {lambda_param})) + message(paste(" resolution:", {resolution})) + message(paste(" n_components:", {n_components})) + message(paste(" n_cores:", {n_cores})) + message(paste(" verbose:", {str(verbose).upper()})) + message(paste(" seed:", {seed})) + + # Run BANKSY + obj <- runBanksy( + object = obj, + k_neighbours = {k_neighbours}, + lambda = {lambda_param}, + resolution = {resolution}, + n_components = {n_components}, + verbose = {str(verbose).upper()} + ) + + # Save the updated object + save(obj, file = output_obj_path) + + message(paste("Updated object saved to:", output_obj_path)) + """ + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + # 3. Subprocess execution + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + env=os.environ + ) + + stdout = process.stdout + stderr = process.stderr + + # 4. Error handling: Check for R-specific errors in stderr + if "Error" in stderr or "stop(" in stderr: + raise RuntimeError(f"R script execution failed. Stderr: {stderr}") + + if not output_rdata_path.exists(): + raise RuntimeError(f"Output file was not created by R script: {output_rdata_path}") + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rdata_path)], + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Is R installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up temporary R script + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) + + +@mcp.tool() +def banksy_cluster_banksy( + input_rdata_path: Path, + output_rdata_path: Path, + resolution: float = 0.8, + method: str = "leiden", + verbose: bool = True, + seed: int = 123, +) -> Dict[str, Any]: + """ + Performs clustering on a BanksyObject or Seurat object after BANKSY analysis. + + This tool takes an RData file containing a Seurat or BanksyObject (typically + after `runBanksy`), performs clustering using the specified method and resolution, + and saves the updated object to a new RData file. + + Requires R and the 'banksy' and 'Seurat' R packages to be installed + and accessible in the environment. + + Args: + input_rdata_path: Path to the input .RData file containing a Seurat or BanksyObject. + output_rdata_path: Path where the updated Seurat/BanksyObject will be saved as an .RData file. + resolution: Resolution parameter for clustering. + method: Clustering method to use (e.g., "leiden", "louvain"). + verbose: If TRUE, print messages during execution. + seed: Random seed for reproducibility. + + Returns: + A dictionary containing execution details: + - command_executed: The Rscript command and generated R script path. + - stdout: Standard output from the Rscript execution. + - stderr: Standard error from the Rscript execution. + - output_files: A list of paths to generated output files. + """ + # 1. Input validation + if not input_rdata_path.exists(): + raise FileNotFoundError(f"Input RData file not found: {input_rdata_path}") + if not input_rdata_path.is_file(): + raise ValueError(f"Input RData path is not a file: {input_rdata_path}") + if output_rdata_path.suffix.lower() != ".rdata": + raise ValueError(f"Output RData file must have a .RData extension: {output_rdata_path}") + if resolution <= 0: + raise ValueError("resolution must be a positive float.") + if method not in ["leiden", "louvain"]: + raise ValueError(f"Unsupported clustering method: {method}. Choose from 'leiden', 'louvain'.") + + # Ensure output directory exists + output_rdata_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate R script content + r_script_content = f""" + # Load required packages + library(Seurat) + library(banksy) + + # Set random seed for reproducibility + set.seed({seed}) + + # Define input and output paths + input_obj_path <- "{input_rdata_path.as_posix()}" + output_obj_path <- "{output_rdata_path.as_posix()}" + + # Check if input file exists + if (!file.exists(input_obj_path)) {{ + stop(paste("Input RData file not found:", input_obj_path)) + }} + + # Load the object + loaded_env <- new.env() + load(input_obj_path, envir = loaded_env) + + obj <- NULL + for (var_name in ls(loaded_env)) {{ + candidate <- get(var_name, envir = loaded_env) + if (inherits(candidate, "Seurat") || inherits(candidate, "BanksyObject")) {{ + obj <- candidate + break + }} + }} + + if (is.null(obj)) {{ + stop("No Seurat or BanksyObject found in the input RData file.") + }} + + message("Clustering banksy object with parameters:") + message(paste(" resolution:", {resolution})) + message(paste(" method:", "{method}")) + message(paste(" verbose:", {str(verbose).upper()})) + message(paste(" seed:", {seed})) + + # Cluster BANKSY object + obj <- clusterBanksy( + object = obj, + resolution = {resolution}, + method = "{method}", + verbose = {str(verbose).upper()} + ) + + # Save the updated object + save(obj, file = output_obj_path) + + message(paste("Updated object saved to:", output_obj_path)) + """ + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + # 3. Subprocess execution + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + env=os.environ + ) + + stdout = process.stdout + stderr = process.stderr + + # 4. Error handling: Check for R-specific errors in stderr + if "Error" in stderr or "stop(" in stderr: + raise RuntimeError(f"R script execution failed. Stderr: {stderr}") + + if not output_rdata_path.exists(): + raise RuntimeError(f"Output file was not created by R script: {output_rdata_path}") + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rdata_path)], + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Is R installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up temporary R script + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) + + +@mcp.tool() +def banksy_spatial_dim_plot( + input_rdata_path: Path, + output_plot_path: Path, + reduction: str = "banksy", + group_by: str = "banksy_clusters", + label: bool = True, + pt_size: float = 1.5, + verbose: bool = True, + width: float = 7.0, + height: float = 7.0, + units: str = "in", + dpi: int = 300, +) -> Dict[str, Any]: + """ + Generates a spatial dimensionality plot for a BanksyObject. + + This tool takes an RData file containing a BanksyObject (typically after + `runBanksy` and `clusterBanksy`), generates a spatial plot, and saves it + to an image file (e.g., PNG, PDF). + + Requires R and the 'banksy', 'Seurat', and 'ggplot2' R packages to be installed + and accessible in the environment. + + Args: + input_rdata_path: Path to the input .RData file containing a BanksyObject. + output_plot_path: Path where the plot will be saved (e.g., .png, .pdf, .jpeg). + reduction: Dimensionality reduction to use for plotting (e.g., "banksy", "umap"). + group_by: Feature to group cells by for coloring (e.g., "banksy_clusters"). + label: If TRUE, label clusters on the plot. + pt_size: Size of the points in the plot. + verbose: If TRUE, print messages during execution. + width: Width of the output plot. + height: Height of the output plot. + units: Units for width and height ("in", "cm", "mm"). + dpi: Resolution for raster plots (e.g., PNG, JPEG). + + Returns: + A dictionary containing execution details: + - command_executed: The Rscript command and generated R script path. + - stdout: Standard output from the Rscript execution. + - stderr: Standard error from the Rscript execution. + - output_files: A list of paths to generated output files. + """ + # 1. Input validation + if not input_rdata_path.exists(): + raise FileNotFoundError(f"Input RData file not found: {input_rdata_path}") + if not input_rdata_path.is_file(): + raise ValueError(f"Input RData path is not a file: {input_rdata_path}") + + valid_plot_suffixes = [".png", ".pdf", ".jpeg", ".jpg", ".tiff", ".bmp"] + if output_plot_path.suffix.lower() not in valid_plot_suffixes: + raise ValueError(f"Output plot file must have one of the following extensions: {', '.join(valid_plot_suffixes)}") + + if pt_size <= 0: + raise ValueError("pt_size must be a positive float.") + if width <= 0 or height <= 0: + raise ValueError("Width and height must be positive floats.") + if units not in ["in", "cm", "mm"]: + raise ValueError(f"Invalid units: {units}. Choose from 'in', 'cm', 'mm'.") + if dpi <= 0: + raise ValueError("DPI must be a positive integer.") + + # Ensure output directory exists + output_plot_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate R script content + r_script_content = f""" + # Load required packages + library(Seurat) + library(banksy) + library(ggplot2) # For saving plots + + # Define input and output paths + input_obj_path <- "{input_rdata_path.as_posix()}" + output_plot_path <- "{output_plot_path.as_posix()}" + + # Check if input file exists + if (!file.exists(input_obj_path)) {{ + stop(paste("Input RData file not found:", input_obj_path)) + }} + + # Load the object + loaded_env <- new.env() + load(input_obj_path, envir = loaded_env) + + obj <- NULL + for (var_name in ls(loaded_env)) {{ + candidate <- get(var_name, envir = loaded_env) + if (inherits(candidate, "Seurat") || inherits(candidate, "BanksyObject")) {{ + obj <- candidate + break + }} + }} + + if (is.null(obj)) {{ + stop("No Seurat or BanksyObject found in the input RData file.") + }} + + message("Generating spatial dimensionality plot with parameters:") + message(paste(" reduction:", "{reduction}")) + message(paste(" group_by:", "{group_by}")) + message(paste(" label:", {str(label).upper()})) + message(paste(" pt_size:", {pt_size})) + message(paste(" verbose:", {str(verbose).upper()})) + + # Generate plot + p <- spatialDimPlot( + object = obj, + reduction = "{reduction}", + group.by = "{group_by}", + label = {str(label).upper()}, + pt.size.factor = {pt_size}, # Note: R parameter is pt.size.factor + verbose = {str(verbose).upper()} + ) + + # Save the plot + ggsave( + filename = output_plot_path, + plot = p, + width = {width}, + height = {height}, + units = "{units}", + dpi = {dpi} + ) + + message(paste("Plot saved to:", output_plot_path)) + """ + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + # 3. Subprocess execution + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + env=os.environ + ) + + stdout = process.stdout + stderr = process.stderr + + # 4. Error handling: Check for R-specific errors in stderr + if "Error" in stderr or "stop(" in stderr: + raise RuntimeError(f"R script execution failed. Stderr: {stderr}") + + if not output_plot_path.exists(): + raise RuntimeError(f"Output plot file was not created by R script: {output_plot_path}") + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_plot_path)], + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Is R installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up temporary R script + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..443a3dbaa17b252927fcc6750ea19d64dcd0aa4d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/app/bioconductor-banksy_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_banksy' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5745dcb463d5d3a4a0240bea07df9ef2cafba776 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-banksy: + build: . + image: mcp-bioconductor-banksy:latest + container_name: mcp-bioconductor-banksy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-banksy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..508d5e0076bfb9bafa1307f48692fa5c85f624eb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-banksy + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-banksy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..049a35d085b83f15bc149115150cd24367530eef --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-benchdamic via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-benchdamic -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-benchdamic_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-benchdamic_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-benchdamic_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/app/__pycache__/bioconductor-benchdamic_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/app/__pycache__/bioconductor-benchdamic_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98e5753e6e63b63e963933c21a5ff3e37ba6eed5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/app/__pycache__/bioconductor-benchdamic_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a6ed675c4d398642f704254b729325432807bab0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_server.py @@ -0,0 +1,464 @@ +import subprocess +import tempfile +from pathlib import Path +import os +import logging +from typing import List, Optional + +# Set up logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# MCP decorator is assumed to be available in the execution environment. +# This is a placeholder for the actual decorator. +class mcp: + @staticmethod + def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +@mcp.tool +def run_benchdamic( + config_file: Path, + output_dir: Path, +): + """ + Runs the full benchdamic pipeline. + + This function serves as the main entry point for the benchdamic workflow, + executing data generation, method application, evaluation, and plotting + based on a single YAML configuration file. The process is run within the + specified output directory. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory where all outputs will be stored. + It will be created if it doesn't exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + + # 2. File path handling + output_dir.mkdir(parents=True, exist_ok=True) + + # The R function benchdamic() relies on the 'output_dir' key within the config YAML. + # By running Rscript from the specified output_dir, we ensure that + # relative paths in the config file are resolved correctly. + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed. Please install it from Bioconductor.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + + cat("Starting benchdamic pipeline...\\n") + benchdamic::benchdamic(config_file = config_path) + cat("benchdamic pipeline finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=output_dir) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + # Use relative path for the command since we set cwd + command_to_execute = ["Rscript", str(r_script_path.name)] + + files_before = set(os.listdir(output_dir)) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + cwd=output_dir, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(os.listdir(output_dir)) + # Find new files and directories + new_items = files_after - files_before + output_files = [str(output_dir / item) for item in new_items] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files + } + +@mcp.tool +def generate_data( + config_file: Path, + output_dir: Path, +): + """ + Generates simulated data using the benchdamic configuration. + + This function corresponds to the `generate_data` step in the benchdamic + workflow. It reads simulation parameters from the config file and writes + the generated datasets to the specified output directory. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory where generated data will be stored. + It will be created if it doesn't exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + + # 2. File path handling + output_dir.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + output_path <- "{output_dir.resolve()}" + + cat("Starting data generation...\\n") + benchdamic::generate_data(config_file = config_path, output_dir = output_path) + cat("Data generation finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command_to_execute = ["Rscript", str(r_script_path)] + + files_before = set(p.resolve() for p in output_dir.glob('**/*')) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(p.resolve() for p in output_dir.glob('**/*')) + new_files = [str(p) for p in files_after - files_before] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": new_files + } + +@mcp.tool +def run_methods( + config_file: Path, + output_dir: Path, +): + """ + Runs differential abundance methods on generated data. + + This function corresponds to the `run_methods` step in the benchdamic + workflow. It applies the specified methods to the datasets found in the + output directory and saves their results. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory containing the generated data and + where method results will be stored. It must exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + if not output_dir.is_dir(): + raise FileNotFoundError(f"Output directory not found: {output_dir}. Please run generate_data first.") + + # 2. R script content + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + output_path <- "{output_dir.resolve()}" + + cat("Running differential abundance methods...\\n") + benchdamic::run_methods(config_file = config_path, output_dir = output_path) + cat("Method execution finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command_to_execute = ["Rscript", str(r_script_path)] + + files_before = set(p.resolve() for p in output_dir.glob('**/*')) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(p.resolve() for p in output_dir.glob('**/*')) + new_files = [str(p) for p in files_after - files_before] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": new_files + } + +@mcp.tool +def evaluate_methods( + config_file: Path, + output_dir: Path, +): + """ + Evaluates the performance of differential abundance methods. + + This function corresponds to the `evaluate_methods` step in the benchdamic + workflow. It computes performance metrics based on the method results + and ground truth, saving the evaluation to the output directory. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory containing method results. It must exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + if not output_dir.is_dir(): + raise FileNotFoundError(f"Output directory not found: {output_dir}.") + + # 2. R script content + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + output_path <- "{output_dir.resolve()}" + + cat("Evaluating method performance...\\n") + benchdamic::evaluate_methods(config_file = config_path, output_dir = output_path) + cat("Evaluation finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command_to_execute = ["Rscript", str(r_script_path)] + + files_before = set(p.resolve() for p in output_dir.glob('**/*')) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(p.resolve() for p in output_dir.glob('**/*')) + new_files = [str(p) for p in files_after - files_before] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": new_files + } + +@mcp.tool +def plot_results( + config_file: Path, + output_dir: Path, +): + """ + Generates plots from the evaluation results. + + This function corresponds to the `plot_results` step in the benchdamic + workflow. It creates various visualizations of the performance metrics + and saves them as files in the output directory. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory containing evaluation results. It must exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + if not output_dir.is_dir(): + raise FileNotFoundError(f"Output directory not found: {output_dir}.") + + # 2. R script content + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + output_path <- "{output_dir.resolve()}" + + cat("Generating plots...\\n") + benchdamic::plot_results(config_file = config_path, output_dir = output_path) + cat("Plot generation finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command_to_execute = ["Rscript", str(r_script_path)] + + files_before = set(p.resolve() for p in output_dir.glob('**/*')) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(p.resolve() for p in output_dir.glob('**/*')) + new_files = [str(p) for p in files_after - files_before] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": new_files + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..81c55f4d646eb595c0b00feb64ae68cf28d60fcd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_benchdamic' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..65f8f9f6c1b78e6c31e9ba07e6510d513ea8cfaf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-benchdamic: + build: . + image: mcp-bioconductor-benchdamic:latest + container_name: mcp-bioconductor-benchdamic + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-benchdamic + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..69f3813eec164585774531f51cba29fd74c0d74a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-benchdamic + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-benchdamic/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..130d0cb09407199e02934e5328c96ea05926be5b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-blase via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-blase -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-blase_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-blase_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-blase_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/__pycache__/bioconductor-blase_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/__pycache__/bioconductor-blase_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37fbfb91397b890d11f6911b85a99e99566556fc Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/__pycache__/bioconductor-blase_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b81d5232adb6c0b67ee95e04b724d805658e9686 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_server.py @@ -0,0 +1,193 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List + +# In a real MCP environment, the 'mcp' package would be available. +# For standalone execution, this decorator is a placeholder. +class mcp: + @staticmethod + def tool(func=None, **kwargs): + if func: + return func + return lambda f: f + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_blase' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def blase_run( + sce_file: Path, + bulk_data_file: Path, + output_prefix: str, + n_genes: int = 2000, + assay_name: str = "logcounts", + pseudotime_column: str = "pseudotime", + cell_group_column: Optional[str] = None, + n_boots: int = 100, + n_cores: int = 1, + seed: int = 123, + seurat_assay: str = "RNA", + dispersed_features_method: str = "seurat", +) -> Dict: + """ + Runs the BLASE analysis to map bulk RNA-seq data to a single-cell pseudotime trajectory. + + BLASE (Bulk Linking Analysis for Single-cell Experiments) uses Spearman correlation + with bootstrapping to determine the position of bulk RNA-seq samples along a + single-cell pseudotime trajectory. This tool is a wrapper for the main `blaseR` + function from the Bioconductor package. + + Args: + sce_file: Path to the SingleCellExperiment or Seurat object saved as an RDS file. + bulk_data_file: Path to the bulk RNA-seq data, typically a CSV file with genes + as rows (first column) and samples as columns. + output_prefix: A prefix for the output files. Two files will be generated: + `_results.rds` and `_plot.pdf`. + n_genes: Number of highly variable genes to use for the analysis. + assay_name: Name of the assay in the SCE object containing expression data. + pseudotime_column: Name of the column in `colData(sce)` containing pseudotime values. + cell_group_column: Optional name of the column in `colData(sce)` for grouping cells. + n_boots: Number of bootstrap iterations for confidence interval calculation. + n_cores: Number of cores to use for parallel processing. + seed: Random seed for reproducibility. + seurat_assay: The assay to use if the input `sce_file` contains a Seurat object. + dispersed_features_method: Method to find dispersed features. Must be 'seurat' or 'scran'. + + Returns: + A dictionary containing the execution command, stdout, stderr, and paths to the + generated output files (RDS results and PDF plot). + """ + # --- Input Validation --- + if not sce_file.is_file(): + raise FileNotFoundError(f"Input SCE file not found: {sce_file}") + if not bulk_data_file.is_file(): + raise FileNotFoundError(f"Input bulk data file not found: {bulk_data_file}") + + if n_genes <= 0: + raise ValueError("n_genes must be a positive integer.") + if n_boots <= 0: + raise ValueError("n_boots must be a positive integer.") + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + + if dispersed_features_method not in ["seurat", "scran"]: + raise ValueError("dispersed_features_method must be either 'seurat' or 'scran'.") + + # --- Prepare Output Paths --- + output_rds_path = Path(f"{output_prefix}_results.rds") + output_pdf_path = Path(f"{output_prefix}_plot.pdf") + + # --- R Script Generation --- + # Handle optional string parameter for R script: convert Python None to R NULL + r_cell_group = f'"{cell_group_column}"' if cell_group_column else "NULL" + + r_script_content = f""" + # Ensure required packages are available + if (!requireNamespace("blase", quietly = TRUE)) {{ + stop("The 'blase' package is not installed. Please install it from Bioconductor.") + }} + if (!requireNamespace("ggplot2", quietly = TRUE)) {{ + stop("The 'ggplot2' package is not installed.") + }} + library(blase) + library(ggplot2) + + # --- Input parameters from MCP tool --- + sce_file <- "{sce_file.resolve()}" + bulk_data_file <- "{bulk_data_file.resolve()}" + output_rds <- "{output_rds_path.resolve()}" + output_pdf <- "{output_pdf_path.resolve()}" + n_genes_param <- {n_genes} + assay_name_param <- "{assay_name}" + pseudotime_param <- "{pseudotime_column}" + cell_group_param <- {r_cell_group} + n_boots_param <- {n_boots} + n_cores_param <- {n_cores} + seed_param <- {seed} + seurat_assay_param <- "{seurat_assay}" + dispersed_features_method_param <- "{dispersed_features_method}" + + # --- Data Loading --- + cat("Loading single-cell data from:", sce_file, "\\n") + sce <- readRDS(sce_file) + + cat("Loading bulk data from:", bulk_data_file, "\\n") + # Assuming bulk data is a standard CSV with gene names in the first column + bulk_data <- as.matrix(read.csv(bulk_data_file, row.names = 1, check.names = FALSE)) + + # --- BLASE Analysis --- + cat("Running BLASE analysis...\\n") + blase_results <- blaseR( + sce = sce, + bulk_data = bulk_data, + n_genes = n_genes_param, + assay_name = assay_name_param, + pseudotime = pseudotime_param, + cell_group = cell_group_param, + n_boots = n_boots_param, + n_cores = n_cores_param, + seed = seed_param, + seurat_assay = seurat_assay_param, + dispersed_features_method = dispersed_features_method_param + ) + + # --- Save Results --- + cat("Saving results object to:", output_rds, "\\n") + saveRDS(blase_results, file = output_rds) + + # --- Generate and Save Plot --- + cat("Generating and saving plot to:", output_pdf, "\\n") + p <- plotBlase(blase_results) + ggsave(output_pdf, plot = p, width = 8, height = 6, device = "pdf") + + cat("BLASE analysis completed successfully.\\n") + """ + + # --- Subprocess Execution --- + r_script_path = None + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {e.cmd}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + # Ensure the temporary R script is always removed + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + # --- Structured Result Return --- + output_files = { + "results_rds": str(output_rds_path.resolve()), + "results_plot": str(output_pdf_path.resolve()) + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7c22627f7f0173e3d34cda25bb943ceeef526f87 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/app/bioconductor-blase_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_blase' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eccd488237878c7b9413ba58d98e98df504b8bd1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-blase: + build: . + image: mcp-bioconductor-blase:latest + container_name: mcp-bioconductor-blase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-blase + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a2b798ba05a05a1d718a06c7af2ed86cdfa2774 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-blase + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-blase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d4d8e2ec0016e59226eb9e474ee2211b6eda3866 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-catscradle via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-catscradle -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-catscradle_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-catscradle_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-catscradle_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/__pycache__/bioconductor-catscradle_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/__pycache__/bioconductor-catscradle_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..399d7a74081eb44286eb36a29be5d2e8643458a5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/__pycache__/bioconductor-catscradle_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9c4bdfb1741a2a019aa1e13eb3df700381e079 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_server.py @@ -0,0 +1,312 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_catscradle' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def catscradle_build_neighborhoods( + input_rds: str, + output_rds: str, + radius: float = 50.0, + cell_type_col: str = "cell_type", + assay: str = "Spatial", + slot: str = "counts", + min_cells: int = 1 +): + """ + Identifies tissue neighborhoods in spatial transcriptomics data and produces a Seurat object + where individual elements are neighborhoods rather than cells. + + Args: + input_rds: Path to the input Seurat or SpatialExperiment object (RDS format). + output_rds: Path where the resulting neighborhood Seurat object will be saved. + radius: The radius (in spatial units) defining the contiguous region surrounding individual cells. + cell_type_col: Metadata column name containing cell type annotations. + assay: Assay to use from the input object. + slot: Slot to use (e.g., counts, data). + min_cells: Minimum number of cells required to define a neighborhood. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + if radius <= 0: + return {"error": "Radius must be a positive float."} + + # R script to perform neighborhood construction + r_code = f""" + library(CatsCradle) + library(Seurat) + library(SpatialExperiment) + + # Load data + input_data <- readRDS("{input_path}") + + # Check if it's SpatialExperiment and convert if necessary + if (inherits(input_data, "SpatialExperiment")) {{ + # CatsCradle handles SE/SPE, but we ensure Seurat compatibility if needed + # Internal CatsCradle functions typically take these objects + }} + + # Core CatsCradle logic for neighborhood construction + # Based on package description: "produces Seurat objects whose individual elements are neighborhoods" + # We use the primary constructor function (inferred from documentation) + neighborhood_obj <- CatsCradle::spatialToNeighborhoods( + object = input_data, + radius = {radius}, + cell_type_col = "{cell_type_col}", + assay = "{assay}", + slot = "{slot}", + min_cells = {min_cells} + ) + + saveRDS(neighborhood_obj, "{output_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def catscradle_gene_centric_analysis( + input_rds: str, + output_rds: str, + assay: str = "RNA", + slot: str = "data", + variable_features_only: bool = True, + n_features: int = 2000 +): + """ + Enables the categorisation and annotation of genes by producing Seurat objects + whose elements are genes rather than cells. + + Args: + input_rds: Path to the input Seurat object (RDS format). + output_rds: Path where the gene-centric Seurat object will be saved. + assay: Assay to use for gene expression data. + slot: Slot to use (e.g., data, scale.data). + variable_features_only: Whether to only include highly variable features. + n_features: Number of features to select if variable_features_only is True. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + r_code = f""" + library(CatsCradle) + library(Seurat) + + input_data <- readRDS("{input_path}") + + # Core CatsCradle logic for gene-centric Seurat object creation + gene_obj <- CatsCradle::geneCentricSeurat( + object = input_data, + assay = "{assay}", + slot = "{slot}", + variable_features_only = {"TRUE" if variable_features_only else "FALSE"}, + n_features = {n_features} + ) + + saveRDS(gene_obj, "{output_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def catscradle_tag_neighborhoods( + neighborhood_rds: str, + output_rds: str, + tag_by: str = "cell_type", + threshold: float = 0.1 +): + """ + Categorizes neighborhoods by the cell types contained in them or the genes expressed in them. + + Args: + neighborhood_rds: Path to the neighborhood Seurat object created by catscradle_build_neighborhoods. + output_rds: Path to save the tagged neighborhood object. + tag_by: Attribute to tag by ('cell_type' or 'gene_expression'). + threshold: Minimum proportion or expression level to consider a tag present in a neighborhood. + """ + input_path = Path(neighborhood_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file not found: {neighborhood_rds}"} + + r_code = f""" + library(CatsCradle) + library(Seurat) + + nb_obj <- readRDS("{input_path}") + + # Categorize neighborhoods + nb_obj <- CatsCradle::tagNeighborhoods( + object = nb_obj, + tag_by = "{tag_by}", + threshold = {threshold} + ) + + saveRDS(nb_obj, "{output_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def catscradle_spatial_vignette_pipeline( + input_rds: str, + output_prefix: str, + radius: float = 50.0, + cell_type_col: str = "cell_type" +): + """ + Runs a standard CatsCradle spatial analysis pipeline, including neighborhood construction + and gene clustering, as described in the package vignettes. + + Args: + input_rds: Path to the input spatial transcriptomics RDS file. + output_prefix: Prefix for output files (e.g., 'results/sample1'). + radius: Radius for neighborhood definition. + cell_type_col: Metadata column for cell types. + """ + input_path = Path(input_rds) + out_dir = Path(output_prefix).parent + if not out_dir.exists(): + out_dir.mkdir(parents=True, exist_ok=True) + + r_code = f""" + library(CatsCradle) + library(Seurat) + + # 1. Load Data + spatial_data <- readRDS("{input_path}") + + # 2. Build Neighborhoods + nb_obj <- CatsCradle::spatialToNeighborhoods( + object = spatial_data, + radius = {radius}, + cell_type_col = "{cell_type_col}" + ) + saveRDS(nb_obj, paste0("{output_prefix}", "_neighborhoods.rds")) + + # 3. Gene Centric Analysis + gene_obj <- CatsCradle::geneCentricSeurat(spatial_data) + saveRDS(gene_obj, paste0("{output_prefix}", "_gene_centric.rds")) + + # 4. Discover Gene Clusters (Internal CatsCradle method) + # This typically involves standard Seurat clustering on the gene-centric object + gene_obj <- Seurat::FindVariableFeatures(gene_obj) + gene_obj <- Seurat::ScaleData(gene_obj) + gene_obj <- Seurat::RunPCA(gene_obj) + gene_obj <- Seurat::FindNeighbors(gene_obj) + gene_obj <- Seurat::FindClusters(gene_obj) + saveRDS(gene_obj, paste0("{output_prefix}", "_gene_clusters.rds")) + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [ + f"{output_prefix}_neighborhoods.rds", + f"{output_prefix}_gene_centric.rds", + f"{output_prefix}_gene_clusters.rds" + ] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c604bab269e08d1147d431d0970acc6a49f34d81 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/app/bioconductor-catscradle_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_catscradle' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d730384b0f7f5e35a4f9c96890d4ba2612be1eaa --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-catscradle: + build: . + image: mcp-bioconductor-catscradle:latest + container_name: mcp-bioconductor-catscradle + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-catscradle + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c46cd1636494f83da0ae619d694ce46850c60680 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-catscradle + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-catscradle/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..52ec0d803f99f7a08118a664f84fa502c5ecfe8e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-clustifyr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-clustifyr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-clustifyr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-clustifyr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-clustifyr_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/app/__pycache__/bioconductor-clustifyr_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/app/__pycache__/bioconductor-clustifyr_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce7efc2a30a82feedc44fbd3ba00e8de026a4428 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/app/__pycache__/bioconductor-clustifyr_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..479e8abb69c6c5096a5ae81bf9bd02ea73ae4f78 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py @@ -0,0 +1,127 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict, Any + +# @mcp.tool() is a placeholder for the actual decorator in the MCP framework. +# The code is written to be compatible with it. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_clustifyr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def clustifyr_rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script using Rscript, for running Bioconductor packages like clustifyr. + + This tool serves as a wrapper around the Rscript command-line interpreter, + allowing the execution of R scripts that utilize the clustifyr library or other + Bioconductor packages. You can either provide an R script file or a list of + R expressions to execute. + + Args: + script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute. Mutually exclusive with 'script_file'. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, print information on progress. + default_packages: A comma-separated list of package names to be loaded by default (e.g., "clustifyr,Seurat"). + save: If True, save the workspace at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, do not read the site and user environment files. Ignored if 'vanilla' is True. + no_site_file: If True, do not read the site-wide Rprofile. Ignored if 'vanilla' is True. + no_init_file: If True, do not read the user R profile. Ignored if 'vanilla' is True. + restore: If True, restore previously saved objects at startup. Ignored if 'vanilla' is True. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Note: Output files are not automatically detected and must be known from the R script's logic. + """ + # 1. Input Validation + if not script_file and not expressions: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + if script_file and expressions: + raise ValueError("'script_file' and 'expressions' are mutually exclusive and cannot be used together.") + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + cmd = ["Rscript"] + + # The --vanilla option is a shortcut for several other flags. + if vanilla: + cmd.append("--vanilla") + else: + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + + if verbose: + cmd.append("--verbose") + + if default_packages: + cmd.extend(["--default-packages", default_packages]) + + # Add the script file or expressions to execute + if script_file: + cmd.append(str(script_file)) + elif expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + # Add any additional arguments for the R script itself + if script_args: + cmd.extend(script_args) + + command_executed = shlex.join(cmd) + + # 3. Subprocess Execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Rscript does not have a defined output file parameter. + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # Handle cases where the R script fails + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9a8dc5da9264cbcef08a93d1d7a705cca6df9336 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_clustifyr' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..815f8ab58e324137dfb25d93e4ee371b34fc90af --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-clustifyr: + build: . + image: mcp-bioconductor-clustifyr:latest + container_name: mcp-bioconductor-clustifyr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-clustifyr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..34e35a6e37b07334f789ad2eaa09c886ac0f1f7e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-clustifyr + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clustifyr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1e1a9b49fc7ea6267c7df02b1ad96b7d47557d59 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-complexheatmap via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-complexheatmap -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-complexheatmap_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-complexheatmap_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-complexheatmap_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/__pycache__/bioconductor-complexheatmap_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/__pycache__/bioconductor-complexheatmap_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad963047d1a48c8066ae103ed74bf947da36960b Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/__pycache__/bioconductor-complexheatmap_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fad979cb135327d992c814fe538f72b0983845a2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_server.py @@ -0,0 +1,233 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided. +def mcp_tool_decorator_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("mcp", (), {"tool": mcp_tool_decorator_placeholder}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_complexheatmap' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def make_complex_heatmap( + matrix_file: Path, + output_file_prefix: str, + output_format: str = "png", + file_separator: str = "comma", + name: str = "heatmap", + cluster_rows: bool = True, + cluster_columns: bool = True, + show_row_names: bool = True, + show_column_names: bool = True, + row_names_font_size: int = 10, + column_names_font_size: int = 10, + clustering_distance_rows: str = "euclidean", + clustering_distance_columns: str = "euclidean", + clustering_method_rows: str = "complete", + clustering_method_columns: str = "complete", + row_dend_side: str = "left", + column_dend_side: str = "top", + show_heatmap_legend: bool = True, + heatmap_legend_title: Optional[str] = None, + row_title: Optional[str] = None, + column_title: Optional[str] = None, + color_min: str = "blue", + color_mid: str = "white", + color_max: str = "red", + break_min: Optional[float] = None, + break_mid: float = 0.0, + break_max: Optional[float] = None, + na_col: str = "grey", + output_width_in: int = 8, + output_height_in: int = 8, + output_res_dpi: int = 300, +) -> dict: + """ + Generates a complex heatmap using the R package ComplexHeatmap. + + This tool takes a numerical matrix as input and produces a heatmap image. + The input file should be a text file (CSV or TSV) where the first column + contains row names and the first row contains column names. + + Args: + matrix_file: Path to the input data matrix (CSV or TSV). + output_file_prefix: Prefix for the output heatmap file. + output_format: Format of the output image. Valid choices: 'png', 'pdf', 'svg'. + file_separator: Separator used in the matrix file. Valid choices: 'comma', 'tab'. + name: Name of the heatmap, used as the default legend title. + cluster_rows: Whether to perform clustering on rows. + cluster_columns: Whether to perform clustering on columns. + show_row_names: Whether to display row names on the heatmap. + show_column_names: Whether to display column names on the heatmap. + row_names_font_size: Font size for row names. + column_names_font_size: Font size for column names. + clustering_distance_rows: Distance measure for row clustering. + clustering_distance_columns: Distance measure for column clustering. + clustering_method_rows: Method for row clustering. + clustering_method_columns: Method for column clustering. + row_dend_side: Position of the row dendrogram. Valid choices: 'left', 'right'. + column_dend_side: Position of the column dendrogram. Valid choices: 'top', 'bottom'. + show_heatmap_legend: Whether to display the heatmap legend. + heatmap_legend_title: Title for the heatmap legend. Defaults to the 'name' parameter. + row_title: Title for the rows. + column_title: Title for the columns. + color_min: Color for the minimum value in the heatmap. + color_mid: Color for the middle value in the heatmap. + color_max: Color for the maximum value in the heatmap. + break_min: Value corresponding to the minimum color. Defaults to the matrix minimum. + break_mid: Value corresponding to the middle color. + break_max: Value corresponding to the maximum color. Defaults to the matrix maximum. + na_col: Color for NA (missing) values. + output_width_in: Width of the output image in inches. + output_height_in: Height of the output image in inches. + output_res_dpi: Resolution (DPI) for PNG output. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not matrix_file.is_file(): + raise FileNotFoundError(f"Input file not found: {matrix_file}") + + valid_formats = ["png", "pdf", "svg"] + if output_format not in valid_formats: + raise ValueError(f"output_format must be one of {valid_formats}, not '{output_format}'") + + valid_separators = ["comma", "tab"] + if file_separator not in valid_separators: + raise ValueError(f"file_separator must be one of {valid_separators}, not '{file_separator}'") + + valid_row_dend_sides = ["left", "right"] + if row_dend_side not in valid_row_dend_sides: + raise ValueError(f"row_dend_side must be one of {valid_row_dend_sides}, not '{row_dend_side}'") + + valid_col_dend_sides = ["top", "bottom"] + if column_dend_side not in valid_col_dend_sides: + raise ValueError(f"column_dend_side must be one of {valid_col_dend_sides}, not '{column_dend_side}'") + + if output_width_in <= 0 or output_height_in <= 0 or output_res_dpi <= 0: + raise ValueError("Output dimensions and resolution must be positive.") + + # --- R Script Generation --- + output_file = Path(f"{output_file_prefix}.{output_format}") + + sep = "," if file_separator == "comma" else "\\t" + + r_script_lines = [ + "library(ComplexHeatmap)", + "library(circlize)", + "", + f'mat <- as.matrix(read.csv("{matrix_file}", row.names=1, header=TRUE, sep="{sep}"))', + "", + "# Define color mapping function", + "mat_min <- min(mat, na.rm = TRUE)", + "mat_max <- max(mat, na.rm = TRUE)", + ] + + break_min_r = str(break_min) if break_min is not None else "mat_min" + break_max_r = str(break_max) if break_max is not None else "mat_max" + + r_script_lines.append( + f'col_fun = colorRamp2(c({break_min_r}, {break_mid}, {break_max_r}), c("{color_min}", "{color_mid}", "{color_max}"))' + ) + + r_script_lines.append("") + r_script_lines.append("# Open graphics device") + if output_format == "png": + r_script_lines.append(f'png("{output_file}", width={output_width_in}, height={output_height_in}, units="in", res={output_res_dpi})') + elif output_format == "pdf": + r_script_lines.append(f'pdf("{output_file}", width={output_width_in}, height={output_height_in})') + elif output_format == "svg": + r_script_lines.append(f'svg("{output_file}", width={output_width_in}, height={output_height_in})') + + # Build Heatmap function arguments + ht_params = [ + "mat", + f'name = "{name}"', + "col = col_fun", + f'na_col = "{na_col}"', + f"cluster_rows = {str(cluster_rows).upper()}", + f"cluster_columns = {str(cluster_columns).upper()}", + f"show_row_names = {str(show_row_names).upper()}", + f"show_column_names = {str(show_column_names).upper()}", + f'row_names_gp = gpar(fontsize = {row_names_font_size})', + f'column_names_gp = gpar(fontsize = {column_names_font_size})', + f'clustering_distance_rows = "{clustering_distance_rows}"', + f'clustering_distance_columns = "{clustering_distance_columns}"', + f'clustering_method_rows = "{clustering_method_rows}"', + f'clustering_method_columns = "{clustering_method_columns}"', + f'row_dend_side = "{row_dend_side}"', + f'column_dend_side = "{column_dend_side}"', + f"show_heatmap_legend = {str(show_heatmap_legend).upper()}", + ] + + if row_title: + ht_params.append(f'row_title = "{row_title}"') + if column_title: + ht_params.append(f'column_title = "{column_title}"') + if heatmap_legend_title: + ht_params.append(f'heatmap_legend_param = list(title = "{heatmap_legend_title}")') + + r_script_lines.append("") + r_script_lines.append("# Create and draw the heatmap") + r_script_lines.append(f"ht = Heatmap({', '.join(ht_params)})") + r_script_lines.append("draw(ht)") + r_script_lines.append("") + r_script_lines.append("# Close the graphics device") + r_script_lines.append("dev.off()") + + r_script = "\n".join(r_script_lines) + + # --- Subprocess Execution --- + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # Provide more context in case of an R error + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"R Script Content:\n---\n{r_script}\n---\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) from e + finally: + # Clean up the temporary script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..778d5a23914d720e0da9da3a661fa7d11abddf48 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_complexheatmap' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..abf545b662467e8085f4cce746121deafc82b593 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-complexheatmap: + build: . + image: mcp-bioconductor-complexheatmap:latest + container_name: mcp-bioconductor-complexheatmap + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-complexheatmap + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0081bc8f415129604bd28e7791cccea6de50469e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-complexheatmap + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-complexheatmap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eb724cc9838a8a6772f972aac6a8cd14be1ef854 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-ctsv via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ctsv -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-ctsv_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-ctsv_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-ctsv_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/__pycache__/bioconductor-ctsv_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/__pycache__/bioconductor-ctsv_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2653081540cc797497ae2a84218815293f1a9ce1 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/__pycache__/bioconductor-ctsv_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f4b440d72cb0087b2ed07a266c8b0aa454678f5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_server.py @@ -0,0 +1,254 @@ +import subprocess +import tempfile +import textwrap +import re +from pathlib import Path +from typing import Optional, Dict, Any + +# This is a placeholder for the actual decorator as per the user's request. +# In a real MCP environment, you would use `from mcp import mcp`. +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool}) + +# Define allowed values for specific string parameters to ensure validity +ALLOWED_DIST_METHODS = ["dtw_basic", "dtw", "sbd", "fourier", "euclidean"] +ALLOWED_CENTROID_METHODS = ["dba", "pam", "mean", "median", "shape"] +ALLOWED_NORM_METHODS = ["zscore", "minmax", "none"] +ALLOWED_STEP_PATTERNS = [ + "symmetric1", "symmetricP1", "symmetric2", "symmetricP2", + "asymmetric", "asymmetricP0", "asymmetricP05", "asymmetricP1", "asymmetricP2" +] +ALLOWED_K_METHODS = ["all", "silhouette", "elbow", "gap_stat"] + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_ctsv' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_ctsv( + input_file: Path, + output_dir: Path, + n_clusters: Optional[int] = None, + k_list: Optional[str] = None, + output_prefix: str = "ctsv_results", + dist_method: str = "dtw_basic", + centroid_method: str = "dba", + norm_method: str = "zscore", + step_pattern: str = "symmetricP2", + window_size: Optional[int] = None, + seed: int = 1234, + k_method: str = "all", +) -> Dict[str, Any]: + """ + Performs clustering of temporal signals in raster data using the 'ctsv' R package. + + This tool wraps the core functions of the 'ctsv' Bioconductor package. It can either + run clustering for a fixed number of clusters (by setting 'n_clusters') or automatically + determine the optimal number of clusters from a given range (by setting 'k_list'). + + Args: + input_file: Path to the input raster file (e.g., GeoTIFF stack). + output_dir: Path to the directory where output files will be saved. + n_clusters: The fixed number of clusters to create. Mutually exclusive with 'k_list'. + k_list: A range of cluster numbers to test for automatic selection (e.g., "2:10"). + Mutually exclusive with 'n_clusters'. + output_prefix: Prefix for all output files. + dist_method: The distance method for comparing time series. + centroid_method: The method for calculating cluster centroids. + norm_method: The normalization method to apply to the time series. + step_pattern: The step pattern for Dynamic Time Warping (DTW). + window_size: The window size for DTW, constraining the warping path. + seed: An integer for the random number generator to ensure reproducibility. + k_method: The method for selecting the optimal number of clusters when 'k_list' is used. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a + structured dictionary of output file paths. + """ + # 1. Input Validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if (n_clusters is None and k_list is None) or (n_clusters is not None and k_list is not None): + raise ValueError("Exactly one of 'n_clusters' or 'k_list' must be provided.") + + if n_clusters is not None and n_clusters <= 1: + raise ValueError("'n_clusters' must be an integer greater than 1.") + + if k_list is not None: + if not re.match(r"^\d+:\d+$", k_list): + raise ValueError("Invalid 'k_list' format. Expected 'start:end', e.g., '2:10'.") + start, end = map(int, k_list.split(':')) + if start < 2 or start >= end: + raise ValueError("'k_list' range must start at 2 or greater and be an increasing range.") + + if dist_method not in ALLOWED_DIST_METHODS: + raise ValueError(f"Invalid 'dist_method'. Choose from: {', '.join(ALLOWED_DIST_METHODS)}") + if centroid_method not in ALLOWED_CENTROID_METHODS: + raise ValueError(f"Invalid 'centroid_method'. Choose from: {', '.join(ALLOWED_CENTROID_METHODS)}") + if norm_method not in ALLOWED_NORM_METHODS: + raise ValueError(f"Invalid 'norm_method'. Choose from: {', '.join(ALLOWED_NORM_METHODS)}") + if step_pattern not in ALLOWED_STEP_PATTERNS: + raise ValueError(f"Invalid 'step_pattern'. Choose from: {', '.join(ALLOWED_STEP_PATTERNS)}") + if k_list is not None and k_method not in ALLOWED_K_METHODS: + raise ValueError(f"Invalid 'k_method'. Choose from: {', '.join(ALLOWED_K_METHODS)}") + + if window_size is not None and window_size <= 0: + raise ValueError("'window_size' must be a positive integer.") + + # 2. R Script Generation + # We embed parameters directly into the script to avoid shell quoting issues. + r_script_content = textwrap.dedent(f""" + # Suppress package startup messages for cleaner output + suppressPackageStartupMessages(library(ctsv)) + suppressPackageStartupMessages(library(raster)) + suppressPackageStartupMessages(library(dtw)) + + # --- Parameters --- + input_file_path <- "{str(input_file.resolve())}" + output_dir_path <- "{str(output_dir.resolve())}" + output_prefix_str <- "{output_prefix}" + n_clusters_val <- {n_clusters if n_clusters is not None else 'NULL'} + k_list_str <- {"'{k_list}'" if k_list is not None else 'NULL'} + dist_method_str <- "{dist_method}" + centroid_method_str <- "{centroid_method}" + norm_method_str <- "{norm_method}" + step_pattern_str <- "{step_pattern}" + window_size_val <- {window_size if window_size is not None else 'NULL'} + seed_val <- {seed} + k_method_str <- "{k_method}" + + # Set seed for reproducibility + set.seed(seed_val) + + # Load input data + message("Loading input data from: ", input_file_path) + input_data <- tryCatch({{ + raster::stack(input_file_path) + }}, error = function(e) {{ + stop("Failed to load input file. Ensure it is a valid raster format. Error: ", e$message) + }}) + + # Map step pattern string to dtw object + step_pattern_obj <- switch(step_pattern_str, + "symmetric1" = dtw::symmetric1, "symmetricP1" = dtw::symmetricP1, + "symmetric2" = dtw::symmetricP2, "symmetricP2" = dtw::symmetricP2, + "asymmetric" = dtw::asymmetric, "asymmetricP0" = dtw::asymmetricP0, + "asymmetricP05" = dtw::asymmetricP05, "asymmetricP1" = dtw::asymmetricP1, + "asymmetricP2" = dtw::asymmetricP2, + dtw::symmetricP2 # Default + ) + + # Decide whether to run ctsv or ctsv_auto + if (!is.null(n_clusters_val)) {{ + message("Running ctsv with n_clusters = ", n_clusters_val) + result <- ctsv( + x = input_data, n_clusters = n_clusters_val, dist_method = dist_method_str, + centroid_method = centroid_method_str, norm_method = norm_method_str, + step_pattern = step_pattern_obj, window_size = window_size_val, seed = seed_val + ) + }} else if (!is.null(k_list_str)) {{ + message("Running ctsv_auto with k_list = ", k_list_str) + k_vector <- eval(parse(text=k_list_str)) + result <- ctsv_auto( + x = input_data, k_list = k_vector, dist_method = dist_method_str, + centroid_method = centroid_method_str, norm_method = norm_method_str, + step_pattern = step_pattern_obj, window_size = window_size_val, + seed = seed_val, k_method = k_method_str + ) + }} else {{ + stop("Internal error: Neither n_clusters nor k_list was provided to the R script.") + }} + + # Create output directory + dir.create(output_dir_path, showWarnings = FALSE, recursive = TRUE) + + # --- Save outputs --- + clustered_raster_path <- file.path(output_dir_path, paste0(output_prefix_str, "_clustered_raster.tif")) + raster::writeRaster(result$clustered_raster, filename=clustered_raster_path, overwrite=TRUE) + message("SUCCESS: Saved clustered raster to: ", clustered_raster_path) + + profiles_plot_path <- file.path(output_dir_path, paste0(output_prefix_str, "_profiles.png")) + png(profiles_plot_path, width=800, height=600) + plot(ctsv_get_profiles(result)) + dev.off() + message("SUCCESS: Saved profiles plot to: ", profiles_plot_path) + + members_df <- ctsv_get_members(result) + members_csv_path <- file.path(output_dir_path, paste0(output_prefix_str, "_members.csv")) + write.csv(members_df, file=members_csv_path, row.names=FALSE) + message("SUCCESS: Saved cluster members to: ", members_csv_path) + + if (!is.null(k_list_str)) {{ + validation_plot_path <- file.path(output_dir_path, paste0(output_prefix_str, "_k_validation.png")) + png(validation_plot_path, width=800, height=600) + plot(result$k_validation) + dev.off() + message("SUCCESS: Saved k validation plot to: ", validation_plot_path) + }} + + message("Processing complete.") + """) + + # 3. Subprocess Execution + r_script_path = "" + try: + output_dir.mkdir(parents=True, exist_ok=True) + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=output_dir) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=output_dir, + ) + + # 4. Collect and Verify Output Files + output_files_map = { + "clustered_raster": output_dir / f"{output_prefix}_clustered_raster.tif", + "profiles_plot": output_dir / f"{output_prefix}_profiles.png", + "cluster_members": output_dir / f"{output_prefix}_members.csv", + } + if k_list is not None: + output_files_map["k_validation_plot"] = output_dir / f"{output_prefix}_k_validation.png" + + # Verify that all expected files were created + missing_files = [str(p) for p in output_files_map.values() if not p.exists()] + if missing_files: + raise RuntimeError(f"R script finished, but expected output files are missing: {', '.join(missing_files)}") + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {key: str(path) for key, path in output_files_map.items()} + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Stderr:\n{e.stderr}\n" + f"Stdout:\n{e.stdout}" + ) + raise RuntimeError(error_message) from e + finally: + # Clean up the temporary R script + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d70d357d3a8631b2eecaee6288607cc627bfbdce --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/app/bioconductor-ctsv_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_ctsv' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9ff81c86eee540a7c6bf6a8d1be45b64e058c6b9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ctsv: + build: . + image: mcp-bioconductor-ctsv:latest + container_name: mcp-bioconductor-ctsv + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ctsv + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6db1e33d080c74872941d56c7234ca6d659a2fdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ctsv + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ctsv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..58d8e02b0aef74db7e2e9514bae607a6208870c7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-data-packages via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-data-packages -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-data-packages_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-data-packages_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-data-packages_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/__pycache__/bioconductor-data-packages_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/__pycache__/bioconductor-data-packages_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d82ce72da4711d622e03ce301b5d7c39654bf829 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/__pycache__/bioconductor-data-packages_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_server.py new file mode 100644 index 0000000000000000000000000000000000000000..da46b8bc503a4957a0a94c41d8a4d92cfe9e94f5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_server.py @@ -0,0 +1,254 @@ +from pathlib import Path +import subprocess +from typing import Optional, List, Union +import tempfile +import os + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_data_packages' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def install_bioconductor_data_package( + package_name: str, + lib_path: Optional[str] = None, + update: bool = False, + ask: bool = False, + force: bool = False, + version: Optional[str] = None +): + """ + Installs a Bioconductor data package using the R BiocManager infrastructure. + + Args: + package_name: The name of the Bioconductor data package to install (e.g., 'AnnotationHub', 'GenomicFeatures'). + lib_path: Specific library path where the package should be installed. + update: Whether to update all dependencies during installation. + ask: Whether to prompt the user before installing/updating. + force: Force installation even if the package is already installed. + version: Specific Bioconductor version to use (e.g., '3.16'). + """ + # Input validation + if not package_name: + return {"error": "package_name is required"} + + # Construct R command + r_cmds = ["if (!require('BiocManager', quietly = TRUE)) install.packages('BiocManager', repos='https://cloud.r-project.org')"] + + install_args = [f"'{package_name}'"] + if lib_path: + lib_p = Path(lib_path).resolve() + install_args.append(f"lib='{lib_p}'") + + install_args.append(f"update={'TRUE' if update else 'FALSE'}") + install_args.append(f"ask={'TRUE' if ask else 'FALSE'}") + install_args.append(f"force={'TRUE' if force else 'FALSE'}") + + if version: + r_cmds.append(f"BiocManager::install(version = '{version}', ask = FALSE)") + + r_cmds.append(f"BiocManager::install({', '.join(install_args)})") + + full_r_script = "; ".join(r_cmds) + + try: + result = subprocess.run( + ["Rscript", "-e", full_r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{full_r_script}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript -e \"{full_r_script}\"", + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def list_bioconductor_data_packages( + version: Optional[str] = None, + grep_pattern: Optional[str] = None +): + """ + Lists available Bioconductor data packages for a specific version. + + Args: + version: Bioconductor version to query (e.g., '3.16'). If None, uses the current version. + grep_pattern: Optional pattern to filter the package list. + """ + r_cmds = ["if (!require('BiocManager', quietly = TRUE)) install.packages('BiocManager', repos='https://cloud.r-project.org')"] + + if version: + r_cmds.append(f"pkgs <- BiocManager::available(version = '{version}')") + else: + r_cmds.append("pkgs <- BiocManager::available()") + + # Filter for ExperimentData or AnnotationData if possible, or just return all + r_cmds.append("print(pkgs)") + + full_r_script = "; ".join(r_cmds) + + try: + result = subprocess.run( + ["Rscript", "-e", full_r_script], + capture_output=True, + text=True, + check=True + ) + + output = result.stdout + if grep_pattern: + lines = [line for line in output.split('\n') if grep_pattern.lower() in line.lower()] + output = '\n'.join(lines) + + return { + "command_executed": "Rscript BiocManager::available()", + "stdout": output, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def download_bioconductor_data_file( + url: str, + output_path: str, + use_curl: bool = True +): + """ + Downloads a specific Bioconductor data file or tarball using curl. + + Args: + url: The direct URL to the Bioconductor data resource. + output_path: The local path where the file should be saved. + use_curl: Whether to use curl (default) or standard download methods. + """ + out_p = Path(output_path) + # Ensure directory exists + out_p.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["curl", "-L", url, "-o", str(out_p)] if use_curl else ["wget", url, "-O", str(out_p)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_file": str(out_p.resolve()) + } + except subprocess.CalledProcessError as e: + return { + "error": f"Download failed: {str(e)}", + "stderr": e.stderr + } + +@mcp.tool() +def parse_bioconductor_yaml_metadata( + yaml_file_path: str, + query: str = "." +): + """ + Parses Bioconductor data package metadata stored in YAML format using yq. + + Args: + yaml_file_path: Path to the YAML file containing package metadata. + query: The yq query string to extract specific information (default is "." for everything). + """ + yaml_p = Path(yaml_file_path) + if not yaml_p.exists(): + return {"error": f"File not found: {yaml_file_path}"} + + try: + # Using yq to parse the metadata + result = subprocess.run( + ["yq", query, str(yaml_p)], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"yq {query} {yaml_file_path}", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": f"yq execution failed: {str(e)}", + "stderr": e.stderr + } + +@mcp.tool() +def search_bioconductor_data_packages( + query: str +): + """ + Searches for Bioconductor data packages matching a specific query string. + + Args: + query: The search term (e.g., 'H. sapiens', 'methylation', 'scRNA-seq'). + """ + if not query: + return {"error": "Query string is required"} + + r_script = f""" + if (!require('BiocManager', quietly = TRUE)) install.packages('BiocManager', repos='https://cloud.r-project.org'); + pkgs <- BiocManager::available(); + matches <- pkgs[grep('{query}', pkgs, ignore.case = TRUE)]; + cat(matches, sep='\\n'); + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "query": query, + "results": result.stdout.splitlines(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def get_bioconductor_version_info(): + """ + Retrieves the current Bioconductor and R version information. + """ + r_script = "if (!require('BiocManager', quietly = TRUE)) install.packages('BiocManager', repos='https://cloud.r-project.org'); BiocManager::version()" + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "bioconductor_version": result.stdout.strip(), + "r_version": subprocess.run(["R", "--version"], capture_output=True, text=True).stdout.splitlines()[0] + } + except subprocess.CalledProcessError as e: + return {"error": str(e)} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d2fead283b6e8bcf843fb60ebd493d1751ad8f4e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/app/bioconductor-data-packages_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_data_packages' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0d8d5a3e5ea75f6a8a9d10e4afddae0f74a6bd20 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-data-packages: + build: . + image: mcp-bioconductor-data-packages:latest + container_name: mcp-bioconductor-data-packages + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-data-packages + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fae089583404a67cf5f48b9cab9c8e51f9c0eb24 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-data-packages + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-data-packages/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b841dc6fd6491701fc9d712aa92aad2174e6eed7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-decontam via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-decontam -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-decontam_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-decontam_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-decontam_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/__pycache__/bioconductor-decontam_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/__pycache__/bioconductor-decontam_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea5dacc01b240bf1e6bea93e315036de5d40a293 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/__pycache__/bioconductor-decontam_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ec61400556fffc522339bc4ff2f66808ccf4a6d4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_server.py @@ -0,0 +1,236 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Literal + +# The R script that will be executed. It includes package installation, +# argument parsing, data loading, running decontam, and saving results. +R_SCRIPT_CONTENT = """ +# --- Package Installation --- +# Function to install a package if it's not already installed +install_if_missing <- function(pkg, repo = "cran") { + if (!requireNamespace(pkg, quietly = TRUE)) { + if (repo == "bioc") { + if (!requireNamespace("BiocManager", quietly = TRUE)) { + install.packages("BiocManager", repos = "http://cran.us.r-project.org") + } + BiocManager::install(pkg, update = FALSE, ask = FALSE) + } else { + install.packages(pkg, repos = "http://cran.us.r-project.org") + } + } +} + +# Install required packages from CRAN and Bioconductor +install_if_missing("argparse", repo = "cran") +install_if_missing("decontam", repo = "bioc") +install_if_missing("phyloseq", repo = "bioc") + +# --- Library Loading --- +suppressPackageStartupMessages(library(argparse)) +suppressPackageStartupMessages(library(decontam)) +suppressPackageStartupMessages(library(phyloseq)) + +# --- Argument Parsing --- +parser <- ArgumentParser(description="Run decontam's isContaminant function from a command line interface.") + +parser$add_argument("--feature_table", type="character", required=TRUE, help="Path to the feature table (CSV, features as columns, samples as rows).") +parser$add_argument("--metadata", type="character", required=TRUE, help="Path to the sample metadata file (CSV).") +parser$add_argument("--output_path", type="character", required=TRUE, help="Path to save the output results CSV file.") +parser$add_argument("--method", type="character", choices=c("prevalence", "frequency", "combined"), default="prevalence", help="Decontamination method to use.") +parser$add_argument("--neg_column", type="character", required=TRUE, help="Column name in metadata indicating negative controls (must contain TRUE/FALSE values).") +parser$add_argument("--conc_column", type="character", default=NULL, help="Column name in metadata for DNA concentration. Required for 'frequency' and 'combined' methods.") +parser$add_argument("--threshold", type="double", default=0.1, help="P-value threshold for contaminant classification.") +parser$add_argument("--normalize", action="store_true", default=FALSE, help="Normalize by library size (for frequency method). Pass this flag to enable.") +parser$add_argument("--detailed", action="store_true", default=FALSE, help="Return detailed output including p-values. Pass this flag to enable.") + +args <- parser$parse_args() + +# --- Data Loading and Validation --- +tryCatch({ + # The first column of the input CSVs is expected to be the sample/feature names + feature_table <- read.csv(args$feature_table, row.names=1, check.names=FALSE) +}, error = function(e) { + stop(paste("Error reading feature table:", e$message)) +}) + +tryCatch({ + metadata <- read.csv(args$metadata, row.names=1, check.names=FALSE) +}, error = function(e) { + stop(paste("Error reading metadata:", e$message)) +}) + +# Align samples between feature table and metadata to ensure they match +common_samples <- intersect(rownames(feature_table), rownames(metadata)) +if (length(common_samples) == 0) { + stop("No common samples found between feature table and metadata. Please check that sample names in the first column of both files match.") +} +feature_table <- feature_table[common_samples, , drop=FALSE] +metadata <- metadata[common_samples, , drop=FALSE] + +# Validate that required columns exist in the metadata +if (!args$neg_column %in% colnames(metadata)) { + stop(paste0("Negative control column '", args$neg_column, "' not found in metadata file.")) +} +if (args$method %in% c("frequency", "combined")) { + if (is.null(args$conc_column)) { + stop("A concentration column ('--conc_column') is required for the 'frequency' or 'combined' method.") + } + if (!args$conc_column %in% colnames(metadata)) { + stop(paste0("Concentration column '", args$conc_column, "' not found in metadata file.")) + } +} + +# --- Run Decontam --- +# Decontam requires a phyloseq object, which we construct from the input tables +otu <- otu_table(as.matrix(feature_table), taxa_are_rows=FALSE) +samdf <- sample_data(metadata) +physeq <- phyloseq(otu, samdf) + +# Prepare arguments for the isContaminant function call +is_contam_args <- list( + seqtab = physeq, + method = args$method, + neg = args$neg_column, + threshold = args$threshold, + detailed = args$detailed +) + +if (args$method %in% c("frequency", "combined")) { + is_contam_args$conc <- args$conc_column + is_contam_args$normalize <- args$normalize +} + +# Execute isContaminant and handle potential errors during its run +contam_df <- tryCatch({ + do.call(isContaminant, is_contam_args) +}, error = function(e) { + stop(paste("Error during decontam execution:", e$message)) +}) + +# --- Save Output --- +tryCatch({ + write.csv(contam_df, file=args$output_path, row.names=TRUE) +}, error = function(e) { + stop(paste("Error writing output file:", e$message)) +}) + +cat(paste("Decontam analysis complete. Results saved to", args$output_path, "\\n")) +""" + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_decontam' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def is_contaminant( + feature_table: Path, + metadata: Path, + output_path: Path, + neg_column: str, + method: Literal["prevalence", "frequency", "combined"] = "prevalence", + conc_column: Optional[str] = None, + threshold: float = 0.1, + normalize: bool = True, + detailed: bool = False, +): + """ + Identifies contaminant sequences in sequencing data using the decontam R package. + + This tool wraps the isContaminant function from decontam, which identifies contaminants + based on two statistical methods: 'frequency' (correlation with DNA concentration) and + 'prevalence' (presence in negative controls). + + Args: + feature_table: Path to the feature table file (e.g., ASV/OTU table). + Format: CSV with samples as rows and features as columns. + The first column must contain unique sample IDs. + metadata: Path to the sample metadata file. + Format: CSV with samples as rows and metadata as columns. + The first column must contain sample IDs matching the feature table. + output_path: Path to save the output CSV file containing contaminant classifications. + neg_column: The name of the column in the metadata file that identifies negative + control samples. This column must contain boolean (TRUE/FALSE) values. + method: The statistical method for identifying contaminants. + 'prevalence': Identifies contaminants based on their higher prevalence in negative controls. + 'frequency': Identifies contaminants based on their inverse correlation with sample DNA concentration. + 'combined': A combination of both frequency and prevalence methods. + conc_column: The name of the column in the metadata file containing DNA concentrations. + Required if method is 'frequency' or 'combined'. + threshold: The p-value threshold for classifying a feature as a contaminant. + Features with a p-value below this threshold are classified as contaminants. + normalize: If True, normalize by library size in the 'frequency' method. + detailed: If True, the output will include detailed statistics (e.g., p-values) + for each feature instead of just the boolean contaminant classification. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not feature_table.is_file(): + raise FileNotFoundError(f"Feature table file not found: {feature_table}") + if not metadata.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata}") + if not (0.0 <= threshold <= 1.0): + raise ValueError("Threshold must be a float between 0.0 and 1.0.") + if method in ["frequency", "combined"] and not conc_column: + raise ValueError("The 'conc_column' parameter is required for 'frequency' and 'combined' methods.") + + # Check for Rscript dependency + if not shutil.which("Rscript"): + raise RuntimeError("Rscript executable not found in PATH. Please ensure R is installed and accessible.") + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_decontam.R" + r_script_path.write_text(R_SCRIPT_CONTENT) + + # --- Command Construction --- + cmd = [ + "Rscript", + str(r_script_path), + "--feature_table", str(feature_table.resolve()), + "--metadata", str(metadata.resolve()), + "--output_path", str(output_path.resolve()), + "--method", method, + "--neg_column", neg_column, + "--threshold", str(threshold), + ] + + if conc_column: + cmd.extend(["--conc_column", conc_column]) + if normalize: + cmd.append("--normalize") + if detailed: + cmd.append("--detailed") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # R can print errors to either stdout or stderr, so we combine them for a comprehensive error message. + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}\n" + ) + raise RuntimeError(error_message) from e + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path.resolve())] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ce314e63102909fabf0930e6385b0a2cfc949f0d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/app/bioconductor-decontam_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_decontam' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c6ce8822731866aa0f4eb6b74685000567296134 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-decontam: + build: . + image: mcp-bioconductor-decontam:latest + container_name: mcp-bioconductor-decontam + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-decontam + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb54043185521d18619255a22a22a8db8de09be4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-decontam + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-decontam/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..688e4b88373ed30f5a74d5f62ced57b363eb1fc3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-diffbind via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-diffbind -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-diffbind_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-diffbind_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-diffbind_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/__pycache__/bioconductor-diffbind_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/__pycache__/bioconductor-diffbind_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6c25a17c5b497f34a8f48e357d89173a9be0477 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/__pycache__/bioconductor-diffbind_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd61607c37bca9be1cf86268553917ec81b74c3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_server.py @@ -0,0 +1,269 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_diffbind' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_diffbind( + sample_sheet: Path, + output_prefix: str, + method: str = "DBA_DESEQ2", + fdr_threshold: float = 0.05, + summits: Optional[int] = None, + min_overlap: int = 2, + use_summarize_overlaps: bool = False, + cores: int = 1, + plot_pca: bool = True, + plot_heatmap: bool = True, + plot_ma: bool = True, + plot_volcano: bool = True, +) -> dict: + """ + Performs differential binding analysis of ChIP-Seq peak data using DiffBind. + + This tool wraps the main DiffBind analysis workflow, including data loading, + read counting, normalization, contrast definition, differential analysis, + and reporting. + + Args: + sample_sheet: Path to the sample sheet CSV file. This file must contain + metadata for each sample. Essential columns include: SampleID, + Condition, Replicate, bamReads, and Peaks. Optional columns include + ControlID and bamControl for control reads. + output_prefix: Prefix for all output files (e.g., 'my_analysis'). + method: The differential analysis method to use. + Must be one of 'DBA_EDGER', 'DBA_DESEQ2', or 'DBA_LIMMA'. + fdr_threshold: FDR threshold for reporting significantly differentially + bound sites. + summits: Optional integer value. If set, peaks will be re-centered + around the point of greatest enrichment, with the size of the peak + extended to this value. If not provided, no re-centering is done. + min_overlap: The minimum number of peaksets a peak must be in to be + included in the global binding matrix. + use_summarize_overlaps: If True, use the more accurate but slower + `summarizeOverlaps` method for counting reads in peaks. + cores: Number of CPU cores to use for parallel processing. + plot_pca: If True, generate a PCA plot of the samples. + plot_heatmap: If True, generate a correlation heatmap. + plot_ma: If True, generate an MA plot for the contrast. + plot_volcano: If True, generate a volcano plot for the contrast. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not sample_sheet.is_file(): + raise FileNotFoundError(f"Sample sheet not found at: {sample_sheet}") + + allowed_methods = ["DBA_EDGER", "DBA_DESEQ2", "DBA_LIMMA"] + if method not in allowed_methods: + raise ValueError(f"Method must be one of {allowed_methods}, not '{method}'.") + + if not (0 < fdr_threshold <= 1): + raise ValueError("fdr_threshold must be between 0 and 1.") + + if cores < 1: + raise ValueError("cores must be a positive integer.") + + if summits is not None and summits <= 0: + raise ValueError("summits must be a positive integer if specified.") + + r_script_content = """ + suppressPackageStartupMessages(library(optparse)) + suppressPackageStartupMessages(library(DiffBind)) + suppressPackageStartupMessages(library(BiocParallel)) + + option_list <- list( + make_option(c("-s", "--sampleSheet"), type="character", default=NULL, + help="Path to the sample sheet CSV file", metavar="character"), + make_option(c("-o", "--outputPrefix"), type="character", default="diffbind_results", + help="Prefix for output files", metavar="character"), + make_option(c("-m", "--method"), type="character", default="DBA_DESEQ2", + help="Differential analysis method (DBA_EDGER, DBA_DESEQ2, DBA_LIMMA)", metavar="character"), + make_option(c("-t", "--threshold"), type="double", default=0.05, + help="FDR threshold for reporting", metavar="double"), + make_option(c("--summits"), type="integer", default=NULL, + help="Re-center peaks to this size. If not provided, no re-centering is done.", metavar="integer"), + make_option(c("--minOverlap"), type="integer", default=2, + help="Minimum overlap for consensus peaks", metavar="integer"), + make_option(c("--useSummarizeOverlaps"), action="store_true", default=FALSE, + help="Use SummarizeOverlaps for counting"), + make_option(c("--cores"), type="integer", default=1, + help="Number of cores for parallel processing", metavar="integer"), + make_option(c("--plotPCA"), action="store_true", default=FALSE, help="Generate PCA plot"), + make_option(c("--plotHeatmap"), action="store_true", default=FALSE, help="Generate correlation heatmap"), + make_option(c("--plotMA"), action="store_true", default=FALSE, help="Generate MA plot"), + make_option(c("--plotVolcano"), action="store_true", default=FALSE, help="Generate Volcano plot") + ) + + opt_parser <- OptionParser(option_list=option_list) + opt <- parse_args(opt_parser) + + if (is.null(opt$sampleSheet)){ + print_help(opt_parser) + stop("Sample sheet file must be supplied.", call.=FALSE) + } + + # Set up parallel processing + if (opt$cores > 1) { + register(MulticoreParam(workers = opt$cores)) + cat(paste("Using", opt$cores, "cores for parallel processing.\\n")) + } + + # 1. Load data + cat("Loading sample sheet...\\n") + samples <- read.csv(opt$sampleSheet) + dbObj <- dba(sampleSheet=samples) + + # 2. Count reads + cat("Counting reads...\\n") + count_summits_val <- if (is.null(opt$summits)) FALSE else opt$summits + dbObj <- dba.count(dbObj, summits=count_summits_val, bUseSummarizeOverlaps=opt$useSummarizeOverlaps) + + # 3. Normalize + cat("Normalizing data...\\n") + dbObj <- dba.normalize(dbObj) + + # 4. Establish contrast + cat("Establishing contrast...\\n") + dbObj <- dba.contrast(dbObj, minMembers=opt$minOverlap) + + # 5. Perform analysis + cat(paste("Performing differential analysis with", opt$method, "...\\n")) + analysis_method <- switch(opt$method, + "DBA_EDGER"=DBA_EDGER, + "DBA_DESEQ2"=DBA_DESEQ2, + "DBA_LIMMA"=DBA_LIMMA, + stop("Invalid method specified")) + dbObj <- dba.analyze(dbObj, method=analysis_method) + + # 6. Report results + cat("Generating report...\\n") + report <- dba.report(dbObj, th=opt$threshold) + if (!is.null(report)) { + report_df <- as.data.frame(report) + report_file <- paste0(opt$outputPrefix, "_differential_report.csv") + write.csv(report_df, file=report_file, row.names=FALSE) + cat(paste("Report saved to", report_file, "\\n")) + } else { + cat("No significant results to report.\\n") + } + + + # 7. Plotting + if (opt$plotPCA) { + cat("Generating PCA plot...\\n") + pdf(paste0(opt$outputPrefix, "_pca.pdf")) + dba.plotPCA(dbObj, label=DBA_ID) + dev.off() + } + + if (opt$plotHeatmap) { + cat("Generating correlation heatmap...\\n") + pdf(paste0(opt$outputPrefix, "_correlation_heatmap.pdf")) + dba.plotHeatmap(dbObj) + dev.off() + } + + if (opt$plotMA) { + cat("Generating MA plot...\\n") + pdf(paste0(opt$outputPrefix, "_ma_plot.pdf")) + dba.plotMA(dbObj) + dev.off() + } + + if (opt$plotVolcano) { + cat("Generating Volcano plot...\\n") + pdf(paste0(opt$outputPrefix, "_volcano_plot.pdf")) + dba.plotVolcano(dbObj) + dev.off() + } + + cat("DiffBind analysis complete.\\n") + """ + + output_files = [] + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as r_script: + r_script_path = r_script.name + r_script.write(r_script_content) + + try: + cmd = [ + "Rscript", + r_script_path, + "--sampleSheet", + str(sample_sheet), + "--outputPrefix", + output_prefix, + "--method", + method, + "--threshold", + str(fdr_threshold), + "--minOverlap", + str(min_overlap), + "--cores", + str(cores), + ] + + if summits is not None: + cmd.extend(["--summits", str(summits)]) + if use_summarize_overlaps: + cmd.append("--useSummarizeOverlaps") + if plot_pca: + cmd.append("--plotPCA") + if plot_heatmap: + cmd.append("--plotHeatmap") + if plot_ma: + cmd.append("--plotMA") + if plot_volcano: + cmd.append("--plotVolcano") + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + # Collect output files + report_file = Path(f"{output_prefix}_differential_report.csv") + if report_file.exists(): + output_files.append(str(report_file)) + if plot_pca: + output_files.append(f"{output_prefix}_pca.pdf") + if plot_heatmap: + output_files.append(f"{output_prefix}_correlation_heatmap.pdf") + if plot_ma: + output_files.append(f"{output_prefix}_ma_plot.pdf") + if plot_volcano: + output_files.append(f"{output_prefix}_volcano_plot.pdf") + + # Verify that plot files were created + verified_files = [f for f in output_files if Path(f).exists()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": verified_files, + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "DiffBind R script failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5d9a62f8fdb2232066170a010012510be2613f3e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/app/bioconductor-diffbind_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_diffbind' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..18b3fc5e962c25d0514a55227a62185efbc6e09a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-diffbind: + build: . + image: mcp-bioconductor-diffbind:latest + container_name: mcp-bioconductor-diffbind + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-diffbind + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..839a0d08388f697b8b465c52c817fde4915186d0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-diffbind + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-diffbind/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ce330750f20d1fec8196e0bc3c8a1de5fbd3e99 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomicfeatures via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomicfeatures -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomicfeatures_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomicfeatures_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomicfeatures_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/__pycache__/bioconductor-genomicfeatures_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/__pycache__/bioconductor-genomicfeatures_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1cd856cd7bd5a84420831111f768ccf19fcca24 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/__pycache__/bioconductor-genomicfeatures_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py new file mode 100644 index 0000000000000000000000000000000000000000..363bdf78d73781b0dd864e5ad440d07ec8286ac6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py @@ -0,0 +1,178 @@ +import subprocess +import tempfile +import shlex +from pathlib import Path +from typing import Optional, Dict, List + +# @mcp.tool() is a placeholder for the actual decorator. +# The code is written to be compatible with the MCP framework. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_genomicfeatures' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def make_txdb_from_gff( + gff_file: Path, + output_db_path: Path, + format: Optional[str] = None, + data_source: Optional[str] = None, + organism: Optional[str] = None, + taxonomy_id: Optional[int] = None, + chrominfo_file: Optional[Path] = None, + metadata_file: Optional[Path] = None, + pruning_mode: str = "coarse", + on_foreign_chrom: str = "abort", + infer_cds: bool = False, + infer_utr: bool = True, +) -> Dict: + """ + Creates a TranscriptDb (TxDb) SQLite database from a GFF or GTF file. + + This tool serves as a wrapper for the `makeTxDbFromGFF` function from the + R/Bioconductor GenomicFeatures package. It parses a gene annotation file + (GFF3 or GTF) and stores the transcript metadata in a structured SQLite + database, which is highly efficient for downstream analysis. + + Args: + gff_file: Path to the input GFF3 or GTF file. + output_db_path: Path where the output SQLite TxDb file will be saved. + format: The format of the input file. Can be 'gff3' or 'gtf'. + If not provided, the tool attempts to infer it from the file extension. + data_source: A string describing the source of the data (e.g., "Ensembl v104"). + organism: The scientific name of the organism (e.g., "Homo sapiens"). + taxonomy_id: The NCBI Taxonomy ID for the organism. + chrominfo_file: Optional path to a two-column, tab-separated file containing + chromosome names and their lengths. + metadata_file: Optional path to a two-column, tab-separated file containing + metadata as name-value pairs to be stored in the database. + pruning_mode: Sets the strictness for handling problematic transcripts. + Must be one of 'coarse', 'fine', or 'strict'. + on_foreign_chrom: Action to take for features on chromosomes not listed in + `chrominfo_file`. Must be one of 'abort', 'drop', or 'as.is'. + infer_cds: If TRUE, infer CDS features from annotated stop codons. + infer_utr: If TRUE, infer UTR features (5' and 3') when not explicitly provided. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a + mapping to the generated output database file. + """ + # 1. Input Validation + if not gff_file.is_file(): + raise FileNotFoundError(f"Input GFF/GTF file not found: {gff_file}") + + if chrominfo_file and not chrominfo_file.is_file(): + raise FileNotFoundError(f"Chrominfo file not found: {chrominfo_file}") + + if metadata_file and not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + + if format and format.lower() not in ["gff3", "gtf"]: + raise ValueError("Parameter 'format' must be either 'gff3' or 'gtf'.") + + allowed_pruning = ["coarse", "fine", "strict"] + if pruning_mode not in allowed_pruning: + raise ValueError(f"Parameter 'pruning_mode' must be one of {allowed_pruning}.") + + allowed_foreign_chrom = ["abort", "drop", "as.is"] + if on_foreign_chrom not in allowed_foreign_chrom: + raise ValueError(f"Parameter 'on_foreign_chrom' must be one of {allowed_foreign_chrom}.") + + output_db_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. R Script Generation + # Use R-friendly paths (forward slashes) for cross-platform compatibility + gff_file_r = str(gff_file).replace('\\', '/') + output_db_path_r = str(output_db_path).replace('\\', '/') + + r_script_lines = [ + "suppressPackageStartupMessages(library(GenomicFeatures))", + "", + "# Build the argument list for makeTxDbFromGFF", + f'txdb_args <- list(file = "{gff_file_r}")', + ] + + # Add optional arguments to the list + if format: + r_script_lines.append(f'txdb_args$format <- "{format.lower()}"') + if data_source: + r_script_lines.append(f'txdb_args$dataSource <- "{data_source}"') + if organism: + r_script_lines.append(f'txdb_args$organism <- "{organism}"') + if taxonomy_id is not None: + r_script_lines.append(f'txdb_args$taxonomyId <- {taxonomy_id}') + + r_script_lines.append(f'txdb_args$pruning.mode <- "{pruning_mode}"') + r_script_lines.append(f'txdb_args$on.foreign.chrom <- "{on_foreign_chrom}"') + r_script_lines.append(f'txdb_args$infer_cds <- {"TRUE" if infer_cds else "FALSE"}') + r_script_lines.append(f'txdb_args$infer_utr <- {"TRUE" if infer_utr else "FALSE"}') + + if chrominfo_file: + chrominfo_file_r = str(chrominfo_file).replace('\\', '/') + r_script_lines.extend([ + f'chrominfo_df <- read.table("{chrominfo_file_r}", sep="\\t", header=FALSE, col.names=c("chrom", "length"), stringsAsFactors=FALSE)', + 'txdb_args$chrominfo <- chrominfo_df' + ]) + + if metadata_file: + metadata_file_r = str(metadata_file).replace('\\', '/') + r_script_lines.extend([ + f'metadata_df <- read.table("{metadata_file_r}", sep="\\t", header=FALSE, col.names=c("name", "value"), stringsAsFactors=FALSE)', + 'txdb_args$metadata <- metadata_df' + ]) + + r_script_lines.extend([ + "", + "# Execute the function with the constructed arguments", + "txdb <- do.call(makeTxDbFromGFF, txdb_args)", + "", + "# Save the resulting database", + f'saveDb(txdb, file="{output_db_path_r}")', + 'message("TxDb database created successfully.")' + ]) + + r_script_content = "\n".join(r_script_lines) + + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + # 3. Subprocess Execution + cmd = ["Rscript", script_path] + command_executed = shlex.join(cmd) + + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"txdb_database": str(output_db_path)} + } + + except subprocess.CalledProcessError as e: + # R often prints errors to stdout, so combine them for a comprehensive message + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}\n" + ) + raise RuntimeError(error_message) from e + + finally: + # Clean up the temporary script file + if script_path and Path(script_path).exists(): + Path(script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1a1da4f2d1e41d1807c9abd124c323c7e5bad914 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_genomicfeatures' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ed64c15246a6e42f3ed448bcf13f62762db3b12 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomicfeatures: + build: . + image: mcp-bioconductor-genomicfeatures:latest + container_name: mcp-bioconductor-genomicfeatures + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomicfeatures + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..077be5894b7e52c31a6f405538213f1090d401b7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomicfeatures + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicfeatures/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a783e9fd7d22fd481ab343307f3a69bcaebf197c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomicranges via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomicranges -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomicranges_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomicranges_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomicranges_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/__pycache__/bioconductor-genomicranges_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/__pycache__/bioconductor-genomicranges_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c08ee76102246ea48759f99b312046f069b59d3 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/__pycache__/bioconductor-genomicranges_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6a8dacf47d1f5bce76ea29000a24a5a0f451fc1a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py @@ -0,0 +1,352 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any, Union + +def _run_r_command(r_code: str) -> Dict[str, Any]: + """ + Helper function to execute R code via Rscript. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + # Ensure GenomicRanges and rtracklayer are loaded + full_code = f"library(GenomicRanges); library(rtracklayer); {r_code}" + tmp.write(full_code) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "error_msg": str(e) + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_genomicranges' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def granges_reduce( + input_file: str, + output_file: str, + min_gapwidth: int = 1, + ignore_strand: bool = False, + with_revmap: bool = False +): + """ + Merge overlapping and adjacent genomic ranges into a single range. + Equivalent to GenomicRanges::reduce(). + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + reduced <- reduce(gr, min.gapwidth={min_gapwidth}, ignore.strand={str(ignore_strand).upper()}, with.revmap={str(with_revmap).upper()}) + export(reduced, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_intersect( + query_file: str, + subject_file: str, + output_file: str, + ignore_strand: bool = False +): + """ + Find the intersection of two sets of genomic ranges. + Equivalent to GenomicRanges::intersect(). + """ + for f in [query_file, subject_file]: + if not Path(f).exists(): + raise FileNotFoundError(f"File {f} not found.") + + r_code = f""" + q <- import("{query_file}") + s <- import("{subject_file}") + res <- intersect(q, s, ignore.strand={str(ignore_strand).upper()}) + export(res, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_union( + query_file: str, + subject_file: str, + output_file: str, + ignore_strand: bool = False +): + """ + Find the union of two sets of genomic ranges. + Equivalent to GenomicRanges::union(). + """ + for f in [query_file, subject_file]: + if not Path(f).exists(): + raise FileNotFoundError(f"File {f} not found.") + + r_code = f""" + q <- import("{query_file}") + s <- import("{subject_file}") + res <- union(q, s, ignore.strand={str(ignore_strand).upper()}) + export(res, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_setdiff( + query_file: str, + subject_file: str, + output_file: str, + ignore_strand: bool = False +): + """ + Find the set difference between two sets of genomic ranges (query - subject). + Equivalent to GenomicRanges::setdiff(). + """ + for f in [query_file, subject_file]: + if not Path(f).exists(): + raise FileNotFoundError(f"File {f} not found.") + + r_code = f""" + q <- import("{query_file}") + s <- import("{subject_file}") + res <- setdiff(q, s, ignore.strand={str(ignore_strand).upper()}) + export(res, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_find_overlaps( + query_file: str, + subject_file: str, + output_csv: str, + min_overlap: int = 1, + type: str = "any", + select: str = "all", + ignore_strand: bool = False +): + """ + Find overlaps between query and subject ranges. Returns a CSV of hit indices. + type: 'any', 'start', 'end', 'within', 'equal' + select: 'all', 'first', 'last', 'arbitrary' + """ + if type not in ["any", "start", "end", "within", "equal"]: + raise ValueError("Invalid type. Must be 'any', 'start', 'end', 'within', or 'equal'.") + if select not in ["all", "first", "last", "arbitrary"]: + raise ValueError("Invalid select. Must be 'all', 'first', 'last', or 'arbitrary'.") + + for f in [query_file, subject_file]: + if not Path(f).exists(): + raise FileNotFoundError(f"File {f} not found.") + + r_code = f""" + q <- import("{query_file}") + s <- import("{subject_file}") + hits <- findOverlaps(q, s, minoverlap={min_overlap}, type="{type}", select="{select}", ignore.strand={str(ignore_strand).upper()}) + if ("{select}" == "all") {{ + write.csv(as.data.frame(hits), "{output_csv}", row.names=FALSE) + }} else {{ + write.csv(data.frame(queryHits=seq_along(hits), subjectHits=hits), "{output_csv}", row.names=FALSE) + }} + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_csv] + return res + +@mcp.tool() +def granges_flank( + input_file: str, + output_file: str, + width: int, + start: bool = True, + both: bool = False, + ignore_strand: bool = False +): + """ + Generate flanking regions for each range. + width: width of the flank. + start: if True, flank the start; if False, flank the end. + both: if True, flank both sides. + """ + if width < 0: + raise ValueError("Width must be a non-negative integer.") + + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + flanked <- flank(gr, width={width}, start={str(start).upper()}, both={str(both).upper()}, ignore.strand={str(ignore_strand).upper()}) + export(flanked, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_resize( + input_file: str, + output_file: str, + width: int, + fix: str = "start", + ignore_strand: bool = False +): + """ + Resize genomic ranges to a specified width. + fix: 'start', 'end', or 'center' + """ + if fix not in ["start", "end", "center"]: + raise ValueError("fix must be 'start', 'end', or 'center'.") + if width < 0: + raise ValueError("Width must be a non-negative integer.") + + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + resized <- resize(gr, width={width}, fix="{fix}", ignore.strand={str(ignore_strand).upper()}) + export(resized, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_shift( + input_file: str, + output_file: str, + shift: int = 0 +): + """ + Shift genomic ranges by a specified number of nucleotides. + """ + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + shifted <- shift(gr, shift={shift}) + export(shifted, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_coverage( + input_file: str, + output_bw: str +): + """ + Calculate coverage across the genome and export as BigWig. + Note: Requires chromosome lengths to be present in the input or inferred. + """ + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + cov <- coverage(gr) + export(cov, "{output_bw}", format="bigWig") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_bw] + return res + +@mcp.tool() +def granges_gaps( + input_file: str, + output_file: str, + start: int = 1, + end: Optional[int] = None +): + """ + Find the gaps (uncovered regions) between ranges. + """ + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + end_val = f", end={end}" if end is not None else "" + + r_code = f""" + gr <- import("{input_file}") + gp <- gaps(gr, start={start}{end_val}) + export(gp, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_narrow( + input_file: str, + output_file: str, + start: int = 1, + end: Optional[int] = None, + width: Optional[int] = None +): + """ + Narrow genomic ranges by providing relative start/end/width. + """ + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + params = [f"start={start}"] + if end is not None: + params.append(f"end={end}") + if width is not None: + params.append(f"width={width}") + + param_str = ", ".join(params) + + r_code = f""" + gr <- import("{input_file}") + narrowed <- narrow(gr, {param_str}) + export(narrowed, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b0134b18102fe7dffc1443017be3b9790144ddfb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_genomicranges' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e81d4f5f098f9b6f1bc4fc6a0ce0235bf53b0514 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomicranges: + build: . + image: mcp-bioconductor-genomicranges:latest + container_name: mcp-bioconductor-genomicranges + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomicranges + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ffc91febb91701103946099d3bc44d0d4de7675 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomicranges + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicranges/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f2c0510d772e52fc655c301f1f3fd7380e937f81 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-hdf5array via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-hdf5array -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-hdf5array_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-hdf5array_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-hdf5array_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/__pycache__/bioconductor-hdf5array_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/__pycache__/bioconductor-hdf5array_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae4daac64d37229107f62e31e201970dc427a3aa Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/__pycache__/bioconductor-hdf5array_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a4048de346ad70d73d03a0fc0339fb993b097ab8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py @@ -0,0 +1,460 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Dict, List, Optional, Union + +# MCP decorator is not defined in this context, so we'll use a placeholder. +# In a real MCP environment, this would be: from mcp import tool +class mcp: + def tool(func): + return func + +@mcp.tool +def write_hdf5_array( + input_file: Path, + output_hdf5: Path, + dataset_name: str, + input_format: str = "csv", + chunk_dim: Optional[str] = None, + compression_level: int = 6, + as_integer: bool = False, + csv_header: bool = True, + csv_row_names_col: Optional[int] = 1, +) -> Dict[str, Union[str, Dict[str, str]]]: + """ + Converts a data file (CSV, TSV, or RDS) into an HDF5 file using HDF5Array. + + This tool is a wrapper around the HDF5Array::writeHDF5Array R function. + It requires R and the Bioconductor 'HDF5Array' package to be installed. + """ + # 1. Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not output_hdf5.parent.exists(): + raise FileNotFoundError(f"Output directory does not exist: {output_hdf5.parent}") + if input_format not in ["csv", "tsv", "rds"]: + raise ValueError("input_format must be one of 'csv', 'tsv', or 'rds'.") + if not (0 <= compression_level <= 9): + raise ValueError("compression_level must be between 0 and 9.") + if chunk_dim: + try: + [int(d) for d in chunk_dim.split(',')] + except ValueError: + raise ValueError("chunk_dim must be a comma-separated string of integers (e.g., '100,1000').") + + # 2. R script for execution + r_script_content = textwrap.dedent(""" + suppressPackageStartupMessages({ + library(optparse) + library(HDF5Array) + }) + + option_list <- list( + make_option("--input", type="character", help="Input file path (CSV, TSV, or RDS)."), + make_option("--output", type="character", help="Output HDF5 file path."), + make_option("--name", type="character", help="Name for the dataset within the HDF5 file."), + make_option("--format", type="character", default="csv", help="Input file format [csv, tsv, rds]."), + make_option("--chunkdim", type="character", default=NULL, help="Comma-separated chunk dimensions."), + make_option("--level", type="integer", default=6, help="Compression level (0-9)."), + make_option("--as_integer", action="store_true", default=FALSE, help="Coerce data to integer."), + make_option("--header", action="store_true", default=TRUE, help="Does the CSV/TSV have a header?"), + make_option("--rownames", type="integer", default=NULL, help="Column number for row names in CSV/TSV.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + # Read input data + message("Reading input file: ", args$input) + if (args$format == "rds") { + data_matrix <- readRDS(args$input) + } else if (args$format == "csv") { + data_matrix <- read.csv(args$input, header=args$header, row.names=args$rownames, check.names=FALSE) + } else if (args$format == "tsv") { + data_matrix <- read.delim(args$input, header=args$header, row.names=args$rownames, check.names=FALSE) + } else { + stop("Unsupported format: ", args$format) + } + + if (!is.matrix(data_matrix)) { + message("Input data is not a matrix, coercing...") + data_matrix <- as.matrix(data_matrix) + } + + if (args$as_integer) { + message("Coercing data to integer...") + storage.mode(data_matrix) <- "integer" + } + + # Parse chunk dimensions + chunk_dims <- NULL + if (!is.null(args$chunkdim)) { + chunk_dims <- as.integer(strsplit(args$chunkdim, ",")[[1]]) + message("Using chunk dimensions: ", paste(chunk_dims, collapse=", ")) + } + + # Write HDF5 array + message("Writing HDF5 array to: ", args$output) + writeHDF5Array( + x = data_matrix, + filepath = args$output, + name = args$name, + chunkdim = chunk_dims, + level = args$level, + with.dimnames = TRUE, + verbose = TRUE + ) + message("Successfully created HDF5 file.") + """) + + # 3. Subprocess execution + cmd = [ + "Rscript", "-", + "--input", str(input_file), + "--output", str(output_hdf5), + "--name", dataset_name, + "--format", input_format, + "--level", str(compression_level), + ] + if chunk_dim: + cmd.extend(["--chunkdim", chunk_dim]) + if as_integer: + cmd.append("--as_integer") + if csv_header: + cmd.append("--header") + if csv_row_names_col is not None: + cmd.extend(["--rownames", str(csv_row_names_col)]) + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_file.flush() + + # Rebuild command to use the script file + cmd[1] = r_script_file.name + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"output_hdf5": str(output_hdf5)}, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"HDF5Array R script failed with exit code {e.returncode}.\n" + f"This may be due to missing R packages ('optparse', 'HDF5Array').\n" + f"Please install them in R using:\n" + f"install.packages('optparse')\n" + f"if (!requireNamespace('BiocManager', quietly = TRUE)) install.packages('BiocManager')\n" + f"BiocManager::install('HDF5Array')\n\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + + +@mcp.tool +def save_hdf5_summarized_experiment( + input_rds: Path, + output_dir: Path, + prefix: Optional[str] = None, + replace: bool = False, +) -> Dict[str, Union[str, Dict[str, str]]]: + """ + Saves a SummarizedExperiment object from an RDS file to an HDF5-backed format. + + This tool wraps the HDF5Array::saveHDF5SummarizedExperiment R function. + It requires R and the Bioconductor packages 'HDF5Array' and 'SummarizedExperiment'. + """ + # 1. Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if output_dir.exists() and not output_dir.is_dir(): + raise ValueError(f"Output path exists but is not a directory: {output_dir}") + if output_dir.exists() and any(output_dir.iterdir()) and not replace: + raise FileExistsError(f"Output directory {output_dir} is not empty. Use replace=True to overwrite.") + + output_dir.mkdir(parents=True, exist_ok=True) + + # 2. R script for execution + r_script_content = textwrap.dedent(""" + suppressPackageStartupMessages({ + library(optparse) + library(HDF5Array) + library(SummarizedExperiment) + }) + + option_list <- list( + make_option("--input", type="character", help="Input RDS file containing a SummarizedExperiment object."), + make_option("--outdir", type="character", help="Output directory to save the HDF5SummarizedExperiment."), + make_option("--prefix", type="character", default=NULL, help="Optional prefix for file names."), + make_option("--replace", action="store_true", default=FALSE, help="Replace existing directory content.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + message("Reading SummarizedExperiment object from: ", args$input) + se <- readRDS(args$input) + + if (!is(se, "SummarizedExperiment")) { + stop("The object in the RDS file is not a SummarizedExperiment.") + } + + message("Saving HDF5SummarizedExperiment to: ", args$outdir) + saveHDF5SummarizedExperiment( + x = se, + dir = args$outdir, + prefix = args$prefix, + replace = args$replace, + verbose = TRUE + ) + message("Successfully saved HDF5SummarizedExperiment.") + """) + + # 3. Subprocess execution + cmd = [ + "Rscript", "-", + "--input", str(input_rds), + "--outdir", str(output_dir), + ] + if prefix: + cmd.extend(["--prefix", prefix]) + if replace: + cmd.append("--replace") + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_file.flush() + + cmd[1] = r_script_file.name + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"output_directory": str(output_dir)}, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"HDF5Array R script failed with exit code {e.returncode}.\n" + f"This may be due to missing R packages ('optparse', 'HDF5Array', 'SummarizedExperiment').\n" + f"Please install them in R using BiocManager.\n\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + + +@mcp.tool +def export_hdf5_summarized_experiment( + input_dir: Path, + output_dir: Path, + assay_names: Optional[str] = None, + export_coldata: bool = True, + export_rowdata: bool = True, +) -> Dict[str, Union[str, Dict[str, str]]]: + """ + Loads an HDF5SummarizedExperiment and exports its components to CSV files. + + This tool wraps HDF5Array::loadHDF5SummarizedExperiment and exports data. + Requires R and the Bioconductor packages 'HDF5Array' and 'SummarizedExperiment'. + """ + # 1. Input validation + if not input_dir.is_dir(): + raise FileNotFoundError(f"Input directory not found: {input_dir}") + if output_dir.exists() and not output_dir.is_dir(): + raise ValueError(f"Output path exists but is not a directory: {output_dir}") + + output_dir.mkdir(parents=True, exist_ok=True) + + # 2. R script for execution + r_script_content = textwrap.dedent(""" + suppressPackageStartupMessages({ + library(optparse) + library(HDF5Array) + library(SummarizedExperiment) + }) + + option_list <- list( + make_option("--indir", type="character", help="Input directory of the HDF5SummarizedExperiment."), + make_option("--outdir", type="character", help="Output directory for exported CSV files."), + make_option("--assays", type="character", default=NULL, help="Comma-separated list of assays to export (default: all)."), + make_option("--coldata", action="store_true", default=FALSE, help="Export colData to CSV."), + make_option("--rowdata", action="store_true", default=FALSE, help="Export rowData to CSV.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + message("Loading HDF5SummarizedExperiment from: ", args$indir) + se <- loadHDF5SummarizedExperiment(dir = args$indir) + + assays_to_export <- assayNames(se) + if (!is.null(args$assays)) { + assays_to_export <- intersect(assays_to_export, strsplit(args$assays, ",")[[1]]) + } + + if (length(assays_to_export) > 0) { + for (aname in assays_to_export) { + message("Exporting assay: ", aname) + out_path <- file.path(args$outdir, paste0("assay_", aname, ".csv")) + mat <- as.matrix(assay(se, aname)) + write.csv(mat, file=out_path, quote=FALSE, row.names=TRUE) + } + } + + if (args$coldata) { + message("Exporting colData") + out_path <- file.path(args$outdir, "coldata.csv") + write.csv(as.data.frame(colData(se)), file=out_path, quote=FALSE, row.names=TRUE) + } + + if (args$rowdata) { + message("Exporting rowData") + out_path <- file.path(args$outdir, "rowdata.csv") + write.csv(as.data.frame(rowData(se)), file=out_path, quote=FALSE, row.names=TRUE) + } + + message("Export complete.") + """) + + # 3. Subprocess execution + cmd = [ + "Rscript", "-", + "--indir", str(input_dir), + "--outdir", str(output_dir), + ] + if assay_names: + cmd.extend(["--assays", assay_names]) + if export_coldata: + cmd.append("--coldata") + if export_rowdata: + cmd.append("--rowdata") + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_file.flush() + + cmd[1] = r_script_file.name + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [str(p) for p in output_dir.glob("*.csv")] + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"output_directory": str(output_dir), "exported_files": output_files}, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"HDF5Array R script failed with exit code {e.returncode}.\n" + f"This may be due to missing R packages or an invalid HDF5SummarizedExperiment directory.\n\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + + +@mcp.tool +def inspect_hdf5_array( + input_hdf5: Path, + dataset_name: str, +) -> Dict[str, str]: + """ + Inspects an HDF5 file and prints properties of a specific HDF5Array dataset. + + This tool provides information like dimensions and chunking without loading data. + Requires R and the Bioconductor 'HDF5Array' package. + """ + # 1. Input validation + if not input_hdf5.exists(): + raise FileNotFoundError(f"Input HDF5 file not found: {input_hdf5}") + + # 2. R script for execution + r_script_content = textwrap.dedent(""" + suppressPackageStartupMessages({ + library(optparse) + library(HDF5Array) + }) + + option_list <- list( + make_option("--file", type="character", help="Input HDF5 file path."), + make_option("--name", type="character", help="Name of the dataset to inspect.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + # Load the HDF5 array seed + HDF5_dataset <- HDF5Array(args$file, args$name) + + # Print properties + cat("Dataset:", name(HDF5_dataset), "\\n") + cat("Filepath:", path(HDF5_dataset), "\\n") + cat("Dimensions:", paste(dim(HDF5_dataset), collapse=" x "), "\\n") + cat("Datatype:", class(HDF5_dataset@seed@first_val), "\\n") + cat("Chunking:", paste(chunkdim(HDF5_dataset), collapse=" x "), "\\n") + """) + + # 3. Subprocess execution + cmd = [ + "Rscript", "-", + "--file", str(input_hdf5), + "--name", dataset_name, + ] + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_file.flush() + + cmd[1] = r_script_file.name + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"HDF5Array R script failed with exit code {e.returncode}.\n" + f"This may be due to a missing R package, an incorrect file path, or a non-existent dataset name ('{dataset_name}').\n\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c526f717b855e99523f2e5f0f4750bdb38529269 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_hdf5array' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..97bfa9f0817812b9b034da837a26e1ca56d332f8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-hdf5array: + build: . + image: mcp-bioconductor-hdf5array:latest + container_name: mcp-bioconductor-hdf5array + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-hdf5array + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d5fae2ca90a31c0f18e23fab27e79852206c4dc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-hdf5array + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-hdf5array/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ba94b99931ffc59e28a5684f5d74096eb1da097e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-imcrtools via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-imcrtools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-imcrtools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-imcrtools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-imcrtools_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/__pycache__/bioconductor-imcrtools_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/__pycache__/bioconductor-imcrtools_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2783085e087fc0f5c51d322ea2c9a7a3758de05f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/__pycache__/bioconductor-imcrtools_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ecc94bf786e53e1930adf5ddb2ea986f3ec200 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py @@ -0,0 +1,425 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Literal, List +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_imcrtools' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def build_spatial_graph( + input_object: Path, + output_rds: Path, + img_id: str, + type: Literal["knn", "delaunay", "expansion", "voronoi"], + k: Optional[int] = 5, + max_dist: Optional[float] = None, + directed: bool = False, + name: str = "spatial_graph", +) -> dict: + """ + Constructs a spatial graph to represent cell-cell interactions. + + This function builds a graph where nodes are cells and edges represent spatial proximity. + The graph is added to the colPair slot of the SpatialExperiment object. + + Args: + input_object: Path to the input SpatialExperiment object in RDS format. + output_rds: Path to save the output SpatialExperiment object with the graph in RDS format. + img_id: The column name in colData that identifies images. Graphs are built per image. + type: The type of graph to build. + k: The number of nearest neighbors for the 'knn' graph type. + max_dist: The maximum distance for graph construction using the 'expansion' type. + directed: Should the graph be directed? Defaults to FALSE. + name: The name under which to store the graph in the colPair slot. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # Input validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + if type == "knn" and (k is None or k <= 0): + raise ValueError("Parameter 'k' must be a positive integer for 'knn' graph type.") + if type == "expansion" and (max_dist is None or max_dist <= 0): + raise ValueError("Parameter 'max_dist' must be a positive float for 'expansion' graph type.") + + r_script_content = f""" + library(imcRtools) + library(SpatialExperiment) + library(S4Vectors) + library(igraph) + + args <- commandArgs(trailingOnly=TRUE) + input_rds_path <- args[1] + output_rds_path <- args[2] + p_img_id <- args[3] + p_type <- args[4] + p_k <- if (args[5] == "NULL") NULL else as.integer(args[5]) + p_max_dist <- if (args[6] == "NULL") NULL else as.numeric(args[6]) + p_directed <- as.logical(args[7]) + p_name <- args[8] + + spe <- readRDS(input_rds_path) + + spe <- buildSpatialGraph(spe, + img_id = p_img_id, + type = p_type, + k = p_k, + max_dist = p_max_dist, + directed = p_directed, + name = p_name) + + saveRDS(spe, file = output_rds_path) + """ + + cmd_args = [ + str(input_object), + str(output_rds), + img_id, + type, + str(k) if k is not None else "NULL", + str(max_dist) if max_dist is not None else "NULL", + "TRUE" if directed else "FALSE", + name, + ] + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + cmd_args + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + logging.info(f"Successfully built spatial graph for {input_object}") + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Error in build_spatial_graph: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def aggregate_neighbors( + input_object: Path, + output_rds: Path, + col_pair_name: str, + aggregate_by: Literal["metadata", "expression"], + count_by: Optional[str] = None, + assay_type: str = "counts", + name: str = "aggregated_neighbors", +) -> dict: + """ + Aggregates features of neighboring cells for each cell. + + This function summarizes information from neighboring cells, such as cell types or + mean marker expression, and adds it to the colData of the SpatialExperiment object. + + Args: + input_object: Path to the input SpatialExperiment object (RDS format) containing a spatial graph. + output_rds: Path to save the updated SpatialExperiment object (RDS format). + col_pair_name: The name of the graph in colPair(object) to use for aggregation. + aggregate_by: Whether to aggregate cell 'metadata' (e.g., cell types) or marker 'expression'. + count_by: If aggregating by metadata, the colData column to use for counting (e.g., 'cell_type'). + assay_type: If aggregating by expression, the assay to use for summarization. + name: The name for the output data frame in colData(object). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # Input validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + if aggregate_by == "metadata" and count_by is None: + raise ValueError("Parameter 'count_by' must be specified when 'aggregate_by' is 'metadata'.") + + r_script_content = f""" + library(imcRtools) + library(SpatialExperiment) + + args <- commandArgs(trailingOnly=TRUE) + input_rds_path <- args[1] + output_rds_path <- args[2] + p_col_pair_name <- args[3] + p_aggregate_by <- args[4] + p_count_by <- if (args[5] == "NULL") NULL else args[5] + p_assay_type <- args[6] + p_name <- args[7] + + spe <- readRDS(input_rds_path) + + spe <- aggregateNeighbors(spe, + colPairName = p_col_pair_name, + aggregate_by = p_aggregate_by, + count_by = p_count_by, + assay_type = p_assay_type, + name = p_name) + + saveRDS(spe, file = output_rds_path) + """ + + cmd_args = [ + str(input_object), + str(output_rds), + col_pair_name, + aggregate_by, + count_by if count_by is not None else "NULL", + assay_type, + name, + ] + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + cmd_args + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + logging.info(f"Successfully aggregated neighbors for {input_object}") + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Error in aggregate_neighbors: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def test_interactions( + input_object: Path, + output_csv: Path, + group_by: str, + label: str, + col_pair_name: str = "spatial_graph", + method: Literal["classic", "histocat", "patch"] = "classic", + permutations: int = 1000, + p_adjust_method: str = "BH", +) -> dict: + """ + Performs permutation testing to find significant cell-cell interactions. + + This function tests for spatial attraction or avoidance between cell types by comparing + observed interaction counts to a null distribution generated by permuting cell labels. + + Args: + input_object: Path to the input SpatialExperiment object (RDS format). + output_csv: Path to save the interaction testing results as a CSV file. + group_by: The colData column for grouping images before testing (e.g., patient ID). + label: The colData column containing cell type labels. + col_pair_name: The name of the graph in colPair(object) to use. + method: The permutation method to use. + permutations: The number of permutations to perform. + p_adjust_method: Method for multiple testing correction. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output CSV file. + """ + # Input validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + if permutations <= 0: + raise ValueError("Number of permutations must be a positive integer.") + + r_script_content = f""" + library(imcRtools) + library(SpatialExperiment) + library(data.table) + + args <- commandArgs(trailingOnly=TRUE) + input_rds_path <- args[1] + output_csv_path <- args[2] + p_group_by <- args[3] + p_label <- args[4] + p_col_pair_name <- args[5] + p_method <- args[6] + p_permutations <- as.integer(args[7]) + p_p_adjust_method <- args[8] + + spe <- readRDS(input_rds_path) + + interaction_results <- testInteractions(spe, + group_by = p_group_by, + label = p_label, + colPairName = p_col_pair_name, + method = p_method, + permutations = p_permutations, + p_adjust_method = p_p_adjust_method) + + fwrite(interaction_results, file = output_csv_path) + """ + + cmd_args = [ + str(input_object), + str(output_csv), + group_by, + label, + col_pair_name, + method, + str(permutations), + p_adjust_method, + ] + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + cmd_args + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + logging.info(f"Successfully tested interactions for {input_object}") + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_csv)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Error in test_interactions: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def plot_spatial_graph( + input_object: Path, + output_image: Path, + img_id: str, + node_color_by: Optional[str] = None, + node_shape_by: Optional[str] = None, + node_size_by: Optional[str] = None, + col_pair_name: str = "spatial_graph", + draw_edges: bool = True, + directed: bool = False, +) -> dict: + """ + Visualizes the spatial graph for a specific image. + + This function generates a plot of cells (nodes) and their spatial interactions (edges) + for a single image ID. + + Args: + input_object: Path to the input SpatialExperiment object (RDS format). + output_image: Path to save the output plot (e.g., plot.png, plot.pdf). + img_id: The specific image ID to plot from the 'img_id' column used in build_spatial_graph. + node_color_by: The colData column to color nodes by (e.g., 'cell_type'). + node_shape_by: The colData column to shape nodes by. + node_size_by: The colData column to size nodes by. + col_pair_name: The name of the graph to visualize. + draw_edges: Whether to draw the edges of the graph. + directed: Are the edges directed? Passed to ggraph. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output image file. + """ + # Input validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + if not output_image.suffix in [".png", ".pdf", ".svg", ".jpeg", ".tiff"]: + raise ValueError("Output image format must be one of: .png, .pdf, .svg, .jpeg, .tiff") + + r_script_content = f""" + library(imcRtools) + library(SpatialExperiment) + library(ggplot2) + + args <- commandArgs(trailingOnly=TRUE) + input_rds_path <- args[1] + output_image_path <- args[2] + p_img_id <- args[3] + p_node_color_by <- if (args[4] == "NULL") NULL else args[4] + p_node_shape_by <- if (args[5] == "NULL") NULL else args[5] + p_node_size_by <- if (args[6] == "NULL") NULL else args[6] + p_col_pair_name <- args[7] + p_draw_edges <- as.logical(args[8]) + p_directed <- as.logical(args[9]) + + spe <- readRDS(input_rds_path) + + p <- plotSpatialGraph(spe, + img_id = p_img_id, + node_color_by = p_node_color_by, + node_shape_by = p_node_shape_by, + node_size_by = p_node_size_by, + colPairName = p_col_pair_name, + draw_edges = p_draw_edges, + directed = p_directed) + + ggsave(output_image_path, plot = p, width = 10, height = 10) + """ + + cmd_args = [ + str(input_object), + str(output_image), + img_id, + node_color_by if node_color_by is not None else "NULL", + node_shape_by if node_shape_by is not None else "NULL", + node_size_by if node_size_by is not None else "NULL", + col_pair_name, + "TRUE" if draw_edges else "FALSE", + "TRUE" if directed else "FALSE", + ] + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + cmd_args + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + logging.info(f"Successfully plotted spatial graph for image {img_id}") + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_image)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Error in plot_spatial_graph: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") + finally: + Path(r_script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0b50a73b88d76ed4c39cb3a561aa40cb59762736 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_imcrtools' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..54888b25732061ffab696c3587f02a60521a4730 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-imcrtools: + build: . + image: mcp-bioconductor-imcrtools:latest + container_name: mcp-bioconductor-imcrtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-imcrtools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4bc94537dfa36fb7175c850db3ec2ee151d5dc7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-imcrtools + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-imcrtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e30f96079a8c672ae33bcfb5e72ab1ed0a42a4cc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-irisfgm via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-irisfgm -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-irisfgm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-irisfgm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-irisfgm_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/app/__pycache__/bioconductor-irisfgm_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/app/__pycache__/bioconductor-irisfgm_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2ff4ccd47aed0250e3cc4e7a0e9492271f4d290 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/app/__pycache__/bioconductor-irisfgm_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c798a7de6725fc156b1af9cf963158a092131d4e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py @@ -0,0 +1,183 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_irisfgm' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_irisfgm_script( + r_script_content: str, + output_dir: Path = Path("./"), + r_environment_setup_script: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes an R script that utilizes the bioconductor-irisfgm package. + + The bioconductor-irisfgm tool is an R package designed for comprehensive + analysis of gene interactivity networks based on single-cell RNA-Seq data. + As the provided documentation does not expose a direct command-line + interface with specific subcommands and parameters, this MCP tool provides + a generic entry point to execute arbitrary R code that leverages the IRISFGM + package. + + Users are expected to provide an R script that loads the IRISFGM package + and calls its internal functions as needed. The R script should be written + to save any desired output files to the directory specified by the + 'OUTPUT_DIR' environment variable, which corresponds to the `output_dir` + parameter. + + Example R script content: + ```R + # Load the IRISFGM package + library(IRISFGM) + + # --- Placeholder for actual IRISFGM function calls --- + # In a real scenario, you would load your actual scRNA-seq data + # (e.g., from a CSV, TSV, or a Seurat object) and then apply IRISFGM functions. + # + # Example: Create a dummy SingleCellExperiment object for demonstration + # library(SingleCellExperiment) + # counts <- matrix(rnbinom(1000, mu=10, size=1), ncol=10) + # rownames(counts) <- paste0("gene", 1:100) + # colnames(counts) <- paste0("cell", 1:10) + # sce <- SingleCellExperiment(assays=list(counts=counts)) + # + # Example of a hypothetical IRISFGM function call (replace with actual functions): + # fgms_result <- IRISFGM::identifyFGMs(sce_object, ...) + # + # Print some output to stdout + message("IRISFGM R script executed successfully.") + # + # Save results to a file in the output directory + # output_dir <- Sys.getenv("OUTPUT_DIR") + # if (!is.null(output_dir) && dir.exists(output_dir)) { + # write.csv(data.frame(gene="gene1", value=10), file = file.path(output_dir, "example_output.csv")) + # message(paste("Saved example_output.csv to", output_dir)) + # } else { + # warning("OUTPUT_DIR environment variable not set or directory does not exist.") + # } + ``` + + Args: + r_script_content: A string containing the R script to be executed. + This script should include calls to IRISFGM functions. + output_dir: The directory where any output files generated by the R script + should be stored. The R script should be written to save + files to this directory (e.g., using `file.path(Sys.getenv("OUTPUT_DIR"), "filename")`). + Defaults to the current working directory. + r_environment_setup_script: Optional R script content to run before the main + `r_script_content`. This can be used for + environment setup, installing packages, etc., + if not handled by the container. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of any output files generated. + """ + if not r_script_content: + raise ValueError("R script content cannot be empty.") + + # Ensure the output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + command_executed: List[str] = [] + stdout: str = "" + stderr: str = "" + output_files: List[Path] = [] + + with tempfile.TemporaryDirectory() as tmpdir: + temp_dir_path = Path(tmpdir) + r_script_path = temp_dir_path / "main_script.R" + setup_script_path: Optional[Path] = None + + # Write the main R script content to a temporary file + with open(r_script_path, "w") as f: + f.write(r_script_content) + + # Prepare environment variables for the R process + env_vars = {"OUTPUT_DIR": str(output_dir)} + + # If an R environment setup script is provided, execute it first + if r_environment_setup_script: + setup_script_path = temp_dir_path / "setup_script.R" + with open(setup_script_path, "w") as f: + f.write(r_environment_setup_script) + setup_command = ["Rscript", str(setup_script_path)] + command_executed.append(" ".join(setup_command)) + try: + setup_result = subprocess.run( + setup_command, + capture_output=True, + text=True, + check=True, + env={**subprocess.os.environ, **env_vars} # Merge with current environment + ) + stdout += f"Setup script stdout:\n{setup_result.stdout}\n" + stderr += f"Setup script stderr:\n{setup_result.stderr}\n" + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(setup_command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R setup script failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(setup_command), + "stdout": "", + "stderr": "Error: Rscript command not found. Is R installed and in PATH?", + "error": "Rscript not found for setup script", + "output_files": [], + } + + # Execute the main R script + r_command = ["Rscript", str(r_script_path)] + command_executed.append(" ".join(r_command)) + + try: + result = subprocess.run( + r_command, + capture_output=True, + text=True, + check=True, + env={**subprocess.os.environ, **env_vars} # Merge with current environment + ) + stdout += result.stdout + stderr += result.stderr + + # Collect output files from the specified output_dir + for f in output_dir.iterdir(): + if f.is_file(): + output_files.append(f) + + except subprocess.CalledProcessError as e: + return { + "command_executed": "\n".join(command_executed), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": "\n".join(command_executed), + "stdout": "", + "stderr": "Error: Rscript command not found. Is R installed and in PATH?", + "error": "Rscript not found for main script", + "output_files": [], + } + + return { + "command_executed": "\n".join(command_executed), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..157ce2bc46e4b72dfc669514aeb94d7cfd931a8e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_irisfgm' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6ec8f6a1ced45007183fe46de3573b1d37550d46 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-irisfgm: + build: . + image: mcp-bioconductor-irisfgm:latest + container_name: mcp-bioconductor-irisfgm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-irisfgm + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca7f25d8bc352e903a8fc4e77bb5c0eba53afd37 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-irisfgm + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-irisfgm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5c6a2b29f342a8ea28bc8a1d8f2327a8ed77fc1c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-metapod via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-metapod -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-metapod_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-metapod_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-metapod_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/__pycache__/bioconductor-metapod_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/__pycache__/bioconductor-metapod_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7484ab8dea782b26987aef64be8792d44970120 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/__pycache__/bioconductor-metapod_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f48df88b46b0abeb0c407bf5d0c468cb8ec8f8b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py @@ -0,0 +1,330 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import List, Optional, Dict, Any + +# No need to import mcp as per instructions + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_metapod' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def combine_p_values( + p_values_file: Path, + output_file: Path, + weights_file: Optional[Path] = None, + method: str = "fisher", + log_p: bool = False, + na_rm: bool = False, + min_p: float = 0.0, + max_p: float = 1.0, + input_sep: str = ",", + input_header: bool = False, +) -> Dict[str, Any]: + """ + Combines p-values from differential analyses using various meta-analysis methods + provided by the bioconductor-metapod R package. + + This function wraps the `metapod::combinePValues` R function. It supports combining + a single vector of p-values or multiple sets of p-values (e.g., from different tests). + + Args: + p_values_file: Path to a file containing p-values. Each row should represent + a set of p-values to be combined. For a single vector of p-values, + the file can have one column. For multiple sets, it can have + multiple columns. + output_file: Path to the output file where the combined p-values will be written. + The output will be a CSV file. + weights_file: Optional path to a file containing weights corresponding to the p-values. + Must have the same structure (number of rows/columns) as `p_values_file`. + method: The method to use for combining p-values. + Allowed values: "fisher", "stouffer", "simes", "davies", "whitlock", + "fdr", "bonferroni", "none". + log_p: If TRUE, p-values are assumed to be log-transformed. + na_rm: If TRUE, NA p-values are removed before combination. + min_p: Minimum p-value to consider. Values below this will be set to min_p. + Must be between 0 and 1. + max_p: Maximum p-value to consider. Values above this will be set to max_p. + Must be between 0 and 1. + input_sep: The field separator character for input p-values and weights files. + Common values are "," for CSV and "\\t" for TSV. + input_header: If TRUE, the input p-values and weights files are assumed to have a header row. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not p_values_file.is_file(): + raise FileNotFoundError(f"Input p-values file not found: {p_values_file}") + if weights_file and not weights_file.is_file(): + raise FileNotFoundError(f"Input weights file not found: {weights_file}") + + if not (0.0 <= min_p <= 1.0): + raise ValueError("min_p must be between 0 and 1.") + if not (0.0 <= max_p <= 1.0): + raise ValueError("max_p must be between 0 and 1.") + if min_p > max_p: + raise ValueError("min_p cannot be greater than max_p.") + + allowed_methods = ["fisher", "stouffer", "simes", "davies", "whitlock", "fdr", "bonferroni", "none"] + if method not in allowed_methods: + raise ValueError(f"Invalid method: '{method}'. Must be one of {allowed_methods}") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Convert boolean to R's TRUE/FALSE + r_log_p = str(log_p).upper() + r_na_rm = str(na_rm).upper() + r_input_header = str(input_header).upper() + + # Create a temporary R script + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as r_script_temp: + r_script_path = Path(r_script_temp.name) + r_script_temp.write(f""" + library(metapod) + + # Read p-values + p_values_data <- read.csv( + "{p_values_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + ) + # metapod::combinePValues expects a numeric vector or a list of numeric vectors. + # If p_values_data is a data.frame, we convert it to a list of vectors (columns) + # or assume it's a single vector if it has one column. + if (ncol(p_values_data) == 1) {{ + p_values_input <- as.numeric(p_values_data[[1]]) + }} else {{ + p_values_input <- lapply(p_values_data, as.numeric) + }} + + weights_input <- NULL + if (!is.null("{weights_file}")) {{ + weights_data <- read.csv( + "{weights_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + ) + if (ncol(weights_data) == 1) {{ + weights_input <- as.numeric(weights_data[[1]]) + }} else {{ + weights_input <- lapply(weights_data, as.numeric) + }} + }} + + # Call combinePValues + combined_p_values <- metapod::combinePValues( + p.values = p_values_input, + weights = weights_input, + method = "{method}", + log.p = {r_log_p}, + na.rm = {r_na_rm}, + min.p = {min_p}, + max.p = {max_p} + ) + + # Write results to output file + write.csv(combined_p_values, file = "{output_file}", row.names = FALSE) + """) + + command = ["Rscript", str(r_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # Clean up the temporary script even if an error occurs + os.remove(r_script_path) + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [], + } + finally: + # Clean up the temporary R script + if r_script_path.exists(): + os.remove(r_script_path) + + if not output_file.is_file(): + stderr += f"\nError: Expected output file '{output_file}' was not created." + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_file)], + } + + +@mcp.tool() +def grouped_p_values( + p_values_file: Path, + groups_file: Path, + output_file: Path, + weights_file: Optional[Path] = None, + method: str = "fisher", + log_p: bool = False, + na_rm: bool = False, + min_p: float = 0.0, + max_p: float = 1.0, + input_sep: str = ",", + input_header: bool = False, +) -> Dict[str, Any]: + """ + Combines p-values within specified groups using various meta-analysis methods + provided by the bioconductor-metapod R package. + + This function wraps the `metapod::groupedPValues` R function. It requires a + separate file for group assignments for each p-value. + + Args: + p_values_file: Path to a file containing a single column of p-values. + groups_file: Path to a file containing a single column of group identifiers, + corresponding to each p-value in `p_values_file`. + output_file: Path to the output file where the combined p-values will be written. + The output will be a CSV file. + weights_file: Optional path to a file containing a single column of weights + corresponding to the p-values. + method: The method to use for combining p-values within groups. + Allowed values: "fisher", "stouffer", "simes", "davies", "whitlock", + "fdr", "bonferroni", "none". + log_p: If TRUE, p-values are assumed to be log-transformed. + na_rm: If TRUE, NA p-values are removed before combination. + min_p: Minimum p-value to consider. Values below this will be set to min_p. + Must be between 0 and 1. + max_p: Maximum p-value to consider. Values above this will be set to max_p. + Must be between 0 and 1. + input_sep: The field separator character for input p-values, groups, and weights files. + Common values are "," for CSV and "\\t" for TSV. + input_header: If TRUE, the input files are assumed to have a header row. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not p_values_file.is_file(): + raise FileNotFoundError(f"Input p-values file not found: {p_values_file}") + if not groups_file.is_file(): + raise FileNotFoundError(f"Input groups file not found: {groups_file}") + if weights_file and not weights_file.is_file(): + raise FileNotFoundError(f"Input weights file not found: {weights_file}") + + if not (0.0 <= min_p <= 1.0): + raise ValueError("min_p must be between 0 and 1.") + if not (0.0 <= max_p <= 1.0): + raise ValueError("max_p must be between 0 and 1.") + if min_p > max_p: + raise ValueError("min_p cannot be greater than max_p.") + + allowed_methods = ["fisher", "stouffer", "simes", "davies", "whitlock", "fdr", "bonferroni", "none"] + if method not in allowed_methods: + raise ValueError(f"Invalid method: '{method}'. Must be one of {allowed_methods}") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Convert boolean to R's TRUE/FALSE + r_log_p = str(log_p).upper() + r_na_rm = str(na_rm).upper() + r_input_header = str(input_header).upper() + + # Create a temporary R script + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as r_script_temp: + r_script_path = Path(r_script_temp.name) + r_script_temp.write(f""" + library(metapod) + + # Read p-values (assuming single column) + p_values_input <- as.numeric(read.csv( + "{p_values_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + )[[1]]) + + # Read groups (assuming single column) + groups_input <- as.factor(read.csv( + "{groups_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + )[[1]]) + + weights_input <- NULL + if (!is.null("{weights_file}")) {{ + weights_input <- as.numeric(read.csv( + "{weights_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + )[[1]]) + }} + + # Call groupedPValues + combined_p_values <- metapod::groupedPValues( + p.values = p_values_input, + groups = groups_input, + weights = weights_input, + method = "{method}", + log.p = {r_log_p}, + na.rm = {r_na_rm}, + min.p = {min_p}, + max.p = {max_p} + ) + + # Write results to output file + write.csv(combined_p_values, file = "{output_file}", row.names = FALSE) + """) + + command = ["Rscript", str(r_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # Clean up the temporary script even if an error occurs + os.remove(r_script_path) + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [], + } + finally: + # Clean up the temporary R script + if r_script_path.exists(): + os.remove(r_script_path) + + if not output_file.is_file(): + stderr += f"\nError: Expected output file '{output_file}' was not created." + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_file)], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..60ddfb3bc20c420d452b8c0ccffe8d3dd6af87cf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_metapod' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d1c5940ca3366fe6942d00fdc1c76e36315ebb66 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-metapod: + build: . + image: mcp-bioconductor-metapod:latest + container_name: mcp-bioconductor-metapod + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-metapod + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..153d07b003e599338e3741bf7537f22006d08e89 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-metapod + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metapod/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ccec41ddd0d80bd47367f90dfd32979fcab14fc9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-moleculeexperiment via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-moleculeexperiment -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-moleculeexperiment_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-moleculeexperiment_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-moleculeexperiment_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/__pycache__/bioconductor-moleculeexperiment_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/__pycache__/bioconductor-moleculeexperiment_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b103802ace6a6f57446e6278ebfc40dd990be2d5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/__pycache__/bioconductor-moleculeexperiment_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fae47e1184e790b367ff82c8ea0bccd7e8786cd4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py @@ -0,0 +1,378 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile +import json + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_moleculeexperiment' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def read_xenium_to_molecule_experiment( + data_dir: str, + output_rds: str, + keep_unassigned: bool = True, +): + """ + Read 10X Xenium spatial transcriptomics data into a MoleculeExperiment RDS file. + + Args: + data_dir: Path to the directory containing Xenium output files (e.g., transcripts.csv.gz, cell_boundaries.csv.gz). + output_rds: Path where the resulting MoleculeExperiment object will be saved (.rds). + keep_unassigned: Whether to keep molecules not assigned to any cell. + """ + data_path = Path(data_dir) + if not data_path.is_dir(): + return {"error": f"Data directory {data_dir} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + tryCatch({{ + me <- readXenium(data_dir = "{data_dir}", keep_unassigned = {str(keep_unassigned).upper()}) + saveRDS(me, "{output_rds}") + cat("Successfully saved MoleculeExperiment to {output_rds}") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"readXenium(data_dir='{data_dir}')", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def read_cosmx_to_molecule_experiment( + data_dir: str, + output_rds: str, + keep_unassigned: bool = True, +): + """ + Read Nanostring Cosmx SMI spatial transcriptomics data into a MoleculeExperiment RDS file. + + Args: + data_dir: Path to the directory containing Cosmx output files. + output_rds: Path where the resulting MoleculeExperiment object will be saved (.rds). + keep_unassigned: Whether to keep molecules not assigned to any cell. + """ + data_path = Path(data_dir) + if not data_path.is_dir(): + return {"error": f"Data directory {data_dir} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + tryCatch({{ + me <- readCosmx(data_dir = "{data_dir}", keep_unassigned = {str(keep_unassigned).upper()}) + saveRDS(me, "{output_rds}") + cat("Successfully saved MoleculeExperiment to {output_rds}") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"readCosmx(data_dir='{data_dir}')", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def read_merscope_to_molecule_experiment( + data_dir: str, + output_rds: str, + keep_unassigned: bool = True, +): + """ + Read Vizgen Merscope spatial transcriptomics data into a MoleculeExperiment RDS file. + + Args: + data_dir: Path to the directory containing Merscope output files. + output_rds: Path where the resulting MoleculeExperiment object will be saved (.rds). + keep_unassigned: Whether to keep molecules not assigned to any cell. + """ + data_path = Path(data_dir) + if not data_path.is_dir(): + return {"error": f"Data directory {data_dir} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + tryCatch({{ + me <- readMerscope(data_dir = "{data_dir}", keep_unassigned = {str(keep_unassigned).upper()}) + saveRDS(me, "{output_rds}") + cat("Successfully saved MoleculeExperiment to {output_rds}") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"readMerscope(data_dir='{data_dir}')", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def count_molecules( + input_rds: str, + output_rds: str, + assay_name: str = "counts", +): + """ + Aggregate molecules in a MoleculeExperiment object into a SpatialExperiment object (cell x gene counts). + + Args: + input_rds: Path to the input MoleculeExperiment RDS file. + output_rds: Path where the resulting SpatialExperiment object will be saved (.rds). + assay_name: Name of the assay to create in the output object. + """ + if not Path(input_rds).exists(): + return {"error": f"Input file {input_rds} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + library(SpatialExperiment) + tryCatch({{ + me <- readRDS("{input_rds}") + se <- countMolecules(me, assay_name = "{assay_name}") + saveRDS(se, "{output_rds}") + cat("Successfully aggregated molecules into SpatialExperiment") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"countMolecules(me, assay_name='{assay_name}')", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def filter_molecules_by_gene( + input_rds: str, + output_rds: str, + genes: List[str], +): + """ + Filter a MoleculeExperiment object to keep only specific genes. + + Args: + input_rds: Path to the input MoleculeExperiment RDS file. + output_rds: Path where the filtered MoleculeExperiment object will be saved (.rds). + genes: List of gene names to keep. + """ + if not Path(input_rds).exists(): + return {"error": f"Input file {input_rds} does not exist."} + + genes_r = 'c("' + '", "'.join(genes) + '")' + + r_code = f""" + library(MoleculeExperiment) + tryCatch({{ + me <- readRDS("{input_rds}") + # Assuming molecules are stored in a way that allows standard subsetting + # MoleculeExperiment typically uses a list-like structure for molecules + me_filtered <- me[me$gene %in% {genes_r}, ] + saveRDS(me_filtered, "{output_rds}") + cat("Successfully filtered molecules") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"me[me$gene %in% {genes_r}, ]", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def plot_molecules_spatial( + input_rds: str, + output_image: str, + genes: Optional[List[str]] = None, + sample_id: Optional[str] = None, + point_size: float = 0.1, +): + """ + Visualize molecule locations from a MoleculeExperiment object. + + Args: + input_rds: Path to the input MoleculeExperiment RDS file. + output_image: Path to save the output plot (e.g., .png, .pdf). + genes: Optional list of specific genes to plot. If None, plots all. + sample_id: Optional sample identifier if multiple samples exist. + point_size: Size of the points in the plot. + """ + if not Path(input_rds).exists(): + return {"error": f"Input file {input_rds} does not exist."} + + genes_r = 'NULL' + if genes: + genes_r = 'c("' + '", "'.join(genes) + '")' + + sample_id_r = f'"{sample_id}"' if sample_id else "NULL" + + r_code = f""" + library(MoleculeExperiment) + library(ggplot2) + tryCatch({{ + me <- readRDS("{input_rds}") + p <- plotMolecules(me, genes = {genes_r}, sample_id = {sample_id_r}, point_size = {point_size}) + ggsave("{output_image}", plot = p, width = 10, height = 10) + cat("Successfully saved plot to {output_image}") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "plotMolecules(...)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_image] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def create_molecule_experiment_from_df( + molecules_csv: str, + output_rds: str, + boundaries_csv: Optional[str] = None, +): + """ + Create a MoleculeExperiment object from custom CSV files. + + Args: + molecules_csv: Path to a CSV containing molecule data (must have x, y, and gene columns). + output_rds: Path where the resulting MoleculeExperiment object will be saved (.rds). + boundaries_csv: Optional path to a CSV containing cell boundary coordinates. + """ + if not Path(molecules_csv).exists(): + return {"error": f"Molecules file {molecules_csv} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + library(data.table) + tryCatch({{ + mols <- fread("{molecules_csv}") + bounds <- NULL + if ("{boundaries_csv}" != "None" && file.exists("{boundaries_csv}")) {{ + bounds <- fread("{boundaries_csv}") + }} + + me <- MoleculeExperiment(molecules = mols, boundaries = bounds) + saveRDS(me, "{output_rds}") + cat("Successfully created MoleculeExperiment from CSV") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "MoleculeExperiment(molecules=mols, boundaries=bounds)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..010e51c97c310dae596632accb9878aef25bdb4f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_moleculeexperiment' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8391b5a42b71f56f0fbadd46a4ebf46bb3be01b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-moleculeexperiment: + build: . + image: mcp-bioconductor-moleculeexperiment:latest + container_name: mcp-bioconductor-moleculeexperiment + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-moleculeexperiment + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..915487a01bd02c680dcac5ec49ea08b92d891c21 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-moleculeexperiment + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-moleculeexperiment/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5fd3bc9dcf3ea6f60926861e1e9b59a8befef3a3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-multiassayexperiment via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-multiassayexperiment -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-multiassayexperiment_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-multiassayexperiment_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-multiassayexperiment_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/__pycache__/bioconductor-multiassayexperiment_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/__pycache__/bioconductor-multiassayexperiment_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..518df31ee37a01fb848d50e04952fccf1935ca06 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/__pycache__/bioconductor-multiassayexperiment_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b9830a23f6a933e3f6f74ec55f738ab7665744 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py @@ -0,0 +1,342 @@ +import subprocess +import tempfile +import shlex +from pathlib import Path +from typing import List, Optional, Dict + +# Helper function to convert a Python list of strings to an R character vector string +def _python_list_to_r_vector(py_list: List[str]) -> str: + """Converts a Python list of strings to an R character vector string e.g., c("a", "b").""" + if not py_list: + return "c()" + quoted_items = [f'"{item}"' for item in py_list] + return f"c({', '.join(quoted_items)})" + +# Helper function to run an R script and handle errors +def _run_r_script(r_script_content: str, command_name: str) -> Dict[str, str]: + """ + Writes R content to a temporary file, executes it, and handles I/O and errors. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_path_str = r_script_file.name + r_script_file.write(r_script_content) + + cmd = ["Rscript", r_script_path_str] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("Rscript executable not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"{command_name} failed. R script execution returned a non-zero exit code {e.returncode}.\n" + f"Stderr:\n{e.stderr}\n" + f"Stdout:\n{e.stdout}" + ) + raise RuntimeError(error_message) + finally: + # Ensure the temporary script is always removed + Path(r_script_path_str).unlink() + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_multiassayexperiment' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def create_multiassayexperiment( + experiments: List[Path], + experiment_names: List[str], + coldata: Path, + samplemap: Path, + output_rds: Path, + metadata_json: Optional[Path] = None, +) -> Dict: + """ + Creates a MultiAssayExperiment object from component files and saves it as an RDS file. + This tool is a wrapper for the R/Bioconductor package 'MultiAssayExperiment'. + + Args: + experiments: List of paths to experiment data files (CSV format, with row names in the first column). + experiment_names: List of names for each experiment, corresponding to the 'experiments' list. + coldata: Path to the sample metadata file (colData) in CSV format. + samplemap: Path to the sample map file in CSV format. + output_rds: Path to save the output MultiAssayExperiment object in RDS format. + metadata_json: Optional path to a JSON file containing metadata for the experiment. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if len(experiments) != len(experiment_names): + raise ValueError("The number of experiment files must match the number of experiment names.") + if not experiments: + raise ValueError("At least one experiment file must be provided.") + + for exp_file in experiments: + if not exp_file.is_file(): + raise FileNotFoundError(f"Experiment file not found: {exp_file}") + if not coldata.is_file(): + raise FileNotFoundError(f"colData file not found: {coldata}") + if not samplemap.is_file(): + raise FileNotFoundError(f"sampleMap file not found: {samplemap}") + if metadata_json and not metadata_json.is_file(): + raise FileNotFoundError(f"Metadata JSON file not found: {metadata_json}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + exp_readers = "\n ".join( + f'exp_list[["{name}"]] <- as.matrix(read.csv({shlex.quote(str(path))}, row.names=1, check.names=FALSE))' + for name, path in zip(experiment_names, experiments) + ) + + meta_loader = "meta <- list()" + if metadata_json: + meta_loader = f""" + if (!requireNamespace("jsonlite", quietly = TRUE)) install.packages("jsonlite", repos="http://cran.us.r-project.org") + meta <- jsonlite::fromJSON({shlex.quote(str(metadata_json))}) + """ + + r_script = f""" + # Ensure BiocManager and required packages are installed + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos="http://cran.us.r-project.org") + pkgs <- c("MultiAssayExperiment", "S4Vectors") + for (pkg in pkgs) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(MultiAssayExperiment) + library(S4Vectors) + + # Create ExperimentList + exp_list <- list() + {exp_readers} + experiments_list_obj <- ExperimentList(exp_list) + + # Read colData and sampleMap + coldata_df <- read.csv({shlex.quote(str(coldata))}, row.names=1, check.names=FALSE) + coldata_s4 <- DataFrame(coldata_df, check.names=FALSE) + + samplemap_df <- read.csv({shlex.quote(str(samplemap))}, check.names=FALSE) + samplemap_s4 <- DataFrame(samplemap_df, check.names=FALSE) + + # Load metadata + {meta_loader} + + # Create MultiAssayExperiment object + mae <- MultiAssayExperiment( + experiments = experiments_list_obj, + colData = coldata_s4, + sampleMap = samplemap_s4, + metadata = meta + ) + + # Save the object + saveRDS(mae, file = {shlex.quote(str(output_rds))}) + print("MultiAssayExperiment object created and saved successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "create_multiassayexperiment") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_rds)], + } + +@mcp.tool() +def subset_by_assay( + input_mae_rds: Path, + output_mae_rds: Path, + assays: List[str], +) -> Dict: + """ + Subsets a MultiAssayExperiment object by assay names. + + Args: + input_mae_rds: Path to the input MultiAssayExperiment RDS file. + output_mae_rds: Path to save the subsetted MultiAssayExperiment RDS file. + assays: A list of assay names to keep in the object. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_mae_rds.is_file(): + raise FileNotFoundError(f"Input MAE file not found: {input_mae_rds}") + if not assays: + raise ValueError("The 'assays' list cannot be empty.") + output_mae_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + assays_r_vector = _python_list_to_r_vector(assays) + r_script = f""" + library(MultiAssayExperiment) + mae <- readRDS({shlex.quote(str(input_mae_rds))}) + assays_to_keep <- {assays_r_vector} + mae_subset <- mae[,,assays_to_keep] + saveRDS(mae_subset, file = {shlex.quote(str(output_mae_rds))}) + print("Subsetting by assay completed successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "subset_by_assay") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_mae_rds)], + } + +@mcp.tool() +def subset_by_sample( + input_mae_rds: Path, + output_mae_rds: Path, + samples: List[str], +) -> Dict: + """ + Subsets a MultiAssayExperiment object by sample names (colData rownames). + + Args: + input_mae_rds: Path to the input MultiAssayExperiment RDS file. + output_mae_rds: Path to save the subsetted MultiAssayExperiment RDS file. + samples: A list of sample names (from colData) to keep. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_mae_rds.is_file(): + raise FileNotFoundError(f"Input MAE file not found: {input_mae_rds}") + if not samples: + raise ValueError("The 'samples' list cannot be empty.") + output_mae_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + samples_r_vector = _python_list_to_r_vector(samples) + r_script = f""" + library(MultiAssayExperiment) + mae <- readRDS({shlex.quote(str(input_mae_rds))}) + samples_to_keep <- {samples_r_vector} + mae_subset <- mae[,samples_to_keep,] + saveRDS(mae_subset, file = {shlex.quote(str(output_mae_rds))}) + print("Subsetting by sample completed successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "subset_by_sample") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_mae_rds)], + } + +@mcp.tool() +def subset_by_row( + input_mae_rds: Path, + output_mae_rds: Path, + rows: List[str], +) -> Dict: + """ + Subsets a MultiAssayExperiment object by row/feature names. + + Args: + input_mae_rds: Path to the input MultiAssayExperiment RDS file. + output_mae_rds: Path to save the subsetted MultiAssayExperiment RDS file. + rows: A list of row/feature names to keep. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_mae_rds.is_file(): + raise FileNotFoundError(f"Input MAE file not found: {input_mae_rds}") + if not rows: + raise ValueError("The 'rows' list cannot be empty.") + output_mae_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + rows_r_vector = _python_list_to_r_vector(rows) + r_script = f""" + library(MultiAssayExperiment) + mae <- readRDS({shlex.quote(str(input_mae_rds))}) + rows_to_keep <- {rows_r_vector} + mae_subset <- mae[rows_to_keep,,] + saveRDS(mae_subset, file = {shlex.quote(str(output_mae_rds))}) + print("Subsetting by row completed successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "subset_by_row") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_mae_rds)], + } + +@mcp.tool() +def export_long_format( + input_mae_rds: Path, + output_csv: Path, + coldata_cols: Optional[List[str]] = None, +) -> Dict: + """ + Exports data from a MultiAssayExperiment object to a long-format CSV file. + + Args: + input_mae_rds: Path to the input MultiAssayExperiment RDS file. + output_csv: Path to save the output long-format data in CSV format. + coldata_cols: Optional list of column names from colData to include in the output. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output CSV file. + """ + # --- Input Validation --- + if not input_mae_rds.is_file(): + raise FileNotFoundError(f"Input MAE file not found: {input_mae_rds}") + output_csv.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + coldata_vars = "NULL" + if coldata_cols: + coldata_vars = _python_list_to_r_vector(coldata_cols) + + r_script = f""" + library(MultiAssayExperiment) + mae <- readRDS({shlex.quote(str(input_mae_rds))}) + long_df <- longFormat(mae, colDataCols = {coldata_vars}) + write.csv(long_df, file = {shlex.quote(str(output_csv))}, row.names = FALSE) + print("Export to long format CSV completed successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "export_long_format") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_csv)], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d012e982d103c48d6a439df5204eb86a64264358 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_multiassayexperiment' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..01a8d206024f451005a92d57776aec5d0da06aca --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-multiassayexperiment: + build: . + image: mcp-bioconductor-multiassayexperiment:latest + container_name: mcp-bioconductor-multiassayexperiment + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-multiassayexperiment + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab0c20e1007cb60d742fd97346f24742a730e275 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-multiassayexperiment + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-multiassayexperiment/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ef6617906b8f7a0a1eedb1ed96648f36004ded13 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-orfhunter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-orfhunter -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-orfhunter_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-orfhunter_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-orfhunter_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/__pycache__/bioconductor-orfhunter_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/__pycache__/bioconductor-orfhunter_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eddb1110f23894537b6a441509d2f08af687c327 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/__pycache__/bioconductor-orfhunter_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..58d501afdf7a36ed397172cfdf6854fa407c105a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py @@ -0,0 +1,291 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_orfhunter' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def predict_orf( + fasta_input: str, + output_csv: str, + model_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Predict the most likely open reading frame (ORF) in nucleotide sequences using a random forest model. + This is the primary tool for automatic determination and annotation of ORFs in RNA molecules. + + Args: + fasta_input: Path to the input FASTA file containing nucleotide sequences. + output_csv: Path where the predicted ORFs and their characteristics will be saved (CSV format). + model_path: Optional path to a custom pre-trained random forest model (.rds file). + If not provided, the default human-specific model included in the package is used. + """ + input_path = Path(fasta_input).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + model_loading = "model <- NULL" + if model_path: + m_path = Path(model_path).resolve() + if not m_path.exists(): + return {"error": f"Model file not found: {model_path}"} + model_loading = f"model <- readRDS('{m_path}')" + + r_script = f""" + library(ORFhunteR) + library(Biostrings) + {model_loading} + sequences <- readDNAStringSet('{input_path}') + # predictORF returns a data.frame with predicted ORFs + result <- predictORF(sequences = sequences, model = model) + write.csv(result, '{output_path}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::predictORF on {fasta_input}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def find_orfs( + fasta_input: str, + output_csv: str, +) -> Dict[str, Any]: + """ + Identify all potential open reading frames (ORFs) in a set of nucleotide sequences. + This tool finds every sequence starting with a start codon and ending with a stop codon. + + Args: + fasta_input: Path to the input FASTA file containing nucleotide sequences. + output_csv: Path where the identified ORFs and their coordinates will be saved (CSV format). + """ + input_path = Path(fasta_input).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + library(ORFhunteR) + library(Biostrings) + library(data.table) + sequences <- readDNAStringSet('{input_path}') + # findORFs returns a list of data.tables + result_list <- findORFs(sequences = sequences) + # Combine list into a single data table with transcript IDs + result_df <- rbindlist(result_list, idcol = "transcript_id") + write.csv(result_df, '{output_path}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::findORFs on {fasta_input}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def classify_orfs( + fasta_input: str, + output_csv: str, + model_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Classify a set of nucleotide sequences as coding or non-coding ORFs using a random forest model. + + Args: + fasta_input: Path to a FASTA file containing the ORF sequences to be classified. + output_csv: Path where the classification probabilities will be saved (CSV format). + model_path: Optional path to a custom pre-trained random forest model (.rds file). + """ + input_path = Path(fasta_input).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + model_loading = "model <- NULL" + if model_path: + m_path = Path(model_path).resolve() + if not m_path.exists(): + return {"error": f"Model file not found: {model_path}"} + model_loading = f"model <- readRDS('{m_path}')" + + r_script = f""" + library(ORFhunteR) + library(Biostrings) + {model_loading} + sequences <- as.character(readDNAStringSet('{input_path}')) + # classifyORFs returns a vector of probabilities + probs <- classifyORFs(ORFs = sequences, model = model) + result <- data.frame(sequence_id = names(sequences), probability = probs) + write.csv(result, '{output_path}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::classifyORFs on {fasta_input}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def vectorize_orfs( + fasta_input: str, + output_csv: str, +) -> Dict[str, Any]: + """ + Transform nucleotide sequences into numerical vectors (feature extraction) for machine learning. + This implements the vectorization algorithm used by the ORFhunteR random forest model. + + Args: + fasta_input: Path to the input FASTA file containing nucleotide sequences. + output_csv: Path where the feature matrix will be saved (CSV format). + """ + input_path = Path(fasta_input).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + library(ORFhunteR) + library(Biostrings) + sequences <- as.character(readDNAStringSet('{input_path}')) + # vectorizeORFs returns a matrix of features + features <- vectorizeORFs(sequences = sequences) + write.csv(as.data.frame(features), '{output_path}', row.names = TRUE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::vectorizeORFs on {fasta_input}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def annotate_orf( + orfs_csv: str, + output_csv: str, + genome_package: str = "BSgenome.Hsapiens.UCSC.hg38", +) -> Dict[str, Any]: + """ + Annotate predicted ORFs by mapping them to genomic coordinates using a BSgenome object. + + Args: + orfs_csv: Path to a CSV file containing predicted ORFs (output from predict_orf). + Must contain 'transcript_id' and coordinate columns. + output_csv: Path where the genomic annotations will be saved (CSV format). + genome_package: The name of the Bioconductor BSgenome package to use for annotation. + Defaults to 'BSgenome.Hsapiens.UCSC.hg38'. + """ + input_path = Path(orfs_csv).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input CSV file not found: {orfs_csv}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + library(ORFhunteR) + library({genome_package}) + orfs_df <- read.csv('{input_path}') + # annotateORFs maps transcript coordinates to genomic coordinates + # It expects the ORFs data frame and corresponding transcript IDs + result <- annotateORFs(ORFs = orfs_df, + transcript_id = orfs_df$transcript_id, + target_genome = {genome_package}) + write.csv(result, '{output_path}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::annotateORFs using {genome_package}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed. Ensure the BSgenome package is installed.", + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c569fa074b095dd4652bad3c74f32a4a4953f057 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_orfhunter' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ffd1257beabc2e36bf2d4c39081ee52804eafd1d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-orfhunter: + build: . + image: mcp-bioconductor-orfhunter:latest + container_name: mcp-bioconductor-orfhunter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-orfhunter + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..abc3d2710d8c879e5c5ae780455731d3b509b0d0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-orfhunter + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-orfhunter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..75db8224da29a94ca004d7668ccd14ab76761985 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-phyloseq via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-phyloseq -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-phyloseq_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-phyloseq_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-phyloseq_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/__pycache__/bioconductor-phyloseq_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/__pycache__/bioconductor-phyloseq_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bcf745d90d0635734f948631de940525b5e203b Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/__pycache__/bioconductor-phyloseq_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..de5c022f375daf37b507c6461ee11963395b66f6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py @@ -0,0 +1,355 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import Optional, List, Literal + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# --- Helper Function to run R scripts --- +def _run_r_script(command: List[str]): + """ + A helper function to execute an R script, handling errors and I/O. + + Args: + command: A list of strings representing the command and its arguments. + + Returns: + A tuple containing stdout and stderr. + + Raises: + subprocess.CalledProcessError: If the R script returns a non-zero exit code. + """ + try: + logger.info(f"Executing command: {' '.join(command)}") + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + if process.stderr: + logger.warning(f"Stderr from R script:\n{process.stderr}") + return process.stdout, process.stderr + except FileNotFoundError: + msg = f"Error: The command '{command[0]}' was not found. Is Rscript in your system's PATH?" + logger.error(msg) + raise + except subprocess.CalledProcessError as e: + logger.error(f"R script failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(e.cmd)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + +# @mcp.tool() - This decorator is assumed to be provided by the MCP framework. +def phyloseq_import_biom( + biom_file: Path, + output_rds: Path, + metadata_file: Optional[Path] = None, + tree_file: Optional[Path] = None, +): + """ + Imports a BIOM file, optional metadata, and an optional phylogenetic tree + into a phyloseq object and saves it as an RDS file. + + This tool requires R, Rscript, and the 'phyloseq' R package. + It assumes an R script named 'run_phyloseq_import.R' is in the system PATH. + + Args: + biom_file (Path): Path to the input BIOM format file (e.g., from QIIME). + output_rds (Path): Path to save the output phyloseq object (.rds file). + metadata_file (Optional[Path]): Path to the sample metadata file. + tree_file (Optional[Path]): Path to the phylogenetic tree file (e.g., Newick format). + """ + # --- Input Validation --- + if not biom_file.is_file(): + raise FileNotFoundError(f"Input BIOM file not found: {biom_file}") + if metadata_file and not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if tree_file and not tree_file.is_file(): + raise FileNotFoundError(f"Tree file not found: {tree_file}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_import.R", + "--biom", str(biom_file), + "--output", str(output_rds), + ] + if metadata_file: + cmd.extend(["--metadata", str(metadata_file)]) + if tree_file: + cmd.extend(["--tree", str(tree_file)]) + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq import failed.", + "output_files": [] + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_phyloseq' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def phyloseq_filter_and_transform( + input_rds: Path, + output_rds: Path, + min_prevalence: float = 0.05, + min_total_abundance: int = 0, + transform_method: Literal["none", "compositional"] = "compositional", +): + """ + Filters taxa based on prevalence and abundance, and optionally transforms + the data to relative abundance (compositional). + + This tool requires R, Rscript, and the 'phyloseq' R package. + It assumes an R script named 'run_phyloseq_filter.R' is in the system PATH. + + Args: + input_rds (Path): Path to the input phyloseq object (.rds file). + output_rds (Path): Path to save the filtered/transformed phyloseq object. + min_prevalence (float): Minimum proportion of samples a taxon must be in to be kept. + min_total_abundance (int): Minimum total abundance a taxon must have across all samples. + transform_method (str): Transformation to apply. 'compositional' for relative abundance. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not (0.0 <= min_prevalence <= 1.0): + raise ValueError("min_prevalence must be between 0.0 and 1.0.") + if min_total_abundance < 0: + raise ValueError("min_total_abundance must be non-negative.") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_filter.R", + "--input", str(input_rds), + "--output", str(output_rds), + "--prevalence", str(min_prevalence), + "--abundance", str(min_total_abundance), + "--transform", transform_method, + ] + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq filtering/transformation failed.", + "output_files": [] + } + +@mcp.tool() +def phyloseq_plot_ordination( + input_rds: Path, + output_plot: Path, + method: Literal["DCA", "CCA", "RDA", "NMDS", "MDS", "PCoA"] = "PCoA", + distance: str = "bray", + color_by: Optional[str] = None, + shape_by: Optional[str] = None, +): + """ + Performs ordination and generates a plot. + + This tool requires R, Rscript, 'phyloseq', and 'ggplot2' R packages. + It assumes an R script named 'run_phyloseq_ordination.R' is in the system PATH. + + Args: + input_rds (Path): Path to the input phyloseq object (.rds file). + output_plot (Path): Path to save the output plot file (e.g., plot.png). + method (str): Ordination method to use. + distance (str): Distance metric to use (for NMDS, MDS, PCoA). + color_by (Optional[str]): Metadata variable to color points by. + shape_by (Optional[str]): Metadata variable to shape points by. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_ordination.R", + "--input", str(input_rds), + "--output", str(output_plot), + "--method", method, + "--distance", distance, + ] + if color_by: + cmd.extend(["--color", color_by]) + if shape_by: + cmd.extend(["--shape", shape_by]) + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq ordination plotting failed.", + "output_files": [] + } + +@mcp.tool() +def phyloseq_plot_richness( + input_rds: Path, + output_plot: Path, + group_by: str, + measures: str = "Observed,Shannon", +): + """ + Calculates and plots alpha diversity (richness) estimates. + + This tool requires R, Rscript, 'phyloseq', and 'ggplot2' R packages. + It assumes an R script named 'run_phyloseq_richness.R' is in the system PATH. + + Args: + input_rds (Path): Path to the input phyloseq object (.rds file). + output_plot (Path): Path to save the output plot file (e.g., plot.png). + group_by (str): Metadata variable to group samples for boxplots. + measures (str): Comma-separated list of richness measures (e.g., "Observed,Shannon,Simpson"). + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not measures: + raise ValueError("At least one richness measure must be provided.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_richness.R", + "--input", str(input_rds), + "--output", str(output_plot), + "--group", group_by, + "--measures", measures, + ] + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq richness plotting failed.", + "output_files": [] + } + +@mcp.tool() +def phyloseq_plot_heatmap( + input_rds: Path, + output_plot: Path, + taxa_rank: str = "Phylum", + top_n_taxa: int = 20, + sample_order_by: Optional[str] = None, + method: Literal["NMDS", "PCoA"] = "NMDS", + distance: str = "bray", +): + """ + Generates a heatmap of the most abundant taxa. + + This tool requires R, Rscript, 'phyloseq', and 'ggplot2' R packages. + It assumes an R script named 'run_phyloseq_heatmap.R' is in the system PATH. + + Args: + input_rds (Path): Path to the input phyloseq object (.rds file). + output_plot (Path): Path to save the output plot file (e.g., plot.png). + taxa_rank (str): Taxonomic rank to agglomerate to before plotting. + top_n_taxa (int): The number of most abundant taxa to include in the heatmap. + sample_order_by (Optional[str]): Metadata variable to order samples by. + method (str): Ordination method for ordering samples if sample_order_by is not provided. + distance (str): Distance metric for ordination-based sample ordering. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if top_n_taxa <= 0: + raise ValueError("top_n_taxa must be a positive integer.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_heatmap.R", + "--input", str(input_rds), + "--output", str(output_plot), + "--rank", taxa_rank, + "--ntaxa", str(top_n_taxa), + "--method", method, + "--distance", distance, + ] + if sample_order_by: + cmd.extend(["--sample_order", sample_order_by]) + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq heatmap plotting failed.", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..92e5fe3c51cc4cccf5f2416eb31cf52e72af16cf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_phyloseq' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-phyloseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4c3b71edffcd345c21c6f37e6f6f21332b953637 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-pipecomp via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-pipecomp -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-pipecomp_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-pipecomp_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-pipecomp_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/__pycache__/bioconductor-pipecomp_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/__pycache__/bioconductor-pipecomp_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b110e774b36dc324be22cc99c7b514f477c3d89 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/__pycache__/bioconductor-pipecomp_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa5b87e02ba06fd4d72537ebcc076ef4e951b2b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py @@ -0,0 +1,178 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Literal, Dict, Any +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# MCP decorator placeholder for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def pipecomp_run( + conf: Path, + outdir: Path, + pipedir: Path = Path("."), + pipename: Optional[str] = None, + select_helpers: Optional[str] = None, + select_mods: Optional[str] = None, + select_pipelines: Optional[str] = None, + select_evals: Optional[str] = None, + run_id: Optional[str] = None, + resume: bool = False, + debug: bool = False, + mode: Literal[ + "local", "batchtools_local", "batchtools_slurm", "batchtools_sge", + "batchtools_lsf", "batchtools_openlava", "batchtools_torque", + "batchtools_multicore" + ] = "local", + batch_resources: Optional[str] = None, + batch_template: Optional[Path] = None, + batch_workers: Optional[int] = None, +) -> Dict[str, Any]: + """ + Runs a pipeComp pipeline comparison based on a configuration file. + + This tool serves as a wrapper for the `run_pipecomp` function from the + Bioconductor R package `pipeComp`. It allows for the execution and + evaluation of bioinformatics pipelines. + + Args: + conf: Path to the main configuration file (e.g., 'conf.yml'). + outdir: Path to the output directory where results will be stored. + pipedir: Path to the directory containing pipeline scripts. Defaults to the current directory. + pipename: Optional name for the pipeline. + select_helpers: Comma-separated string to select specific helper scripts. + select_mods: Comma-separated string to select specific modifications. + select_pipelines: Comma-separated string to select specific pipelines. + select_evals: Comma-separated string to select specific evaluations. + run_id: A unique identifier for this run. + resume: If True, attempts to resume a previous run. Defaults to False. + debug: If True, enables debug mode for more verbose output. Defaults to False. + mode: The execution mode. 'local' runs serially. Other modes use 'batchtools' for parallel execution. + batch_resources: An R-formatted string for batch system resources (e.g., 'list(walltime=3600, ncpus=2)'). + batch_template: Path to a custom batchtools template file. + batch_workers: The number of workers for batch execution. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not conf.is_file(): + raise FileNotFoundError(f"Configuration file not found: {conf}") + if pipedir and not pipedir.is_dir(): + raise NotADirectoryError(f"Pipeline directory not found: {pipedir}") + if batch_template and not batch_template.is_file(): + raise FileNotFoundError(f"Batch template file not found: {batch_template}") + if batch_workers is not None and batch_workers <= 0: + raise ValueError("batch_workers must be a positive integer.") + + # 2. Create output directory + try: + outdir.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Failed to create output directory {outdir}: {e}") from e + + # 3. Command Construction + # Helper to format R arguments, handling NULL for None + def format_r_arg(value: Any) -> str: + if value is None: + return "NULL" + if isinstance(value, bool): + return "TRUE" if value else "FALSE" + if isinstance(value, (int, float)): + return str(value) + # For strings and paths, quote them for R + return f"'{str(value)}'" + + r_args = [ + f"conf = {format_r_arg(conf)}", + f"outdir = {format_r_arg(outdir)}", + f"pipedir = {format_r_arg(pipedir)}", + f"pipename = {format_r_arg(pipename)}", + f"select_helpers = {format_r_arg(select_helpers)}", + f"select_mods = {format_r_arg(select_mods)}", + f"select_pipelines = {format_r_arg(select_pipelines)}", + f"select_evals = {format_r_arg(select_evals)}", + f"run_id = {format_r_arg(run_id)}", + f"resume = {format_r_arg(resume)}", + f"debug = {format_r_arg(debug)}", + f"mode = {format_r_arg(mode)}", + f"batch_template = {format_r_arg(batch_template)}", + f"batch_workers = {format_r_arg(batch_workers)}", + ] + + # batch_resources is passed as a raw string to be evaluated by R + if batch_resources: + r_args.append(f"batch_resources = {batch_resources}") + else: + r_args.append("batch_resources = list()") + + r_function_call = f"pipeComp::run_pipecomp({', '.join(r_args)})" + r_script = f"library(pipeComp); {r_function_call}" + + command = ["Rscript", "-e", r_script] + command_executed = " ".join(shlex.quote(str(c)) for c in command) + logger.info(f"Executing command: {command_executed}") + + # 4. Subprocess Execution & Error Handling + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=False, # We check the return code manually for better error reporting + ) + + if result.returncode != 0: + logger.error(f"pipeComp execution failed with exit code {result.returncode}") + logger.error(f"STDOUT: {result.stdout}") + logger.error(f"STDERR: {result.stderr}") + # Even on failure, some output files might be generated + output_files = [str(f) for f in outdir.rglob("*") if f.is_file()] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": f"Error: pipeComp process exited with code {result.returncode}.\n{result.stderr}", + "output_files": output_files, + } + + except FileNotFoundError: + error_msg = "Error: 'Rscript' command not found. Is R installed and in your system's PATH?" + logger.error(error_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_msg, + "output_files": [], + } + except Exception as e: + error_msg = f"An unexpected error occurred: {e}" + logger.error(error_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_msg, + "output_files": [], + } + + # 5. Collect Output Files + try: + output_files = [str(f) for f in outdir.rglob("*") if f.is_file()] + except Exception as e: + logger.warning(f"Could not list output files in {outdir}: {e}") + output_files = [] + + # 6. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ef9eae8218d25a4cc52e0f485ed2d1d0efdae852 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_pipecomp' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7599e9b748eed80975ee6f04120a79cf1925b687 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-pipecomp: + build: . + image: mcp-bioconductor-pipecomp:latest + container_name: mcp-bioconductor-pipecomp + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-pipecomp + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cdbee95fc4c5b30346a0d26886ab7fe09ab0a168 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-pipecomp + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-pipecomp/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..adbf3ebc54fccef2f2bf508538755a4d5a89b24e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-proteomicsannotationhubdata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-proteomicsannotationhubdata -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-proteomicsannotationhubdata_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-proteomicsannotationhubdata_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-proteomicsannotationhubdata_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/__pycache__/bioconductor-proteomicsannotationhubdata_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/__pycache__/bioconductor-proteomicsannotationhubdata_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f87e5b3640bb1f0a556356e7219a9423374974df Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/__pycache__/bioconductor-proteomicsannotationhubdata_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..90b31cb06cbc02c8ee3218b223749aa9db7f4913 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py @@ -0,0 +1,120 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# MCP decorator placeholder +def tool(func): + """A dummy decorator to stand in for the real mcp.tool decorator.""" + return func + +mcp = type('mcp', (), {'tool': tool}) + +@mcp.tool +def proteomicsannotationhubdata_rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, + script_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Executes an R script using the Rscript command-line interface. + + This tool serves as a generic wrapper for Rscript, enabling the execution of R code + that can leverage Bioconductor packages like proteomicsannotationhubdata. + It allows running R code from a file or directly from string expressions. + + Args: + script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute. Mutually exclusive with 'script_file'. + verbose: If True, enables verbose output, printing information on progress (--verbose). + default_packages: A comma-separated list of packages to load by default (e.g., "utils,graphics"). + save: If True, the workspace will be saved at the end of the session (--save). + no_environ: If True, site and user environment files will not be read (--no-environ). + no_site_file: If True, the site-wide Rprofile will not be read (--no-site-file). + no_init_file: If True, the user's R profile will not be read (--no-init-file). + restore: If True, previously saved objects will be restored at startup (--restore). + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + script_args: A list of arguments to be passed to the R script itself. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Note: This wrapper cannot automatically detect output files generated by the R script. + """ + # 1. Input Validation + if script_file and expressions: + raise ValueError("Cannot specify both 'script_file' and 'expressions'. They are mutually exclusive.") + if not script_file and not expressions: + raise ValueError("Must specify either 'script_file' or 'expressions' to execute.") + + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + command = ["Rscript"] + + if verbose: + command.append("--verbose") + if default_packages: + command.extend(["--default-packages", default_packages]) + if save: + command.append("--save") + if no_environ: + command.append("--no-environ") + if no_site_file: + command.append("--no-site-file") + if no_init_file: + command.append("--no-init-file") + if restore: + command.append("--restore") + if vanilla: + command.append("--vanilla") + + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + elif script_file: + command.append(str(script_file)) + + if script_args: + command.extend(script_args) + + command_str = " ".join(command) + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Make sure R is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the R script returns a non-zero exit code + return { + "command_executed": command_str, + "stdout": e.stdout or "", + "stderr": e.stderr or "", + "output_files": [] + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..593b3d2dfe83e0a6468ed0bfffc56b3651c63976 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_proteomicsannotationhubdata' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8ac5970dd6840a7998007627da87e4f60be9c51 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-proteomicsannotationhubdata: + build: . + image: mcp-bioconductor-proteomicsannotationhubdata:latest + container_name: mcp-bioconductor-proteomicsannotationhubdata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-proteomicsannotationhubdata + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac7f8e4fe821d39719f5a0a64a7123c5d0691d97 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-proteomicsannotationhubdata + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3f2bf309ffe7ffbc844c764b6d238665b9b9f7d6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-protgenerics via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-protgenerics -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-protgenerics_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-protgenerics_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-protgenerics_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/__pycache__/bioconductor-protgenerics_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/__pycache__/bioconductor-protgenerics_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb895aa13ce85a06595c978e8453dbe638c4971e Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/__pycache__/bioconductor-protgenerics_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..66bf7a1b0ec4d3de2a87d88e5dd02a170b925a2a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py @@ -0,0 +1,85 @@ +import subprocess +from pathlib import Path +from typing import List, Optional +import mcp + +@mcp.tool( + name="protgenerics_run_r_script", + description="Executes a user-provided R script in an environment with bioconductor-protgenerics." +) +def run_r_script( + script_path: Path, + args: Optional[List[str]] = None, +) -> dict: + """ + Executes a given R script using the 'Rscript' command. + + This tool serves as a generic executor for R scripts within an environment + where the 'bioconductor-protgenerics' package is expected to be available. + The 'bioconductor-protgenerics' package itself does not provide a direct + command-line interface; it is a library of S4 generic functions for + proteomics analysis, intended to be used within R scripts by other packages. + + Therefore, instead of wrapping non-existent subcommands, this tool allows + you to run your own R script that utilizes the functionality provided by + 'bioconductor-protgenerics' or packages that depend on it. + + Args: + script_path: Path to the R script to be executed. + args: A list of optional command-line arguments to pass to the R script. + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and return code. + """ + # 1. Input validation + if not script_path.is_file(): + raise FileNotFoundError(f"The specified R script was not found: {script_path}") + + if args is None: + args = [] + + # 2. Command construction + command = ["Rscript", str(script_path)] + args + command_str = " ".join(command) + + # 3. Subprocess execution and error handling + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = process.stdout + stderr = process.stderr + return_code = process.returncode + + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH.", + "return_code": -1, + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the R script itself fails (returns a non-zero exit code) + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [] + } + + # 4. Structured result return + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "return_code": return_code, + "output_files": [] # Output files must be managed by the R script itself and their paths known beforehand. + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc227bf149b246d7c1f8e2d78cba137dfd42da4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_protgenerics' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..47e13413587e0d6524543a5a4c25700d07c47e08 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/app/requirements.txt @@ -0,0 +1 @@ +mcp==1.27.0 diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8e1d8d8096c32ba24e5823365e99b8573189e31a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-protgenerics: + build: . + image: mcp-bioconductor-protgenerics:latest + container_name: mcp-bioconductor-protgenerics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-protgenerics + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d17c7b69d3b821e749569b909c88ec485482063c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-protgenerics + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..062b47df16d08f6173721af25952519f73dfcafa --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-protgenerics/requirements.txt @@ -0,0 +1,3 @@ +mcp==1.27.0 +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0490536356ac972684113e03f94ef6e5a5ed5edb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rforproteomics via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rforproteomics -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-rforproteomics_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rforproteomics_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rforproteomics_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/app/__pycache__/bioconductor-rforproteomics_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/app/__pycache__/bioconductor-rforproteomics_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22c9d872d3111e99a6795bebbc34cdf4eb6fc7a6 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/app/__pycache__/bioconductor-rforproteomics_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..11851eb51bc71813affd06c1385fe37f7a179070 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_server.py @@ -0,0 +1,140 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# MCP decorator is assumed to be available in the execution environment. +# +# @mcp.tool +# def rscript(...): +# ... + +def _mcp_tool_dummy_decorator(func): + """A dummy decorator to allow the code to be syntactically valid.""" + return func + +# In a real MCP environment, the @mcp.tool decorator would be provided. +# For this example, we use a dummy decorator. +mcp = type('mcp', (), {'tool': staticmethod(_mcp_tool_dummy_decorator)}) + + +@mcp.tool +def rscript( + file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper for the Rscript utility, allowing for the execution + of R code from a file or directly from string expressions. It supports various + options to control the R session's environment and behavior. Note that either + 'file' or 'expressions' must be provided, but not both. + + Args: + file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to be executed. Mutually exclusive with 'file'. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, enables verbose output, printing information on progress. Corresponds to --verbose. + default_packages: A comma-separated list of package names to be loaded by default (e.g., "utils,graphics"). + Corresponds to --default-packages. + save: If True, saves the workspace at the end of the session. Corresponds to --save. + no_environ: If True, prevents reading of site and user environment files. Corresponds to --no-environ. + no_site_file: If True, prevents reading of the site-wide Rprofile. Corresponds to --no-site-file. + no_init_file: If True, prevents reading of the user R profile. Corresponds to --no-init-file. + restore: If True, restores previously saved objects at startup. Corresponds to --restore. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + Corresponds to --vanilla. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Since Rscript does not have a dedicated output file parameter, 'output_files' will be empty. + """ + # 1. Input Validation + if not file and not expressions: + raise ValueError("Either 'file' or 'expressions' must be provided.") + if file and expressions: + raise ValueError("'file' and 'expressions' are mutually exclusive and cannot be used together.") + if file: + if not file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {file}") + + # 2. Command Construction + cmd = ["Rscript"] + + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.extend(["--default-packages", default_packages]) + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + if vanilla: + cmd.append("--vanilla") + + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + elif file: + cmd.append(str(file)) + + if script_args: + cmd.extend(script_args) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # 3. Subprocess Execution + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + error_message = "Error: 'Rscript' command not found. Please ensure R is installed and accessible in the system's PATH." + logging.error(error_message) + # This is a critical configuration error, so we return a structured error + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_message, + "output_files": [] + } + except subprocess.CalledProcessError as e: + logging.error(f"Rscript execution failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 4. Structured Result Return + # Rscript does not have a defined output file parameter. Any files created + # are determined by the script's own logic. + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6ec748f5d4b2bc3601abc5e90c0e4a8b274b9c0a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rforproteomics' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8777e2825f2c61ac247216ca6df83d0b77132802 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rforproteomics: + build: . + image: mcp-bioconductor-rforproteomics:latest + container_name: mcp-bioconductor-rforproteomics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rforproteomics + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..add6d6abe9185029b539778ee50f8561cb2dbfcc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rforproteomics + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rforproteomics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..94ff6db8337a62074ee000d9331841b428126b2e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scbfa via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scbfa -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-scbfa_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scbfa_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scbfa_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/app/__pycache__/bioconductor-scbfa_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/app/__pycache__/bioconductor-scbfa_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a39eee0a7a5a39d8edad24e0534d6bd30315a10a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/app/__pycache__/bioconductor-scbfa_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b179a68910946e7b326ce16ef4b74822ce00516 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_server.py @@ -0,0 +1,183 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# @mcp.tool() is a placeholder for the actual decorator. +# The final code should be used in an environment where mcp is available. + +def mcp_tool(): + """A dummy decorator for standalone execution.""" + def decorator(f): + return f + return decorator + +@mcp_tool() +def run_scbfa( + input_data: Path, + output_prefix: str, + num_factors: int, + max_iter: int = 1000, + min_rel_err: float = 1e-08, + abs_err: float = 1e-06, + a: float = 0.1, + b: float = 0.1, + alpha: float = 0.1, + beta: float = 0.1, + verbose: bool = False, + rscript_executable: str = "Rscript", + rscript_options: Optional[List[str]] = None, +): + """ + Runs Single-Cell Bayesian Factor Analysis (scBFA) on a given count matrix. + + This tool generates and executes an R script to perform scBFA, saving the + resulting factor loadings and scores to specified output files. It requires + the 'scBFA' Bioconductor package and the 'data.table' CRAN package to be + installed in the R environment. + + Args: + input_data: Path to the input data file (e.g., CSV format). + The data should be a numeric matrix of counts (genes x cells). + output_prefix: Prefix for the output files. Two files will be generated: + _loadings.csv and _scores.csv. + num_factors: The number of latent factors to compute. + max_iter: Maximum number of iterations for the algorithm. + min_rel_err: Minimum relative error for convergence. + abs_err: Absolute error for convergence. + a: Hyperparameter for the gamma prior on factor loadings. + b: Hyperparameter for the gamma prior on factor loadings. + alpha: Hyperparameter for the gamma prior on factor scores. + beta: Hyperparameter for the gamma prior on factor scores. + verbose: If True, enables verbose output from the R script. + rscript_executable: The path to the Rscript executable. + rscript_options: A list of additional options to pass to Rscript + (e.g., ["--vanilla", "--verbose"]). + """ + # 1. Input Validation + if not input_data.is_file(): + raise FileNotFoundError(f"Input data file not found: {input_data}") + if num_factors <= 0: + raise ValueError("num_factors must be a positive integer.") + if max_iter <= 0: + raise ValueError("max_iter must be a positive integer.") + if not output_prefix: + raise ValueError("output_prefix cannot be empty.") + + # 2. R Script Generation + verbose_r = "TRUE" if verbose else "FALSE" + + r_script_content = f""" + # Ensure required packages are installed and loaded + if (!requireNamespace("scBFA", quietly = TRUE)) {{ + stop("The 'scBFA' package is not installed. Please install it from Bioconductor.") + }} + if (!requireNamespace("data.table", quietly = TRUE)) {{ + stop("The 'data.table' package is not installed. Please install it from CRAN.") + }} + library(scBFA) + library(data.table) + + # --- Parameters --- + input_file <- "{str(input_data.resolve())}" + output_prefix <- "{output_prefix}" + num_factors <- {num_factors} + max_iter <- {max_iter} + min_rel_err <- {min_rel_err} + abs_err <- {abs_err} + a <- {a} + b <- {b} + alpha <- {alpha} + beta <- {beta} + verbose_r <- {verbose_r} + + # --- Main Logic --- + tryCatch({{ + message("Reading input data from: ", input_file) + counts_matrix <- as.matrix(fread(input_file)) + message("Input data dimensions: ", paste(dim(counts_matrix), collapse = " x ")) + + message("Running scBFA with ", num_factors, " factors...") + bfa_result <- scBFA( + x = counts_matrix, + num_factors = num_factors, + max_iter = max_iter, + min_rel_err = min_rel_err, + abs_err = abs_err, + a = a, + b = b, + alpha = alpha, + beta = beta, + verbose = verbose_r + ) + message("scBFA completed.") + + # --- Save Results --- + loadings_file <- paste0(output_prefix, "_loadings.csv") + scores_file <- paste0(output_prefix, "_scores.csv") + + message("Saving factor loadings to: ", loadings_file) + write.csv(bfa_result$L, file = loadings_file, row.names = FALSE) + + message("Saving factor scores to: ", scores_file) + write.csv(bfa_result$F, file = scores_file, row.names = FALSE) + + message("Analysis finished successfully.") + }}, error = function(e) {{ + message("An error occurred during scBFA execution: ") + message(conditionMessage(e)) + quit(status = 1, save = "no") + }}) + """ + + # 3. Subprocess Execution + output_files_map = { + "factor_loadings": Path(f"{output_prefix}_loadings.csv").resolve(), + "factor_scores": Path(f"{output_prefix}_scores.csv").resolve() + } + + r_script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + cmd = [rscript_executable] + if rscript_options: + cmd.extend(rscript_options) + cmd.append(r_script_path) + + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {k: str(v) for k, v in output_files_map.items()} + } + + except FileNotFoundError: + return { + "command_executed": f"{rscript_executable} ...", + "stdout": "", + "stderr": f"Error: '{rscript_executable}' not found. Is R installed and in your system's PATH?", + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {} + } + finally: + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..91f0c1c503f49e85d297d4362ccd9526c5b99401 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/app/bioconductor-scbfa_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scbfa' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8ddfddb024ad9c91d3fc9d4cd013f1cb9d9e00b1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scbfa: + build: . + image: mcp-bioconductor-scbfa:latest + container_name: mcp-bioconductor-scbfa + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scbfa + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0e5aaa29f0c7f136ee493fe61a322bcf41a2787f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scbfa + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scbfa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c926501a4fd661158e18096512c4e1f1481c6b4a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scdataviz via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scdataviz -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-scdataviz_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scdataviz_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scdataviz_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/app/__pycache__/bioconductor-scdataviz_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/app/__pycache__/bioconductor-scdataviz_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8611d2784fc498f2c024f2d417fcf1093baba718 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/app/__pycache__/bioconductor-scdataviz_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6262e5ea82010f6d2290e68c395b98fca31465c2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_server.py @@ -0,0 +1,173 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def rscript( + file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[List[str]] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +) -> dict: + """ + Executes an R script or R expressions using the Rscript command-line interface. + + This tool serves as a wrapper for Rscript, allowing you to run R code from a file + or directly as command-line expressions. It provides control over the R session's + environment and startup behavior. You must provide either a script file or a list + of expressions to execute, but not both. + + Args: + file: Path to the R script file to be executed. + expressions: A list of R expressions to execute. Use instead of 'file'. + script_args: A list of arguments to be passed to the R script. + verbose: If True, print information on progress. + default_packages: A list of package names to be loaded by default. + save: If True, save the workspace at the end of the session. + no_environ: If True, do not read the site and user environment files. + no_site_file: If True, do not read the site-wide Rprofile. + no_init_file: If True, do not read the user R profile. + restore: If True, restore previously saved objects at startup. + vanilla: If True, combine --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ for a clean session. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # 1. Input Validation + if (file is None and not expressions) or (file is not None and expressions): + raise ValueError("You must provide either 'file' or 'expressions', but not both.") + + if file and not file.is_file(): + raise FileNotFoundError(f"The specified R script file does not exist: {file}") + + # 2. Command Construction + cmd = ["Rscript"] + + # Add session control options + if vanilla: + cmd.append("--vanilla") + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + if verbose: + cmd.append("--verbose") + if default_packages: + packages_str = ",".join(default_packages) + cmd.append(f"--default-packages={packages_str}") + + # Add the script file or expressions to execute + if file: + cmd.append(str(file)) + elif expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + # Add arguments for the script itself + if script_args: + cmd.extend(script_args) + + command_executed = shlex.join(cmd) + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}", + "output_files": [] + } + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # Rscript itself doesn't guarantee output files; the script's content does. + } + +@mcp.tool +def rscript_version() -> dict: + """ + Retrieves the version of the Rscript interpreter. + + This function executes `Rscript --version` to get the version information of the + installed R environment. + + Returns: + A dictionary containing the executed command, stdout (version info), and stderr. + """ + cmd = ["Rscript", "--version"] + command_executed = shlex.join(cmd) + + try: + # Note: Rscript --version prints to stderr, so we capture both. + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + # Combine stdout and stderr as version info can be in either + output = result.stdout + result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH.", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript version check failed with return code {e.returncode}", + } + + return { + "command_executed": command_executed, + "stdout": output, + "stderr": "", # Stderr content is moved to stdout for consistency + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae6d36752c30e737cf704bf9bcfccc71b2e9591 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scdataviz' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c505a0ca6bc8f3d61067bbe38ad54952de78ce99 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scdataviz: + build: . + image: mcp-bioconductor-scdataviz:latest + container_name: mcp-bioconductor-scdataviz + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scdataviz + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6dcce732cd877fc501a28cde5132e3bd3d44d826 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scdataviz + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scdataviz/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5f8e016875df53696a5db64cc303a6d7da461a8e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scmageck via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scmageck -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-scmageck_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scmageck_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scmageck_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/app/__pycache__/bioconductor-scmageck_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/app/__pycache__/bioconductor-scmageck_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ae44dcf8ac6b7b114dbe73ae06feec642685e6a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/app/__pycache__/bioconductor-scmageck_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/app/bioconductor-scmageck_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/app/bioconductor-scmageck_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4483cbe8ab79d00e30f95d2ce9633b98f3f29ade --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/app/bioconductor-scmageck_server.py @@ -0,0 +1,277 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any +import tempfile + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_scmageck' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def scmageck_eff_estimate( + count_matrix_path: str, + barcode_file_path: str, + output_rds_path: str, + neg_control: str = "non-target", + perturb_gene: Optional[str] = None, + cell_column: str = "cell", + barcode_column: str = "barcode", + gene_column: str = "gene" +): + """ + Estimate the efficiency of guides using the scmageck_eff_estimate function. + + Args: + count_matrix_path: Path to the gene expression count matrix (CSV/TSV or RDS). + barcode_file_path: Path to the barcode-to-cell mapping file (CSV/TSV). + output_rds_path: Path where the resulting RDS object will be saved. + neg_control: Name of the negative control gene/guide. + perturb_gene: Specific gene to estimate efficiency for. If None, estimates for all. + cell_column: Column name for cell identifiers in barcode file. + barcode_column: Column name for barcode identifiers in barcode file. + gene_column: Column name for gene identifiers in barcode file. + """ + # Validate inputs + count_path = Path(count_matrix_path) + bc_path = Path(barcode_file_path) + out_path = Path(output_rds_path) + + if not count_path.exists(): + return {"error": f"Count matrix not found: {count_matrix_path}"} + if not bc_path.exists(): + return {"error": f"Barcode file not found: {barcode_file_path}"} + + # Ensure output directory exists + out_path.parent.mkdir(parents=True, exist_ok=True) + + # Construct R script + perturb_gene_cmd = f'"{perturb_gene}"' if perturb_gene else "NULL" + + r_script = f""" + library(scmageck) + + # Load data + if (grepl(".rds$", "{count_path}", ignore.case = TRUE)) {{ + counts <- readRDS("{count_path}") + }} else {{ + counts <- read.table("{count_path}", header = TRUE, sep = ",", row.names = 1) + }} + + barcodes <- read.table("{bc_path}", header = TRUE, sep = ",") + + # Run efficiency estimation + eff_result <- scmageck_eff_estimate( + count_mat = counts, + barcode_df = barcodes, + negctrl = "{neg_control}", + perturb_gene = {perturb_gene_cmd}, + cell_col = "{cell_column}", + bc_col = "{barcode_column}", + gene_col = "{gene_column}" + ) + + saveRDS(eff_result, file = "{out_path}") + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"scmageck_eff_estimate on {count_matrix_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def scmageck_lr( + expression_matrix_path: str, + perturbation_matrix_path: str, + output_csv_path: str, + lambda_val: float = 0.01, + n_cores: int = 1 +): + """ + Perform Linear Regression analysis to identify gene targets using scmageck_lr. + + Args: + expression_matrix_path: Path to the expression matrix (RDS or CSV). + perturbation_matrix_path: Path to the perturbation matrix (RDS or CSV). + output_csv_path: Path to save the regression results (CSV). + lambda_val: Penalty parameter for regression. + n_cores: Number of CPU cores to use. + """ + expr_path = Path(expression_matrix_path) + pert_path = Path(perturbation_matrix_path) + out_path = Path(output_csv_path) + + if not expr_path.exists() or not pert_path.exists(): + return {"error": "Input expression or perturbation matrix not found."} + + r_script = f""" + library(scmageck) + + # Load matrices + load_mat <- function(p) {{ + if (grepl(".rds$", p, ignore.case = TRUE)) return(readRDS(p)) + return(as.matrix(read.table(p, header = TRUE, row.names = 1, sep = ","))) + }} + + expr_mat <- load_mat("{expr_path}") + pert_mat <- load_mat("{pert_path}") + + # Run LR + lr_result <- scmageck_lr( + m_matrix = expr_mat, + g_matrix = pert_mat, + lambda = {lambda_val} + ) + + # Handle result (scmageck_lr returns a list or matrix depending on version) + write.csv(lr_result, file = "{out_path}") + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "scmageck_lr", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def scmageck_optim_perturb( + rds_input_path: str, + output_rds_path: str, + max_iter: int = 100, + threshold: float = 1e-4 +): + """ + Optimize the perturbation matrix using the scmageck_optim_perturb function. + + Args: + rds_input_path: Path to an RDS file containing the scmageck object/list. + output_rds_path: Path to save the optimized RDS object. + max_iter: Maximum number of iterations for optimization. + threshold: Convergence threshold. + """ + in_path = Path(rds_input_path) + out_path = Path(output_rds_path) + + if not in_path.exists(): + return {"error": f"Input RDS file not found: {rds_input_path}"} + + r_script = f""" + library(scmageck) + + obj <- readRDS("{in_path}") + + # Run optimization + # Note: scmageck_optim_perturb parameters may vary by version; + # usually takes the result of eff_estimate + optim_result <- scmageck_optim_perturb( + eff_obj = obj, + max_iter = {max_iter}, + tol = {threshold} + ) + + saveRDS(optim_result, file = "{out_path}") + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "scmageck_optim_perturb", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def scmageck_get_score( + rds_input_path: str, + output_csv_path: str +): + """ + Extract scores/p-values from a processed scmageck RDS object. + + Args: + rds_input_path: Path to the RDS file generated by scmageck_lr or eff_estimate. + output_csv_path: Path to save the extracted scores as CSV. + """ + in_path = Path(rds_input_path) + out_path = Path(output_csv_path) + + if not in_path.exists(): + return {"error": "Input RDS file not found."} + + r_script = f""" + library(scmageck) + obj <- readRDS("{in_path}") + + # Extracting score logic depends on the object structure + if (is.list(obj) && "score" %in% names(obj)) {{ + write.csv(obj$score, file = "{out_path}") + }} else {{ + # Fallback for matrix results + write.csv(as.data.frame(obj), file = "{out_path}") + }} + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "scmageck_get_score", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/app/bioconductor-scmageck_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/app/bioconductor-scmageck_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d683d0495b220029d381021330182e75662e23d8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/app/bioconductor-scmageck_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/app/bioconductor-scmageck_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scmageck' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8b52be87679997a875f56ca4fd7e866ffb2037e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scmageck: + build: . + image: mcp-bioconductor-scmageck:latest + container_name: mcp-bioconductor-scmageck + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scmageck + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce0115c2ac316e90558b3f5a4f73c8a8d45677b2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scmageck + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scmageck/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..87c58c18dc99720b13df8531fe3ec735a53a472d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-singlecellmultimodal via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-singlecellmultimodal -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-singlecellmultimodal_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-singlecellmultimodal_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-singlecellmultimodal_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/app/__pycache__/bioconductor-singlecellmultimodal_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/app/__pycache__/bioconductor-singlecellmultimodal_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea0f10664bd428146e5ad1f164ff697169a81013 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/app/__pycache__/bioconductor-singlecellmultimodal_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8d9f88e48b26b28ffaf85bf24967f5017bd10ae4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_server.py @@ -0,0 +1,143 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# MCP decorator is not defined here, but the function is written +# to be compatible with it, as per the instructions. +# from mcp import tool as mcp_tool +# For demonstration, we'll use a placeholder decorator. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper around Rscript, allowing for the execution of R code + either from a file or directly from command-line expressions. It supports various + options to control the R session's environment and behavior. + + Args: + script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute. Mutually exclusive with 'script_file'. + script_args: A list of arguments to be passed to the R script specified by 'script_file'. + verbose: If True, prints information on progress. + default_packages: A comma-separated list of package names to be loaded by default. + save: If True, the workspace will be saved at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, site and user environment files will not be read. Ignored if 'vanilla' is True. + no_site_file: If True, the site-wide Rprofile will not be read. Ignored if 'vanilla' is True. + no_init_file: If True, the user's R profile will not be read. Ignored if 'vanilla' is True. + restore: If True, previously saved objects will be restored at startup. Ignored if 'vanilla' is True. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + This provides a "clean" R session. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of potential output files. + """ + # 1. Input Validation + if not script_file and not expressions: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + if script_file and expressions: + raise ValueError("'script_file' and 'expressions' are mutually exclusive.") + if script_args and not script_file: + raise ValueError("'script_args' can only be used when a 'script_file' is specified.") + + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + command = ["Rscript"] + + # The --vanilla flag is a combination of other flags. + if vanilla: + command.append("--vanilla") + else: + if save: + command.append("--save") + if no_environ: + command.append("--no-environ") + if no_site_file: + command.append("--no-site-file") + if no_init_file: + command.append("--no-init-file") + if restore: + command.append("--restore") + + if verbose: + command.append("--verbose") + + if default_packages: + command.append(f"--default-packages={default_packages}") + + # Add the script file or expressions to the command + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + elif script_file: + command.append(str(script_file)) + if script_args: + command.extend(script_args) + + command_str = " ".join(command) + logger.info(f"Executing command: {command_str}") + + # 3. Subprocess Execution + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + logger.info("Rscript executed successfully.") + + except FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in your PATH.") + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript command not found. Please ensure R is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"Rscript execution failed with return code {e.returncode}.") + logger.error(f"Stderr: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 4. Structured Result Return + # Rscript itself does not define output files; the script being run does. + # The list of output_files is therefore empty unless explicitly handled. + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..79ca73eca958fe1eae72da919d172f1897aabf77 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_singlecellmultimodal' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a6f42b0a459288cb5086ca83ad44e9ad694c6bdb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-singlecellmultimodal: + build: . + image: mcp-bioconductor-singlecellmultimodal:latest + container_name: mcp-bioconductor-singlecellmultimodal + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-singlecellmultimodal + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..30cfd95ed178d3a724fdc76a21229d88702c0edc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-singlecellmultimodal + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellmultimodal/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..af0d18bfadbb9ce49b2c0c396674dc0edb2e779b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-smoothclust via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-smoothclust -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-smoothclust_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-smoothclust_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-smoothclust_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/__pycache__/bioconductor-smoothclust_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/__pycache__/bioconductor-smoothclust_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3dcafc8aeea99cce5d7fa8ba170c523501fcc8c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/__pycache__/bioconductor-smoothclust_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_server.py new file mode 100644 index 0000000000000000000000000000000000000000..56ca1d83d467e96659352ff007029418dabecfc5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_server.py @@ -0,0 +1,241 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# NO NEED to import mcp as per instructions + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_smoothclust' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_smoothclust_analysis( + input_spatial_experiment_path: Path, + output_spatial_experiment_path: Path, + output_plot_path: Path, + k_neighbors: int = 10, + smoothing_type: str = "knn", + n_clusters: int = 5, + clustering_method: str = "kmeans", + seed: Optional[int] = None, + r_path: str = "Rscript", +) -> Dict[str, Any]: + """ + Performs spatial domain identification and spatially-aware clustering using the bioconductor-smoothclust R package. + + This tool smooths gene expression profiles across neighboring spatial locations and then applies + unsupervised clustering to identify spatial domains with smooth boundaries. + + NOTE: The provided documentation for bioconductor-smoothclust describes an R package and its + purpose but does not detail a command-line interface or specific R function signatures. + Therefore, the parameters and the R script logic within this MCP tool are inferred based + on the package's description and common spatial transcriptomics analysis workflows. + The actual R function names and parameter names used in the generated R script are illustrative + and based on typical Bioconductor package usage patterns. + + Args: + input_spatial_experiment_path: Path to an RData file containing a SpatialExperiment object. + This object should contain gene expression data and spatial coordinates. + output_spatial_experiment_path: Path to save the resulting SpatialExperiment object, + which will include the clustering results. + output_plot_path: Path to save a visualization of the identified spatial domains. + (e.g., a PNG image). + k_neighbors: Number of nearest neighbors to use for spatial smoothing. + Must be a positive integer. + smoothing_type: Type of spatial smoothing to apply. + Valid options are "knn" (k-nearest neighbors) or "graph" (spatial graph). + n_clusters: The desired number of spatial domains (clusters) to identify. + Must be a positive integer. + clustering_method: The clustering algorithm to use. + Valid options are "kmeans" or "hclust" (hierarchical clustering). + seed: An optional random seed for reproducibility. If not provided, a random seed will be used. + r_path: Path to the Rscript executable. Defaults to "Rscript" assuming it's in PATH. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + + Raises: + ValueError: If input parameters are invalid. + subprocess.CalledProcessError: If the Rscript command fails. + RuntimeError: If the R script encounters a critical error. + """ + + # 1. Input Validation + if not input_spatial_experiment_path.is_file(): + raise ValueError(f"Input SpatialExperiment file not found: {input_spatial_experiment_path}") + if input_spatial_experiment_path.suffix.lower() not in [".rda", ".rdata"]: + raise ValueError(f"Input SpatialExperiment file must be an RData file (.rda or .rdata): {input_spatial_experiment_path}") + + if k_neighbors <= 0: + raise ValueError("k_neighbors must be a positive integer.") + if smoothing_type not in ["knn", "graph"]: + raise ValueError(f"Invalid smoothing_type: {smoothing_type}. Must be 'knn' or 'graph'.") + if n_clusters <= 0: + raise ValueError("n_clusters must be a positive integer.") + if clustering_method not in ["kmeans", "hclust"]: + raise ValueError(f"Invalid clustering_method: {clustering_method}. Must be 'kmeans' or 'hclust'.") + + # Ensure output directories exist + output_spatial_experiment_path.parent.mkdir(parents=True, exist_ok=True) + output_plot_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Prepare R script + # The R script is constructed based on the typical usage of Bioconductor packages + # and the described functionality of 'smoothclust'. + # Specific function names like 'smoothclust_workflow', 'smooth_expression', + # and 'cluster_spatial_domains' are inferred as they are not provided in the + # given documentation. + r_script_content = f""" + # Load necessary Bioconductor packages + suppressPackageStartupMessages({{ + library(smoothclust) + library(SpatialExperiment) + library(SummarizedExperiment) + library(ggplot2) # For plotting spatial domains + }}) + + # Set random seed for reproducibility if provided + seed_val <- {seed if seed is not None else 'NULL'} + if (!is.null(seed_val)) {{ + set.seed(seed_val) + }} + + # Define input and output paths + input_spe_path <- "{input_spatial_experiment_path.resolve()}" + output_spe_path <- "{output_spatial_experiment_path.resolve()}" + output_plot_path <- "{output_plot_path.resolve()}" + + # Load SpatialExperiment object + if (!file.exists(input_spe_path)) {{ + stop(paste0("Input SpatialExperiment file not found: ", input_spe_path)) + }} + + # List objects before loading to identify the new SpatialExperiment object + objects_before_load <- ls() + load(input_spe_path) + objects_after_load <- ls() + + # Find the SpatialExperiment object that was just loaded + new_objects <- setdiff(objects_after_load, objects_before_load) + spe <- NULL + for (obj_name in new_objects) {{ + if (inherits(get(obj_name), "SpatialExperiment")) {{ + spe <- get(obj_name) + message(paste0("Found SpatialExperiment object named '", obj_name, "'.")) + break + }} + }} + + if (is.null(spe)) {{ + stop("No 'SpatialExperiment' object found in the input RData file.") + }} + + message("Starting smoothclust analysis workflow...") + tryCatch({{ + # Attempt to use a hypothetical smoothclust_workflow function if it exists + # This is the most direct way if the package provides an integrated workflow. + if (exists("smoothclust_workflow") && is.function(smoothclust_workflow)) {{ + spe <- smoothclust_workflow( + spe, + k = {k_neighbors}, + n_clusters = {n_clusters}, + type = "{smoothing_type}", + method = "{clustering_method}" + ) + }} else if (exists("smooth_expression") && is.function(smooth_expression) && + exists("cluster_spatial_domains") && is.function(cluster_spatial_domains)) {{ + # If a workflow function is not found, try sequential calls + message("smoothclust_workflow not found, attempting sequential smooth_expression and cluster_spatial_domains.") + spe <- smooth_expression(spe, k = {k_neighbors}, type = "{smoothing_type}") + spe <- cluster_spatial_domains(spe, n_clusters = {n_clusters}, method = "{clustering_method}") + }} else {{ + stop("Could not find expected smoothclust functions (smoothclust_workflow or smooth_expression/cluster_spatial_domains).") + }} + }}, error = function(e) {{ + stop(paste0("Error during smoothclust analysis: ", e$message)) + }}) + + message("Spatial clustering complete.") + + # Save the updated SpatialExperiment object + save(spe, file = output_spe_path) + message(paste0("Updated SpatialExperiment object saved to: ", output_spe_path)) + + # Generate and save a plot of spatial domains + # This assumes a 'spatial_domains' column is added to colData(spe) by smoothclust + if ("spatial_domains" %in% colnames(colData(spe))) {{ + message("Generating spatial domains plot...") + + # Extract spatial coordinates and domain assignments + spatial_coords <- spatialCoords(spe) + plot_data <- data.frame( + x = spatial_coords[,1], + y = spatial_coords[,2], + domain = colData(spe)$spatial_domains + ) + + # Create ggplot object + p <- ggplot(plot_data, aes(x = x, y = y, color = factor(domain))) + + geom_point(size = 1, alpha = 0.8) + + theme_minimal() + + labs(title = "Spatial Domains Identified by smoothclust", + color = "Domain", + x = "Spatial Coordinate X", + y = "Spatial Coordinate Y") + + coord_fixed() # Maintain aspect ratio for spatial plots + + # Save the plot + ggsave(output_plot_path, plot = p, width = 8, height = 7, units = "in") + message(paste0("Spatial domains plot saved to: ", output_plot_path)) + }} else {{ + warning("No 'spatial_domains' column found in colData(spe). Skipping plot generation.") + }} + """ + + # 3. Execute R script + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as tmp_r_script: + tmp_r_script.write(r_script_content) + tmp_r_script_path = Path(tmp_r_script.name) + + command = [r_path, str(tmp_r_script_path)] + command_executed = " ".join(command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # Clean up temp file on error + tmp_r_script_path.unlink(missing_ok=True) + raise RuntimeError( + f"Rscript command failed with exit code {e.returncode}.\n" + f"Command: {e.cmd}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + # Clean up temporary R script + tmp_r_script_path.unlink(missing_ok=True) + + # 4. Return structured output + output_files = [str(output_spatial_experiment_path.resolve())] + if output_plot_path.exists(): + output_files.append(str(output_plot_path.resolve())) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2577d4479ba1702ac057ba102b74b4e94dccac19 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_smoothclust' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4e92c9336fbd161707ba16e39bbc01bba9dd47b0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-smoothclust: + build: . + image: mcp-bioconductor-smoothclust:latest + container_name: mcp-bioconductor-smoothclust + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-smoothclust + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2d5df1756427dc4ca1e3c6a3c771f49e98bf027a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-smoothclust + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoothclust/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoppix/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoppix/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dcfd2d063689b187f49eae4f7660b5c9df6a11b4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoppix/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-smoppix via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-smoppix -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-smoppix_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-smoppix_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-smoppix_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoppix/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoppix/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b5562dc6654f584c7cf609f3a94015453c6d2575 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoppix/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-smoppix: + build: . + image: mcp-bioconductor-smoppix:latest + container_name: mcp-bioconductor-smoppix + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-smoppix + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoppix/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoppix/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e600b2495c03e14f646ed4c274f6e1c09292f831 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-smoppix/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-smoppix + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..47f9e4a080d7864e5083ec0fd055069599e63e8d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-sparsematrixstats via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-sparsematrixstats -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-sparsematrixstats_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-sparsematrixstats_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-sparsematrixstats_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/__pycache__/bioconductor-sparsematrixstats_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/__pycache__/bioconductor-sparsematrixstats_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fca14910d3d2b94b2719631f200da497c0c0776 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/__pycache__/bioconductor-sparsematrixstats_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/bioconductor-sparsematrixstats_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/bioconductor-sparsematrixstats_server.py new file mode 100644 index 0000000000000000000000000000000000000000..32fa2b2188a9cb138120373836cb2b9abed8050e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/bioconductor-sparsematrixstats_server.py @@ -0,0 +1,227 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any, Set + +# In a real MCP implementation, the 'mcp' object would be imported. +# For this standalone script, we define a placeholder for the mcp.tool decorator. +class _MCP: + def tool(self, *args, **kwargs): + """A placeholder decorator for MCP tools.""" + def decorator(func): + return func + return decorator + +mcp = _MCP() + +# A comprehensive set of all statistical functions available in the package. +SUPPORTED_STATS: Set[str] = { + # Column functions + "colAlls", "colAnyNAs", "colAnys", "colAvgsPerRowSet", "colCollapse", "colCounts", + "colCummaxs", "colCummins", "colCumprods", "colCumsums", "colDiffs", "colIQRDiffs", + "colIQRs", "colLogSumExps", "colMadDiffs", "colMads", "colMaxs", "colMeans2", + "colMedians", "colMins", "colOrderStats", "colProds", "colQuantiles", "colRanges", + "colRanks", "colSdDiffs", "colSds", "colSums2", "colTabulates", "colVarDiffs", + "colVars", "colWeightedMads", "colWeightedMeans", "colWeightedMedians", + "colWeightedSds", "colWeightedVars", + # Row functions + "rowAlls", "rowAnyNAs", "rowAnys", "rowAvgsPerColSet", "rowCollapse", "rowCounts", + "rowCummaxs", "rowCummins", "rowCumprods", "rowCumsums", "rowDiffs", "rowIQRDiffs", + "rowIQRs", "rowLogSumExps", "rowMadDiffs", "rowMads", "rowMaxs", "rowMeans2", + "rowMedians", "rowMins", "rowOrderStats", "rowProds", "rowQuantiles", "rowRanges", + "rowRanks", "rowSdDiffs", "rowSds", "rowSums2", "rowTabulates", "rowVarDiffs", + "rowVars", "rowWeightedMads", "rowWeightedMeans", "rowWeightedMedians", + "rowWeightedSds", "rowWeightedVars" +} + +VALID_TIES_METHODS: Set[str] = {"average", "first", "last", "random", "max", "min"} + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_sparsematrixstats' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_sparse_matrix_stats( + input_matrix: Path, + output_file: Path, + statistic: str, + idxs: Optional[List[int]] = None, + na_rm: bool = False, + use_names: bool = True, + probs: Optional[List[float]] = None, + weights: Optional[Path] = None, + ties_method: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes a statistical function from the R/Bioconductor sparseMatrixStats package. + + This tool serves as a command-line wrapper for the sparseMatrixStats R package, + allowing computation of summary statistics on sparse matrices. + + Dependencies: + - R installation is required. + - The following R packages must be installed: 'optparse', 'sparseMatrixStats', + 'Matrix', and 'readr'. + + Args: + input_matrix: Path to the input matrix file (must be in TSV format without headers). + output_file: Path to save the resulting statistics (will be in TSV format). + statistic: The name of the sparseMatrixStats function to run (e.g., 'colMeans2', 'rowSds'). + idxs: An optional list of 1-based row or column indices to subset the matrix. + na_rm: If True, remove NA values before computation (corresponds to na.rm=TRUE). + use_names: If True, preserve row/column names in the output (corresponds to useNames=TRUE). + probs: A list of probabilities (0.0 to 1.0) for quantile calculations. + weights: Path to a file containing weights for weighted statistical functions. + ties_method: Method for handling ties in ranking functions. Must be one of: + 'average', 'first', 'last', 'random', 'max', 'min'. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix}") + + if statistic not in SUPPORTED_STATS: + raise ValueError(f"Unsupported statistic '{statistic}'. Please choose from the supported list.") + + if 'Quantile' in statistic and not probs: + raise ValueError("Parameter 'probs' is required for quantile statistics.") + + if probs: + if not all(0.0 <= p <= 1.0 for p in probs): + raise ValueError("All values in 'probs' must be between 0.0 and 1.0.") + + if 'Weighted' in statistic and not weights: + raise ValueError("Parameter 'weights' is required for weighted statistics.") + + if weights and not weights.is_file(): + raise FileNotFoundError(f"Weights file not found: {weights}") + + if 'Rank' in statistic and ties_method and ties_method not in VALID_TIES_METHODS: + raise ValueError(f"Invalid 'ties_method': {ties_method}. Must be one of {VALID_TIES_METHODS}.") + + # --- R Script Generation --- + r_script_content = """ + suppressPackageStartupMessages(library(optparse)) + suppressPackageStartupMessages(library(sparseMatrixStats)) + suppressPackageStartupMessages(library(Matrix)) + suppressPackageStartupMessages(library(readr)) + + option_list <- list( + make_option(c("-i", "--input"), type="character", help="Input matrix file (TSV)"), + make_option(c("-o", "--output"), type="character", help="Output file for results"), + make_option(c("-s", "--statistic"), type="character", help="Statistic function to apply"), + make_option(c("--idxs"), type="character", default=NULL, help="Comma-separated integer indices"), + make_option(c("--na_rm"), action="store_true", default=FALSE, help="If TRUE, NAs are removed"), + make_option(c("--use_names"), action="store_true", default=TRUE, help="If TRUE, preserve names"), + make_option(c("--probs"), type="character", default=NULL, help="Comma-separated probabilities for quantiles"), + make_option(c("--weights"), type="character", default=NULL, help="Path to weights file"), + make_option(c("--ties_method"), type="character", default=NULL, help="Method for handling ties in ranks") + ) + + opts <- parse_args(OptionParser(option_list=option_list)) + + # Load data as a sparse matrix + mat_df <- readr::read_tsv(opts$input, col_names = FALSE, show_col_types = FALSE) + sparse_mat <- as(as.matrix(mat_df), "dgCMatrix") + + # Prepare arguments for the statistical function + args_list <- list(x = sparse_mat) + stat_func <- get(opts$statistic, asNamespace("sparseMatrixStats")) + func_args <- names(formals(stat_func)) + + if ("na.rm" %in% func_args) { args_list$na.rm <- opts$na_rm } + if ("useNames" %in% func_args) { args_list$useNames <- opts$use_names } + + if (!is.null(opts$idxs)) { + indices <- as.integer(unlist(strsplit(opts$idxs, ","))) + if (grepl("^row", opts$statistic)) { + args_list$rows <- indices + } else if (grepl("^col", opts$statistic)) { + args_list$cols <- indices + } + } + + if ("probs" %in% func_args && !is.null(opts$probs)) { + args_list$probs <- as.numeric(unlist(strsplit(opts$probs, ","))) + } + + if ("W" %in% func_args && !is.null(opts$weights)) { + weights_vec <- as.numeric(readr::read_lines(opts$weights)) + args_list$W <- weights_vec + } + + if ("ties.method" %in% func_args && !is.null(opts$ties_method)) { + args_list$ties.method <- opts$ties_method + } + + # Execute function and save result + result <- do.call(stat_func, args_list) + readr::write_tsv(as.data.frame(result), opts$output, col_names = FALSE) + """ + + r_script_path = "" + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + # --- Command Construction --- + cmd = [ + "Rscript", r_script_path, + "--input", str(input_matrix), + "--output", str(output_file), + "--statistic", statistic, + ] + if na_rm: + cmd.append("--na_rm") + if use_names: + cmd.append("--use_names") + if idxs: + cmd.extend(["--idxs", ",".join(map(str, idxs))]) + if probs: + cmd.extend(["--probs", ",".join(map(str, probs))]) + if weights: + cmd.extend(["--weights", str(weights)]) + if ties_method: + cmd.extend(["--ties_method", ties_method]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_file)] + } + + except subprocess.CalledProcessError as e: + # Structured error from the R script execution + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with return code {e.returncode}", + "output_files": [] + } + except Exception as e: + # General Python-level error + raise e + finally: + # --- Cleanup --- + if r_script_path and os.path.exists(r_script_path): + os.remove(r_script_path) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/bioconductor-sparsematrixstats_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/bioconductor-sparsematrixstats_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8161a4e61da4f4da61e5c71dbc48e5f38b1ecf11 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/bioconductor-sparsematrixstats_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sparsematrixstats/app/bioconductor-sparsematrixstats_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_sparsematrixstats' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3db0472e1369fa63e8431857a783c50e6142d77f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-sparsematrixstats: + build: . + image: mcp-bioconductor-sparsematrixstats:latest + container_name: mcp-bioconductor-sparsematrixstats + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-sparsematrixstats + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..03357b8472bb6a759d72db4ebd92f30ff2d13f49 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-sparsematrixstats + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-sparsematrixstats/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..300f89e40e09a3aa8b27e06ad5193bae60eb31ad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-xvector via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-xvector -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-xvector_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-xvector_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-xvector_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/__pycache__/bioconductor-xvector_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/__pycache__/bioconductor-xvector_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8b2458e018de2d3c6ba07c8875f7155bac38c2f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/__pycache__/bioconductor-xvector_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/bioconductor-xvector_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/bioconductor-xvector_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7f3c202ff5965e9ae058fce54dd124c15807b9f8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/bioconductor-xvector_server.py @@ -0,0 +1,350 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Union, Dict, Any +import json +import tempfile + +def _run_r_command(script: str) -> dict: + """ + Helper function to execute R code via Rscript. + """ + if not subprocess.run(["which", "Rscript"], capture_output=True).returncode == 0: + raise RuntimeError("Rscript not found. Please ensure R and Bioconductor-XVector are installed.") + + # Check if XVector is installed in R + check_pkg = "if (!requireNamespace('XVector', quietly = TRUE)) quit(status = 1)" + if subprocess.run(["Rscript", "-e", check_pkg]).returncode != 0: + raise RuntimeError("R package 'XVector' is not installed.") + + try: + result = subprocess.run( + ["Rscript", "-e", script], + capture_output=True, + text=True, + check=True + ) + return { + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "error_msg": str(e) + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_xvector' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def xvector_get_info( + rds_path: str +) -> Dict[str, Any]: + """ + Retrieve metadata about an XVector object stored in an RDS file. + + Args: + rds_path: Path to the .rds file containing the XVector object. + """ + path = Path(rds_path) + if not path.exists(): + return {"error": f"File {rds_path} not found."} + + script = f""" + library(XVector) + obj <- readRDS('{rds_path}') + cat(paste0('class:', class(obj), '\\n')) + cat(paste0('length:', length(obj), '\\n')) + cat(paste0('typeof:', typeof(obj), '\\n')) + if (is(obj, 'XVectorList')) {{ + cat(paste0('element_lengths:', paste(elementNROWS(obj), collapse=','), '\\n')) + }} + """ + + res = _run_r_command(script) + return { + "command_executed": f"Rscript -e \"{script.strip()}\"", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "status": res.get("status") + } + +@mcp.tool() +def xvector_subseq( + input_rds: str, + output_rds: str, + start: Optional[int] = None, + end: Optional[int] = None, + width: Optional[int] = None +) -> Dict[str, Any]: + """ + Extract a subsequence from an XVector object using subseq(). + + Args: + input_rds: Path to input .rds file. + output_rds: Path to save the resulting .rds file. + start: The start index of the subsequence. + end: The end index of the subsequence. + width: The width of the subsequence. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + # Build R arguments + args = [] + if start is not None: args.append(f"start={start}") + if end is not None: args.append(f"end={end}") + if width is not None: args.append(f"width={width}") + + arg_str = ", ".join(args) + if arg_str: + arg_str = ", " + arg_str + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + res <- subseq(x{arg_str}) + saveRDS(res, '{output_rds}') + """ + + res = _run_r_command(script) + return { + "command_executed": f"subseq(x{arg_str})", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_rds] if res.get("status") == "success" else [] + } + +@mcp.tool() +def xvector_narrow( + input_rds: str, + output_rds: str, + start: int = 1, + end: Optional[int] = None, + width: Optional[int] = None +) -> Dict[str, Any]: + """ + Narrow an XVector object. Unlike subseq, narrow creates a view without copying data. + + Args: + input_rds: Path to input .rds file. + output_rds: Path to save the resulting .rds file. + start: Relative start offset. + end: Relative end offset. + width: Desired width. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + args = [f"start={start}"] + if end is not None: args.append(f"end={end}") + if width is not None: args.append(f"width={width}") + + arg_str = ", ".join(args) + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + res <- narrow(x, {arg_str}) + saveRDS(res, '{output_rds}') + """ + + res = _run_r_command(script) + return { + "command_executed": f"narrow(x, {arg_str})", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_rds] + } + +@mcp.tool() +def xvector_compact( + input_rds: str, + output_rds: str +) -> Dict[str, Any]: + """ + Compact an XVector object to force memory deallocation of unused parts of the external vector. + + Args: + input_rds: Path to input .rds file. + output_rds: Path to save the compacted .rds file. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + res <- compact(x) + saveRDS(res, '{output_rds}') + """ + + res = _run_r_command(script) + return { + "command_executed": "compact(x)", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_rds] + } + +@mcp.tool() +def xvector_slice( + input_rds: str, + lower: float = -float('inf'), + upper: float = float('inf') +) -> Dict[str, Any]: + """ + Slice an XInteger or XDouble vector to find ranges where values are within [lower, upper]. + Returns a summary of the ranges. + + Args: + input_rds: Path to input .rds file. + lower: Lower bound for slicing. + upper: Upper bound for slicing. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + # Handle infinity for R + r_lower = "-Inf" if lower == -float('inf') else lower + r_upper = "Inf" if upper == float('inf') else upper + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + sl <- slice(x, lower={r_lower}, upper={r_upper}) + print(sl) + """ + + res = _run_r_command(script) + return { + "command_executed": f"slice(x, lower={r_lower}, upper={r_upper})", + "stdout": res.get("stdout"), + "stderr": res.get("stderr") + } + +@mcp.tool() +def xvector_to_raw( + input_rds: str, + output_bin: str +) -> Dict[str, Any]: + """ + Export the raw content of an XVector to a binary file. + + Args: + input_rds: Path to input .rds file. + output_bin: Path to the output binary file. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + # Ensure it is an XRaw or similar + writeBin(as.raw(x), '{output_bin}') + """ + + res = _run_r_command(script) + return { + "command_executed": "writeBin(as.raw(x), ...)", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_bin] + } + +@mcp.tool() +def xvector_aggregate( + input_rds: str, + method: str = "sum" +) -> Dict[str, Any]: + """ + Perform aggregation on an XVector (sum, mean, min, max). + + Args: + input_rds: Path to input .rds file. + method: Aggregation method ('sum', 'mean', 'min', 'max'). + """ + if method not in ["sum", "mean", "min", "max"]: + return {"error": "Method must be one of: sum, mean, min, max"} + + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + val <- {method}(x, na.rm=TRUE) + cat(val) + """ + + res = _run_r_command(script) + return { + "command_executed": f"{method}(x)", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "result": res.get("stdout").strip() if res.get("status") == "success" else None + } + +@mcp.tool() +def xvector_create_from_list( + data: List[float], + type: str = "double", + output_rds: str = "vector.rds" +) -> Dict[str, Any]: + """ + Create an XVector object from a Python list and save as RDS. + + Args: + data: List of numeric values. + type: Type of XVector to create ('integer', 'double', 'raw'). + output_rds: Filename for the output RDS. + """ + if type not in ["integer", "double", "raw"]: + return {"error": "Type must be 'integer', 'double', or 'raw'"} + + # Create a temporary file for the data to pass to R + with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as tmp: + json.dump(data, tmp) + tmp_path = tmp.name + + r_class = { + "integer": "XInteger", + "double": "XDouble", + "raw": "XRaw" + }[type] + + script = f""" + library(XVector) + library(jsonlite) + raw_data <- fromJSON('{tmp_path}') + vec <- as(raw_data, '{r_class}') + saveRDS(vec, '{output_rds}') + """ + + try: + res = _run_r_command(script) + return { + "command_executed": f"as(data, '{r_class}')", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_rds] + } + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/bioconductor-xvector_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/bioconductor-xvector_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a57fab143d78ef463a407b1f6be668e8299f52f4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/bioconductor-xvector_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/bioconductor-xvector_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_xvector' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5a5367493fffc3a6cb5c8110673556796cf375d6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-xvector: + build: . + image: mcp-bioconductor-xvector:latest + container_name: mcp-bioconductor-xvector + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-xvector + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb31b4b13d7d554be35fbdf864159c5e39fd7541 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-xvector + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-xvector/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6beb0d72912e7327150b327b51ab8e11bd6653b1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install biopython via conda (e.g., from bioconda) +RUN conda install -c bioconda biopython -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/biopython_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/biopython_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/biopython_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/__pycache__/biopython_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/__pycache__/biopython_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..680a7bc46237f5f9664e76b805e91fad8b2c0f23 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/__pycache__/biopython_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/biopython_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/biopython_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9f780b0524f6e6e3d8f61a2f04b47b2d202bd541 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/biopython_server.py @@ -0,0 +1,86 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# In a real MCP implementation, the mcp package would be available. +# For this standalone script, we'll define a dummy decorator. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def run_script( + script: Path, + script_args: Optional[str] = None, +) -> dict: + """ + Executes a user-provided Python script in an environment with Biopython. + + Biopython is a library, not a standalone command-line tool. This function + provides a way to run custom Python scripts that leverage the Biopython + library for various bioinformatics tasks. + + Args: + script: Path to the Python script to be executed. The script must + utilize the Biopython library. + script_args: A string of command-line arguments to be passed to the + user-provided script. + + Returns: + A dictionary containing the execution details: + - command_executed: The full command line that was run. + - stdout: The standard output from the script. + - stderr: The standard error from the script. + - output_files: A list of output files (this wrapper cannot determine + these, so it will be empty). + """ + # --- Input Validation --- + if not script.is_file(): + raise FileNotFoundError(f"The script file does not exist: {script}") + + # --- Command Construction --- + cmd = ["python", str(script)] + if script_args: + # Split the arguments string into a list + cmd.extend(script_args.split()) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + # This error occurs if 'python' is not in the system's PATH + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'python' executable not found. Ensure Python is installed and in the system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the script returns a non-zero exit code + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + # This generic wrapper cannot know which files the user script might create. + # The user is responsible for managing and tracking output files. + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/biopython_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/biopython_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1b79fc40da814212f5a5e5f689bc0968d377c76c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/biopython_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biopython/app/biopython_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_biopython' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..825eb201666b0ded211046014f851633ce38fb92 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-biopython: + build: . + image: mcp-biopython:latest + container_name: mcp-biopython + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=biopython + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..29db4269c430ba66556f32e28f557df81146a121 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - biopython + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_biopython/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e92733ea1e0f47e2a97581359f7a5c599ccda71a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bowtie via conda (e.g., from bioconda) +RUN conda install -c bioconda bowtie -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bowtie_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bowtie_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bowtie_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/__pycache__/bowtie_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/__pycache__/bowtie_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf8efec9ed69f6a03cbd48f516a7c7bb95eed54e Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/__pycache__/bowtie_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/bowtie_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/bowtie_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6f37b0f719388ff8c8c473751cc46c645805b2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/bowtie_server.py @@ -0,0 +1,206 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + check_syntax_only: bool = False, + loop_around_program: bool = False, + loop_and_print: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + use_modules_no_import: Optional[List[str]] = None, + no_modules_no_import: Optional[List[str]] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + enable_tainting_checks: bool = False, + enable_tainting_warnings: bool = False, + search_path_for_program: bool = False, + record_separator: Optional[str] = None, + enable_line_ending_processing: Optional[str] = None, + enable_switch_parsing: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + extract_program: bool = False, + extract_directory: Optional[Path] = None, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + unicode_features: Optional[str] = None, + disable_sitecustomize: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, +) -> dict: + """ + Executes the Perl interpreter with a wide range of options. + + This tool can run a Perl script from a file, execute one-liners, check syntax, + and modify Perl's behavior with various switches for warnings, modules, + input processing, and more. + """ + # --- Input Validation --- + actionable_input = any([ + programfile, + execute_program, + execute_program_extended, + print_version, + print_config is not None, + check_syntax_only + ]) + if not actionable_input: + raise ValueError( + "Either a programfile, an executable string (-e/-E), or an action " + "like --print_version, --print_config, or --check_syntax_only must be provided." + ) + + if programfile and (execute_program or execute_program_extended): + raise ValueError("Cannot specify both a 'programfile' and an inline program via '-e' or '-E'.") + + if programfile and not programfile.exists(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if loop_around_program and loop_and_print: + raise ValueError("The flags '-n' (loop_around_program) and '-p' (loop_and_print) are mutually exclusive.") + + if enable_all_warnings and disable_all_warnings: + raise ValueError("The flags '-W' (enable_all_warnings) and '-X' (disable_all_warnings) are mutually exclusive.") + + if split_pattern and not autosplit: + raise ValueError("A 'split_pattern' (-F) can only be used with 'autosplit' mode (-a).") + + if extract_directory and not extract_program: + raise ValueError("Specifying 'extract_directory' requires 'extract_program' (-x) to be enabled.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger is not None: + cmd.append(f"-d{run_under_debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_extended: + for prog_line in execute_program_extended: + cmd.extend(["-E", prog_line]) + if disable_sitecustomize: + cmd.append("-f") + if split_pattern: + cmd.extend(["-F", split_pattern]) + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if include_directories: + for directory in include_directories: + cmd.extend(["-I", str(directory)]) + if enable_line_ending_processing is not None: + cmd.append(f"-l{enable_line_ending_processing}") + if use_modules: + for module in use_modules: + cmd.append(f"-M{module}") + if no_modules: + for module in no_modules: + cmd.append(f"-M-{module}") + if use_modules_no_import: + for module in use_modules_no_import: + cmd.append(f"-m{module}") + if no_modules_no_import: + for module in no_modules_no_import: + cmd.append(f"-m-{module}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if enable_switch_parsing: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V{print_config}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if extract_program: + cmd.append("-x") + if extract_directory: + cmd.extend([str(extract_directory)]) + if disable_all_warnings: + cmd.append("-X") + + # Add program file and arguments + if programfile: + cmd.append(str(programfile)) + + if arguments: + # The '--' switch is good practice to separate perl options from script arguments + if programfile or execute_program or execute_program_extended: + cmd.append("--") + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Perl execution doesn't have a defined output file + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/bowtie_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/bowtie_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8539de64265b54d77c00fa2241d923c65fd6a67b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/bowtie_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/bowtie_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bowtie' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b590c5d861b6fcc1f695edf5c47bf23f69e96dbc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bowtie: + build: . + image: mcp-bowtie:latest + container_name: mcp-bowtie + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bowtie + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a94f45ccfd6430e8677fdd9d183a45bb30cda4a9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bowtie + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bowtie/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fb9b2f7a14f012108ae53e5d433bf9ff50ebf674 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install busco via conda (e.g., from bioconda) +RUN conda install -c bioconda busco -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/busco_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/busco_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/busco_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/__pycache__/busco_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/__pycache__/busco_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..656a61e2e4445ec1949a20e08eb5bcae9e20a7f3 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/__pycache__/busco_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/busco_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/busco_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f18a173411ff7984bea45527d9afe23bb6274f9b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/busco_server.py @@ -0,0 +1,377 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# Mock the decorator for standalone execution. In a real MCP environment, this would be provided. +class mcp: + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_busco' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def busco_run( + input_file: Path, + output_name: str, + lineage_dataset: str, + mode: str, + output_path: Optional[Path] = None, + main_out: Optional[Path] = None, + cpu: int = 1, + force: bool = False, + restart: bool = False, + quiet: bool = False, + download_path: Optional[Path] = None, + datasets_version: str = "auto", + offline: bool = False, + evalue: float = 1e-03, + limit: int = 3, + tar: bool = False, + long: bool = False, + auto_lineage: bool = False, + auto_lineage_euk: bool = False, + auto_lineage_prok: bool = False, + auto_lineage_viruses: bool = False, + update_data: bool = False, + config_file: Optional[Path] = None, + scaffold_composition: bool = False, + contig_break: int = 10, + augustus_species: Optional[str] = None, + augustus_parameters: Optional[str] = None, + batch_mode: bool = False, +) -> dict: + """ + Run a BUSCO analysis to assess genome assembly, gene set, or transcriptome completeness. + + Args: + input_file: Input sequence file in FASTA format, or a directory of FASTA files for batch mode. + output_name: Name for the output directory. + lineage_dataset: Path to or name of the BUSCO lineage dataset to use. + mode: BUSCO analysis mode. Must be one of 'geno', 'tran', or 'prot'. + output_path: Optional path to the directory where the output folder will be created. + main_out: Main output folder, where all runs will be placed. + cpu: Number of threads/cores to use. + force: Force overwriting of existing output directory. + restart: Restart a run that was previously interrupted. + quiet: Disable the progress bar and verbose output. + download_path: Path to the directory for downloading BUSCO datasets. + datasets_version: Version of BUSCO datasets to use (e.g., odb10). + offline: Run in offline mode, preventing any downloads. + evalue: E-value cutoff for BLAST/Diamond. + limit: How many candidate regions to consider per BUSCO. + tar: Compress the output files into a tarball. + long: Augustus optimization mode for long reads (for 'geno' mode). + auto_lineage: Run auto-lineage selection. + auto_lineage_euk: Run auto-lineage selection for eukaryotes. + auto_lineage_prok: Run auto-lineage selection for prokaryotes. + auto_lineage_viruses: Run auto-lineage selection for viruses. + update_data: Download or update all BUSCO datasets. + config_file: Path to a custom BUSCO config file. + scaffold_composition: Write a scaffold composition report (for 'geno' mode). + contig_break: Number of 'N's to break a contig. + augustus_species: Augustus species to use for gene prediction. + augustus_parameters: Custom parameters to pass to Augustus. + batch_mode: Treat the input as a directory of files to process. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file or directory not found: {input_file}") + + allowed_modes = ["geno", "tran", "prot"] + if mode not in allowed_modes: + raise ValueError(f"Invalid mode '{mode}'. Must be one of {allowed_modes}.") + + if cpu < 1: + raise ValueError("CPU count must be at least 1.") + + # Command construction + cmd = [ + "busco", + "-i", str(input_file), + "-o", output_name, + "-l", lineage_dataset, + "-m", mode, + "-c", str(cpu), + "-e", str(evalue), + "--limit", str(limit), + "--contig_break", str(contig_break), + "--datasets_version", datasets_version, + ] + + if output_path: + output_path.mkdir(parents=True, exist_ok=True) + cmd.extend(["--out_path", str(output_path)]) + if main_out: + main_out.mkdir(parents=True, exist_ok=True) + cmd.extend(["--main_out", str(main_out)]) + if force: + cmd.append("-f") + if restart: + cmd.append("--restart") + if quiet: + cmd.append("--quiet") + if download_path: + download_path.mkdir(parents=True, exist_ok=True) + cmd.extend(["--download_path", str(download_path)]) + if offline: + cmd.append("--offline") + if tar: + cmd.append("--tar") + if long: + cmd.append("--long") + if auto_lineage: + cmd.append("--auto-lineage") + if auto_lineage_euk: + cmd.append("--auto-lineage-euk") + if auto_lineage_prok: + cmd.append("--auto-lineage-prok") + if auto_lineage_viruses: + cmd.append("--auto-lineage-viruses") + if update_data: + cmd.append("--update-data") + if config_file: + if not config_file.exists(): + raise FileNotFoundError(f"Config file not found: {config_file}") + cmd.extend(["--config", str(config_file)]) + if scaffold_composition: + cmd.append("--scaffold_composition") + if augustus_species: + cmd.extend(["--augustus_species", augustus_species]) + if augustus_parameters: + cmd.extend(["--augustus_parameters", augustus_parameters]) + if batch_mode: + cmd.append("--batch_mode") + + # Subprocess execution + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'busco' command not found. Make sure it is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # Structured result return + final_output_dir = (output_path or Path.cwd()) / output_name + output_files = [] + if final_output_dir.is_dir(): + output_files.append(str(final_output_dir)) + summary_files = list(final_output_dir.glob(f"short_summary.specific.{lineage_dataset}*.txt")) + if summary_files: + output_files.append(str(summary_files[0])) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + +@mcp.tool() +def busco_list_datasets( + lineage_path: Optional[Path] = None, + version: Optional[str] = None, + offline: bool = False +) -> dict: + """ + Lists available BUSCO datasets, either locally or from the remote repository. + + Args: + lineage_path: Optional path to a directory containing custom datasets. + version: The specific BUSCO dataset version to list (e.g., odb10). + offline: List only locally available datasets. + + Returns: + A dictionary containing the command executed, stdout (the list of datasets), and stderr. + """ + cmd = ["busco", "--list-datasets"] + + if lineage_path: + if not lineage_path.is_dir(): + raise NotADirectoryError(f"Provided lineage path is not a directory: {lineage_path}") + cmd.extend(["--lineage_path", str(lineage_path)]) + + if version: + cmd.extend(["--version", version]) + + if offline: + cmd.append("--offline") + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'busco' command not found. Make sure it is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + +@mcp.tool() +def busco_download( + lineage: str, + download_path: Optional[Path] = None, + datasets_version: str = "auto", + update_data: bool = False +) -> dict: + """ + Downloads a specific BUSCO lineage dataset. + + Args: + lineage: The name of the lineage dataset to download. + download_path: Path to the directory for downloading BUSCO datasets. + datasets_version: Version of BUSCO datasets to use (e.g., odb10). + update_data: Force update if the dataset already exists. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the downloaded data. + """ + cmd = ["busco", "--download", lineage] + + if download_path: + download_path.mkdir(parents=True, exist_ok=True) + cmd.extend(["--download_path", str(download_path)]) + + if datasets_version: + cmd.extend(["--datasets_version", datasets_version]) + + if update_data: + cmd.append("--update-data") + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'busco' command not found. Make sure it is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # Attempt to find the downloaded directory + output_files = [] + base_path = download_path or Path.home() / ".busco" / "downloads" + lineage_dir = base_path / "lineages" / lineage + if lineage_dir.is_dir(): + output_files.append(str(lineage_dir)) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + +@mcp.tool() +def busco_plot( + working_directory: Path +) -> dict: + """ + Generates a BUSCO plot from a completed BUSCO run summary file. + + This function calls the 'busco_plot' utility. + + Args: + working_directory: Path to the BUSCO output directory containing the short_summary.*.txt file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the generated plot. + """ + if not working_directory.is_dir(): + raise NotADirectoryError(f"Working directory not found: {working_directory}") + + summary_files = list(working_directory.glob("short_summary.*.txt")) + if not summary_files: + raise FileNotFoundError(f"No 'short_summary.*.txt' file found in {working_directory}") + + cmd = ["busco_plot", "-w", str(working_directory)] + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'busco_plot' command not found. Make sure it is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + output_plot = working_directory / "busco_figure.png" + output_files = [str(output_plot)] if output_plot.exists() else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/busco_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/busco_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d677b34c99525015d1593be377b10baac4e97a8c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/busco_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_busco/app/busco_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_busco' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..46639c5eb610609f9cf7be053f0a1508e3842557 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-busco: + build: . + image: mcp-busco:latest + container_name: mcp-busco + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=busco + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..840db62b21b37284886743c3378629204f752bcf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - busco + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_busco/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1c540403613c57c4f7059830d34ca4cd57ef217e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bwa via conda (e.g., from bioconda) +RUN conda install -c bioconda bwa -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bwa_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bwa_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bwa_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/__pycache__/bwa_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/__pycache__/bwa_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dce2123756cad684061caf2cb47a00090f0f884f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/__pycache__/bwa_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/__pycache__/bwa_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/__pycache__/bwa_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95544bc44fe7578ceabaa90dffc7ec1fa31dfdd6 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/__pycache__/bwa_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/bwa_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/bwa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..047ce2c9e79e9b31c68adb99a74bf008ed6b7fc3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/bwa_server.py @@ -0,0 +1,782 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# In a real MCP environment, you would import mcp. +# This is a placeholder to allow the code to be syntactically valid. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bwa' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def bwa_index( + in_fa: Path, + prefix: Optional[Path] = None, + algorithm: str = "is", + color_space: bool = False, + block_size_bwtsw: int = 10000000, + index_for_64bit_genome: bool = False, +): + """ + Constructs the BWA index for a reference genome. + + This command builds the FM-index for a reference genome in FASTA format. + The index is composed of several files, all of which are required for alignment. + + Args: + in_fa: Path to the input reference genome file in FASTA format. + prefix: Prefix for the output index files. If not provided, it defaults to the input FASTA filename. + algorithm: Algorithm for index construction. Can be 'is' (default) or 'bwtsw'. + color_space: Build a color-space index. + block_size_bwtsw: Block size for the 'bwtsw' algorithm. + index_for_64bit_genome: Index files for 64-bit genome. + + Returns: + A dictionary containing the execution details and paths to the output index files. + """ + if not in_fa.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {in_fa}") + if algorithm not in ["is", "bwtsw"]: + raise ValueError(f"Invalid algorithm '{algorithm}'. Must be 'is' or 'bwtsw'.") + + output_prefix = prefix if prefix else in_fa.with_suffix('') + + cmd = ["bwa", "index"] + if algorithm != "is": + cmd.extend(["-a", algorithm]) + if color_space: + cmd.append("-c") + if block_size_bwtsw != 10000000 and algorithm == "bwtsw": + cmd.extend(["-b", str(block_size_bwtsw)]) + if index_for_64bit_genome: + cmd.append("-6") + + cmd.extend(["-p", str(output_prefix)]) + cmd.append(str(in_fa)) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_str = [ + f"{output_prefix}.amb", + f"{output_prefix}.ann", + f"{output_prefix}.bwt", + f"{output_prefix}.pac", + f"{output_prefix}.sa", + ] + if index_for_64bit_genome: + output_files_str[2] = f"{output_prefix}.bwt.64" + + for f in output_files_str: + if not Path(f).is_file(): + raise FileNotFoundError(f"Expected output file was not created: {f}") + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_str, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA index command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_mem( + idx_prefix: Path, + in1_fq: Path, + in2_fq: Optional[Path] = None, + output_file: Optional[Path] = None, + threads: int = 1, + min_seed_len: int = 19, + band_width: int = 100, + off_diagonal_x_dropoff: int = 100, + reseeding_factor: float = 1.5, + max_mem_occurrences: int = 500, + drop_chain_threshold: float = 0.50, + mark_shorter_splits_sec: bool = False, + perform_sw_rescue: bool = False, + match_score: int = 1, + mismatch_penalty: int = 4, + gap_open_penalty: str = "6,6", + gap_extension_penalty: str = "1,1", + clipping_penalty: str = "5,5", + unpaired_read_penalty: int = 17, + interleaved_input: bool = False, + read_group_header: Optional[str] = None, + min_score_to_output: int = 30, + header: Optional[str] = None, + treat_alt_as_primary: bool = False, + verbosity_level: int = 3, + soft_clip_supplementary: bool = False, + mark_shorter_splits_picard: bool = False, + read_length_params: Optional[str] = None, + read_type: Optional[str] = None, + output_all_alignments: bool = False, + append_fastq_comment: bool = False, + output_ref_header_in_xr: bool = False, + skip_mate_rescue: bool = False, + batch_size: int = 10000000, +): + """ + Aligns 70bp-1Mbp query sequences with the BWA-MEM algorithm. + + Args: + idx_prefix: Path to the BWA index prefix. + in1_fq: Path to the FASTQ file of reads (or first reads for PE). + in2_fq: Path to the FASTQ file of second reads for paired-end data. + output_file: Path to the output SAM file. If None, output is sent to stdout. + threads: Number of threads. + min_seed_len: Minimum seed length. + band_width: Band width for chaining. + off_diagonal_x_dropoff: Off-diagonal X-dropoff. + reseeding_factor: Trigger re-seeding for a MEM longer than min_seed_len * r. + max_mem_occurrences: Discard a MEM if it has more than this many occurrences. + drop_chain_threshold: Drop chains shorter than this fraction of the longest extension. + mark_shorter_splits_sec: Mark shorter split hits as secondary. + perform_sw_rescue: Perform Smith-Waterman to rescue missing hits. + match_score: Score for a sequence match. + mismatch_penalty: Penalty for a mismatch. + gap_open_penalty: Gap open penalty as a string "INT" or "INT,INT". + gap_extension_penalty: Gap extension penalty as a string "INT" or "INT,INT". + clipping_penalty: Penalty for a clipped read as a string "INT" or "INT,INT". + unpaired_read_penalty: Penalty for an unpaired read pair. + interleaved_input: Input file is an interleaved paired-end FASTQ. + read_group_header: Read group header line (e.g., '@RG\\tID:foo\\tSM:bar'). + min_score_to_output: Don't output alignment with score lower than this. + header: Insert this string to header, or read from file if it's a path. + treat_alt_as_primary: Treat ALT contigs as part of the primary assembly. + verbosity_level: Verbosity level. + soft_clip_supplementary: Use soft-clipping for supplementary alignments. + mark_shorter_splits_picard: Mark shorter split hits as secondary (for Picard compatibility). + read_length_params: Comma-separated string of "avg,std,max_is,min_is". + read_type: Read type. Can be 'pacbio', 'ont2d', or 'intractg'. + output_all_alignments: Output all found alignments for single-end or unpaired paired-end reads. + append_fastq_comment: Append FASTA/Q comment to SAM output. + output_ref_header_in_xr: Output the reference FASTA header in the XR tag. + skip_mate_rescue: Skip mate rescue. + batch_size: Process INT reads in a batch. + + Returns: + A dictionary containing the execution details and path to the output SAM file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in1_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ file not found: {in1_fq}") + if in2_fq and not in2_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ file 2 not found: {in2_fq}") + if read_type and read_type not in ['pacbio', 'ont2d', 'intractg']: + raise ValueError(f"Invalid read_type '{read_type}'.") + + cmd = ["bwa", "mem"] + + # Add options + if threads != 1: cmd.extend(["-t", str(threads)]) + if min_seed_len != 19: cmd.extend(["-k", str(min_seed_len)]) + if band_width != 100: cmd.extend(["-w", str(band_width)]) + if off_diagonal_x_dropoff != 100: cmd.extend(["-d", str(off_diagonal_x_dropoff)]) + if reseeding_factor != 1.5: cmd.extend(["-r", str(reseeding_factor)]) + if max_mem_occurrences != 500: cmd.extend(["-c", str(max_mem_occurrences)]) + if drop_chain_threshold != 0.50: cmd.extend(["-D", str(drop_chain_threshold)]) + if mark_shorter_splits_sec: cmd.append("-m") + if perform_sw_rescue: cmd.append("-P") + if match_score != 1: cmd.extend(["-A", str(match_score)]) + if mismatch_penalty != 4: cmd.extend(["-B", str(mismatch_penalty)]) + if gap_open_penalty != "6,6": cmd.extend(["-O", gap_open_penalty]) + if gap_extension_penalty != "1,1": cmd.extend(["-E", gap_extension_penalty]) + if clipping_penalty != "5,5": cmd.extend(["-L", clipping_penalty]) + if unpaired_read_penalty != 17: cmd.extend(["-U", str(unpaired_read_penalty)]) + if interleaved_input: cmd.append("-p") + if read_group_header: cmd.extend(["-R", read_group_header]) + if min_score_to_output != 30: cmd.extend(["-T", str(min_score_to_output)]) + if header: cmd.extend(["-H", header]) + if treat_alt_as_primary: cmd.append("-j") + if verbosity_level != 3: cmd.extend(["-v", str(verbosity_level)]) + if soft_clip_supplementary: cmd.append("-Y") + if mark_shorter_splits_picard: cmd.append("-M") + if read_length_params: cmd.extend(["-I", read_length_params]) + if read_type: cmd.extend(["-x", read_type]) + if output_all_alignments: cmd.append("-a") + if append_fastq_comment: cmd.append("-C") + if output_ref_header_in_xr: cmd.append("-V") + if skip_mate_rescue: cmd.append("-S") + if batch_size != 10000000: cmd.extend(["-K", str(batch_size)]) + if output_file: cmd.extend(["-o", str(output_file)]) + + # Add positional arguments + cmd.append(str(idx_prefix)) + cmd.append(str(in1_fq)) + if in2_fq: + cmd.append(str(in2_fq)) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_file)] if output_file else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA mem command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_aln( + idx_prefix: Path, + in_fq: Path, + output_sai: Optional[Path] = None, + max_diff: float = 0.04, + max_gap_opens: int = 1, + max_gap_extensions: int = -1, + disallow_long_del_at_3_end: int = 16, + disallow_indel_at_ends: int = 5, + seed_length: int = 32, + max_diff_in_seed: int = 2, + threads: int = 1, + mismatch_penalty: int = 3, + gap_open_penalty: int = 11, + gap_extension_penalty: int = 4, + stop_search_threshold: int = 30, + trimming_quality: int = 0, + barcode_length: int = 0, + reverse_query_no_complement: bool = False, + disable_iterative_search: bool = False, + illumina_1_3_plus_fastq: bool = False, + input_is_bam: bool = False, +): + """ + Finds the SA coordinates of the input reads using the BWA-backtrack algorithm. + + Args: + idx_prefix: Path to the BWA index prefix. + in_fq: Path to the input FASTQ file. + output_sai: Path to the output SAI file. If None, output is sent to stdout. + max_diff: Max #diff (int) or missing prob under 0.02 err rate (float). + max_gap_opens: Maximum number of gap opens. + max_gap_extensions: Maximum number of gap extensions. -1 to disable. + disallow_long_del_at_3_end: Disallow a long deletion within INT bp towards the 3'-end. + disallow_indel_at_ends: Disallow an indel within INT bp towards the ends. + seed_length: Take the first INT subsequence as seed. If INT is larger than the query sequence, seeding will be disabled. + max_diff_in_seed: Maximum edit distance in the seed. + threads: Number of threads. + mismatch_penalty: Mismatch penalty. + gap_open_penalty: Gap open penalty. + gap_extension_penalty: Gap extension penalty. + stop_search_threshold: Stop searching when there are > INT equally best hits. + trimming_quality: Quality threshold for read trimming down to 35bp. + barcode_length: Length of barcode starting from the 5'-end. + reverse_query_no_complement: Reverse query but not complement it. + disable_iterative_search: Disable iterative search. + illumina_1_3_plus_fastq: Input is in Illumina 1.3+ FASTQ format. + input_is_bam: Input is BAM. + + Returns: + A dictionary containing the execution details and path to the output SAI file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ/BAM file not found: {in_fq}") + + cmd = ["bwa", "aln"] + + if max_diff != 0.04: cmd.extend(["-n", str(max_diff)]) + if max_gap_opens != 1: cmd.extend(["-o", str(max_gap_opens)]) + if max_gap_extensions != -1: cmd.extend(["-e", str(max_gap_extensions)]) + if disallow_long_del_at_3_end != 16: cmd.extend(["-d", str(disallow_long_del_at_3_end)]) + if disallow_indel_at_ends != 5: cmd.extend(["-i", str(disallow_indel_at_ends)]) + if seed_length != 32: cmd.extend(["-l", str(seed_length)]) + if max_diff_in_seed != 2: cmd.extend(["-k", str(max_diff_in_seed)]) + if threads != 1: cmd.extend(["-t", str(threads)]) + if mismatch_penalty != 3: cmd.extend(["-M", str(mismatch_penalty)]) + if gap_open_penalty != 11: cmd.extend(["-O", str(gap_open_penalty)]) + if gap_extension_penalty != 4: cmd.extend(["-E", str(gap_extension_penalty)]) + if stop_search_threshold != 30: cmd.extend(["-R", str(stop_search_threshold)]) + if trimming_quality != 0: cmd.extend(["-q", str(trimming_quality)]) + if barcode_length != 0: cmd.extend(["-B", str(barcode_length)]) + if reverse_query_no_complement: cmd.append("-c") + if disable_iterative_search: cmd.append("-N") + if illumina_1_3_plus_fastq: cmd.append("-I") + if input_is_bam: cmd.append("-b") + if output_sai: cmd.extend(["-f", str(output_sai)]) + + cmd.extend([str(idx_prefix), str(in_fq)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_sai)] if output_sai else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA aln command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_samse( + idx_prefix: Path, + in_sai: Path, + in_fq: Path, + output_sam: Optional[Path] = None, + read_group_header: Optional[str] = None, + max_alignments_in_xa: int = 3, +): + """ + Generates alignments in the SAM format given single-end reads. + + Args: + idx_prefix: Path to the BWA index prefix. + in_sai: Path to the input SAI file from `bwa aln`. + in_fq: Path to the input FASTQ file. + output_sam: Path to the output SAM file. If None, output is sent to stdout. + read_group_header: Read group header line. + max_alignments_in_xa: Maximum number of alignments to output in the XA tag. + + Returns: + A dictionary containing the execution details and path to the output SAM file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in_sai.is_file(): + raise FileNotFoundError(f"Input SAI file not found: {in_sai}") + if not in_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ file not found: {in_fq}") + + cmd = ["bwa", "samse"] + + if output_sam: cmd.extend(["-f", str(output_sam)]) + if read_group_header: cmd.extend(["-r", read_group_header]) + if max_alignments_in_xa != 3: cmd.extend(["-n", str(max_alignments_in_xa)]) + + cmd.extend([str(idx_prefix), str(in_sai), str(in_fq)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_sam)] if output_sam else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA samse command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_sampe( + idx_prefix: Path, + in1_sai: Path, + in2_sai: Path, + in1_fq: Path, + in2_fq: Path, + output_sam: Optional[Path] = None, + read_group_header: Optional[str] = None, + max_insert_size: int = 500, + max_occurrences: int = 100000, + max_abnormal_xa: int = 3, + max_discordant_xa: int = 10, + load_entire_fm_index: bool = False, +): + """ + Generates alignments in the SAM format given paired-end reads. + + Args: + idx_prefix: Path to the BWA index prefix. + in1_sai: Path to the SAI file for the first reads. + in2_sai: Path to the SAI file for the second reads. + in1_fq: Path to the FASTQ file for the first reads. + in2_fq: Path to the FASTQ file for the second reads. + output_sam: Path to the output SAM file. If None, output is sent to stdout. + read_group_header: Read group header line. + max_insert_size: Maximum insert size for a read pair to be considered being mapped properly. + max_occurrences: Maximum occurrences for one end before mate-SW is used. + max_abnormal_xa: Maximum number of alignments to output in the XA tag for reads paired abnormally. + max_discordant_xa: Maximum number of alignments to output in the XA tag for disconcordant read pairs. + load_entire_fm_index: Load the entire FM-index into memory to reduce disk operations. + + Returns: + A dictionary containing the execution details and path to the output SAM file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in1_sai.is_file(): raise FileNotFoundError(f"Input SAI file not found: {in1_sai}") + if not in2_sai.is_file(): raise FileNotFoundError(f"Input SAI file not found: {in2_sai}") + if not in1_fq.is_file(): raise FileNotFoundError(f"Input FASTQ file not found: {in1_fq}") + if not in2_fq.is_file(): raise FileNotFoundError(f"Input FASTQ file not found: {in2_fq}") + + cmd = ["bwa", "sampe"] + + if output_sam: cmd.extend(["-f", str(output_sam)]) + if read_group_header: cmd.extend(["-r", read_group_header]) + if max_insert_size != 500: cmd.extend(["-a", str(max_insert_size)]) + if max_occurrences != 100000: cmd.extend(["-o", str(max_occurrences)]) + if max_abnormal_xa != 3: cmd.extend(["-n", str(max_abnormal_xa)]) + if max_discordant_xa != 10: cmd.extend(["-N", str(max_discordant_xa)]) + if load_entire_fm_index: cmd.append("-P") + + cmd.extend([str(idx_prefix), str(in1_sai), str(in2_sai), str(in1_fq), str(in2_fq)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_sam)] if output_sam else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA sampe command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_fastmap( + idx_prefix: Path, + in_fq: Path, + output_file: Optional[Path] = None, + min_smem_length: int = 17, + max_interval_size: int = 20, + threads: int = 1, +): + """ + Identify super-maximal exact matches (SMEMs). + + Args: + idx_prefix: Path to the BWA index prefix. + in_fq: Path to the input FASTQ file. + output_file: Path to the output file. If None, output is sent to stdout. + min_smem_length: Minimum length for a SMEM. + max_interval_size: Maximum interval size to find SMEMs. + threads: Number of threads. + + Returns: + A dictionary containing the execution details and path to the output file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ file not found: {in_fq}") + + cmd = ["bwa", "fastmap"] + + if min_smem_length != 17: cmd.extend(["-l", str(min_smem_length)]) + if max_interval_size != 20: cmd.extend(["-w", str(max_interval_size)]) + if threads != 1: cmd.extend(["-t", str(threads)]) + if output_file: cmd.extend(["-o", str(output_file)]) + + cmd.extend([str(idx_prefix), str(in_fq)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_file)] if output_file else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA fastmap command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_shm( + command: str, + idx_prefix: Path, +): + """ + Manage BWA index in shared memory. + + Args: + command: The command to execute: 'load', 'get', or 'rm'. + idx_prefix: Path to the BWA index prefix. + + Returns: + A dictionary containing the execution details. + """ + if command not in ["load", "get", "rm"]: + raise ValueError("Command must be one of 'load', 'get', or 'rm'.") + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + + cmd = ["bwa", "shm", command, str(idx_prefix)] + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA shm command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_fa2pac( + in_fa: Path, + out_pac: Path, + force_overwrite: bool = False, +): + """ + Convert FASTA to PAC format (binary sequence). + + Args: + in_fa: Path to the input FASTA file. + out_pac: Path for the output PAC file. + force_overwrite: Force overwrite of the output file if it exists. + + Returns: + A dictionary containing the execution details and path to the output PAC file. + """ + if not in_fa.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {in_fa}") + + cmd = ["bwa", "fa2pac"] + if force_overwrite: + cmd.append("-f") + cmd.extend([str(in_fa), str(out_pac)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + if not out_pac.is_file(): + raise FileNotFoundError(f"Expected output file was not created: {out_pac}") + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_pac)], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA fa2pac command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_pac2bwt( + in_pac: Path, + out_bwt: Path, + use_manber_myers: bool = False, + use_z_algorithm: bool = False, + force_overwrite: bool = False, +): + """ + Generate BWT from PAC format. + + Args: + in_pac: Path to the input PAC file. + out_bwt: Path for the output BWT file. + use_manber_myers: Use the Manber-Myers algorithm for D-critical characters. + use_z_algorithm: Use the Z-algorithm for D-critical characters. + force_overwrite: Force overwrite of the output file if it exists. + + Returns: + A dictionary containing the execution details and path to the output BWT file. + """ + if not in_pac.is_file(): + raise FileNotFoundError(f"Input PAC file not found: {in_pac}") + + cmd = ["bwa", "pac2bwt"] + if use_manber_myers: + cmd.append("-d") + if use_z_algorithm: + cmd.append("-z") + if force_overwrite: + cmd.append("-f") + cmd.extend([str(in_pac), str(out_bwt)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + if not out_bwt.is_file(): + raise FileNotFoundError(f"Expected output file was not created: {out_bwt}") + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_bwt)], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA pac2bwt command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_bwtupdate( + in_bwt: Path, + out_bwt: Path, +): + """ + Update BWT for the new reference sequence. + + Args: + in_bwt: Path to the input BWT file. + out_bwt: Path for the output BWT file. + + Returns: + A dictionary containing the execution details and path to the output BWT file. + """ + if not in_bwt.is_file(): + raise FileNotFoundError(f"Input BWT file not found: {in_bwt}") + + cmd = ["bwa", "bwtupdate", str(in_bwt), str(out_bwt)] + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + if not out_bwt.is_file(): + raise FileNotFoundError(f"Expected output file was not created: {out_bwt}") + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_bwt)], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA bwtupdate command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_bwt2sa( + in_bwt: Path, + out_sa: Path, + force_overwrite: bool = False, + sa_interval: int = 16, +): + """ + Generate SA from BWT and Occ. + + Args: + in_bwt: Path to the input BWT file. + out_sa: Path for the output SA file. + force_overwrite: Force overwrite of the output file if it exists. + sa_interval: SA interval. + + Returns: + A dictionary containing the execution details and path to the output SA file. + """ + if not in_bwt.is_file(): + raise FileNotFoundError(f"Input BWT file not found: {in_bwt}") + + cmd = ["bwa", "bwt2sa"] + if force_overwrite: + cmd.append("-f") + if sa_interval != 16: + cmd.extend(["-i", str(sa_interval)]) + cmd.extend([str(in_bwt), str(out_sa)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + if not out_sa.is_file(): + raise FileNotFoundError(f"Expected output file was not created: {out_sa}") + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_sa)], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA bwt2sa command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/bwa_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/bwa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..90c35871fb28636a85983d63de75f3aacca30f93 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/bwa_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/bwa_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bwa' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6c34807f2062027c5a22e819759fe77c42ff13b8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bwa: + build: . + image: mcp-bwa:latest + container_name: mcp-bwa + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bwa + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f74db625e040cbe9746d3807eb4a3e3672bf5953 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bwa + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bwa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4b1852f12613c2485bc8551cba47e23776dff112 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install cell2cell via conda (e.g., from bioconda) +RUN conda install -c bioconda cell2cell -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY cell2cell_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/cell2cell_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/cell2cell_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/app/__pycache__/cell2cell_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/app/__pycache__/cell2cell_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c5d97270585b3eca877b2ad28e73210f9a8d4fa Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/app/__pycache__/cell2cell_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/app/cell2cell_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/app/cell2cell_server.py new file mode 100644 index 0000000000000000000000000000000000000000..add33699897768fdf8b5602e02de74a8c2870234 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/app/cell2cell_server.py @@ -0,0 +1,184 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# Note: As cell2cell is a library, these MCP tools are designed to wrap a +# hypothetical command-line script that executes the library's core functions. +# This approach standardizes the library's usage for the MCP server. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_cell2cell' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def interaction_pipeline( + anndata_file: Path, + cell_type_column: str, + lr_pair_data: Path, + output_prefix: str, + communication_score_type: str = "expression_product", + n_permutations: int = 1000, + p_value_cutoff: float = 0.05, + use_complexes: bool = True, + seed: int = 42, +): + """ + Infers cell-cell interactions from a single transcriptomics dataset using the standard cell2cell pipeline. + + This tool computes communication scores between cell types based on the expression of ligand-receptor pairs + and assesses their statistical significance through permutation testing. + + Args: + anndata_file: Path to the input AnnData file (.h5ad) containing the expression matrix and cell metadata. + cell_type_column: The column name in the AnnData object's .obs attribute that contains cell type annotations. + lr_pair_data: Path to the file containing ligand-receptor interaction pairs. + output_prefix: Prefix for all generated output files (e.g., interaction scores, p-values). + communication_score_type: Method to compute the communication score. Defaults to 'expression_product'. + n_permutations: Number of permutations for generating the null distribution to compute p-values. + p_value_cutoff: P-value threshold for determining significant interactions. + use_complexes: Whether to account for protein complexes in the ligand-receptor pairs data. + seed: Random seed for reproducibility of permutation tests. + """ + # Input validation + if not anndata_file.is_file(): + raise FileNotFoundError(f"Input AnnData file not found at {anndata_file}") + if not lr_pair_data.is_file(): + raise FileNotFoundError(f"Ligand-receptor data file not found at {lr_pair_data}") + if n_permutations < 0: + raise ValueError("n_permutations must be a non-negative integer.") + if not (0.0 <= p_value_cutoff <= 1.0): + raise ValueError("p_value_cutoff must be between 0.0 and 1.0.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "cell2cell", "interaction", + "--anndata-file", str(anndata_file), + "--cell-type-column", cell_type_column, + "--lr-pair-data", str(lr_pair_data), + "--output-prefix", output_prefix, + "--communication-score-type", communication_score_type, + "--n-permutations", str(n_permutations), + "--p-value-cutoff", str(p_value_cutoff), + "--seed", str(seed), + ] + + if use_complexes: + cmd.append("--use-complexes") + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "error": "Cell2cell interaction pipeline failed", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + output_files = { + "interaction_scores": f"{output_prefix}_interactions.csv", + "p_values": f"{output_prefix}_pvalues.csv", + "significant_interactions": f"{output_prefix}_significant_interactions.csv", + } + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + + +@mcp.tool() +def tensor_pipeline( + input_path: Path, + output_prefix: str, + ranks: List[int], + init_method: str = "svd", + random_state: int = 42, +): + """ + Deconvolutes cell-cell communication patterns across multiple contexts using Tensor-cell2cell. + + This tool performs tensor factorization on a collection of cell-cell communication scores + (e.g., from different samples, conditions, or time points) to identify recurring patterns. + + Args: + input_path: Path to the input data. This can be a directory containing multiple interaction score matrices + (in .csv or .tsv format) or a single file representing a pre-built tensor. + output_prefix: Prefix for all generated output files (e.g., factor matrices, error plots). + ranks: A list of ranks (number of components) to test for the tensor factorization. + init_method: Initialization method for tensor decomposition. Can be 'svd' or 'random'. + random_state: Random seed for reproducibility of the factorization. + """ + # Input validation + if not input_path.exists(): + raise FileNotFoundError(f"Input path not found at {input_path}") + if not ranks: + raise ValueError("The 'ranks' list cannot be empty.") + if any(r <= 0 for r in ranks): + raise ValueError("All values in 'ranks' must be positive integers.") + if init_method not in ["svd", "random"]: + raise ValueError("init_method must be either 'svd' or 'random'.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + ranks_str = ",".join(map(str, ranks)) + + cmd = [ + "cell2cell", "tensor", + "--input-path", str(input_path), + "--output-prefix", output_prefix, + "--ranks", ranks_str, + "--init-method", init_method, + "--random-state", str(random_state), + ] + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "error": "Cell2cell tensor pipeline failed", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + output_files = { + "reconstruction_error_plot": f"{output_prefix}_reconstruction-error.png", + # Factor matrices will be generated for the best rank + "context_factors": f"{output_prefix}_context-factors.csv", + "cell_pair_factors": f"{output_prefix}_cell-pair-factors.csv", + "lr_pair_factors": f"{output_prefix}_lr-pair-factors.csv", + } + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/app/cell2cell_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/app/cell2cell_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2ed693ac45cee618f8742c52c15bb13ce7baadf3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/app/cell2cell_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_cell2cell/app/cell2cell_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_cell2cell' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ebd427d3de21ee00e9aa8b70b9a7ea572b5c7391 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-cell2cell: + build: . + image: mcp-cell2cell:latest + container_name: mcp-cell2cell + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=cell2cell + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ef46f50cdf2ae312bc852d2aefb5db5e88820e4e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - cell2cell + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cell2cell/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e91bce153a3efec819bb60fd2e743d4e6c250ee6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install checkatlas via conda (e.g., from bioconda) +RUN conda install -c bioconda checkatlas -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/checkatlas_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/checkatlas_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/checkatlas_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/__pycache__/checkatlas_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/__pycache__/checkatlas_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ae625aa4dc4778a703171d7b4fa5065c7596e77 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/__pycache__/checkatlas_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/checkatlas_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/checkatlas_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc05ac225b1dac6d482dc84d35aa6d4c1578897 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/checkatlas_server.py @@ -0,0 +1,131 @@ +import subprocess +import logging +from pathlib import Path +from typing import Literal, List, Dict, Any +import tempfile + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# MCP decorator placeholder - in a real environment, this would be imported +def mcp_tool_placeholder(): + def decorator(func): + # This wrapper is a simple pass-through for demonstration. + # A real MCP decorator would handle marshalling, execution environment, etc. + return func + return decorator + +class mcp: + tool = mcp_tool_placeholder + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_checkatlas' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def checkatlas( + atlas_path: Path, + output_dir: Path, + atlas_name: str, + qc_type: Literal["scanpy", "seurat", "cellranger"], +) -> Dict[str, Any]: + """ + Run CheckAtlas to generate quality control tables and figures for a single-cell atlas. + + CheckAtlas is a tool to check the quality of single-cell atlases. For every atlas, + it produces quality control tables and figures which can then be processed by multiqc. + This function wraps the core 'checkatlas' command-line script. + + Args: + atlas_path: Path to the input atlas file (e.g., .h5ad, .rds, .h5) or a folder containing atlas files. + output_dir: Path to the directory where all output files will be saved. + atlas_name: A descriptive name for the atlas, which will be used in the output reports. + qc_type: The type of the atlas file being processed. Must be one of 'scanpy', 'seurat', or 'cellranger'. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of generated output files. + """ + # 1. Input Validation + if not atlas_path.exists(): + raise FileNotFoundError(f"Input path '{atlas_path}' does not exist.") + if not atlas_name.strip(): + raise ValueError("The 'atlas_name' cannot be empty.") + + # 2. Output Directory Handling + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + logger.error(f"Error creating output directory '{output_dir}': {e}") + raise + + # 3. Command Construction + # Based on the tool's entrypoint, it takes four required arguments. + cmd = [ + "checkatlas", + "--path", str(atlas_path.resolve()), + "--output", str(output_dir.resolve()), + "--atlas_name", atlas_name, + "--qc_type", qc_type, + ] + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + # 4. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = result.stdout + stderr = result.stderr + logger.info("CheckAtlas executed successfully.") + if stdout: + logger.debug(f"STDOUT:\n{stdout}") + if stderr: + logger.warning(f"STDERR:\n{stderr}") + + except FileNotFoundError: + error_message = "Error: 'checkatlas' command not found. Please ensure the checkatlas package is installed and accessible in the system's PATH." + logger.error(error_message) + # Return a structured error that conforms to the expected output format + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_message, + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"CheckAtlas failed with exit code {e.returncode}.") + logger.error(f"STDOUT:\n{e.stdout}") + logger.error(f"STDERR:\n{e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 5. Collect and Return Structured Output + # The tool saves all its output in the specified output directory. + try: + output_files = [str(f) for f in output_dir.rglob("*") if f.is_file()] + if not output_files: + logger.warning(f"CheckAtlas ran successfully but produced no output files in '{output_dir}'.") + except Exception as e: + logger.error(f"Error collecting output files from '{output_dir}': {e}") + output_files = [] + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/checkatlas_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/checkatlas_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..299c72a3fadafc2590c99d4de062116ee7f15dd6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/checkatlas_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_checkatlas/app/checkatlas_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_checkatlas' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5622ecbaa3bd15c1bf5ab28d9cf53682f8e76032 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-checkatlas: + build: . + image: mcp-checkatlas:latest + container_name: mcp-checkatlas + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=checkatlas + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0476854f3a300bcf073dcbe08a628d6a837d6441 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - checkatlas + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_checkatlas/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..45c89e56842a0ba01a9945a2c6d554a3e8e2998e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install circos via conda (e.g., from bioconda) +RUN conda install -c bioconda circos -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/circos_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/circos_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/circos_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/__pycache__/circos_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/__pycache__/circos_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbaac9f49dc73979c15ae2ad048cab2e4224ef5c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/__pycache__/circos_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/circos_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/circos_server.py new file mode 100644 index 0000000000000000000000000000000000000000..831f111c9abfaf119dee6b61d193a7e5d216bbb2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/circos_server.py @@ -0,0 +1,252 @@ +import subprocess +import tempfile +import re +from pathlib import Path +from typing import Optional, List, Dict, Any + +# This is a mock decorator. In a real MCP environment, this would be provided by the mcp package. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def circos_run( + conf: Path, + outputfile: Optional[str] = None, + outputdir: Optional[Path] = None, + debug: bool = False, + debug_group: Optional[str] = None, + cdump: bool = False, + mdump: bool = False, + userconf: Optional[Path] = None, + params: Optional[List[str]] = None, + nosvg: bool = False, + nopng: bool = False, +) -> Dict[str, Any]: + """ + Generates a Circos plot from a configuration file. + + This is the main tool for creating visualizations. It takes a configuration + file and various command-line overrides to produce PNG and/or SVG images. + It can also be used to dump configuration for debugging purposes. + + Args: + conf: The main Circos configuration file. + outputfile: The name of the output image file. + outputdir: The directory where the output files will be saved. + debug: Enable debugging output for all groups. + debug_group: Debug a specific group (e.g., 'summary', 'ideogram'). + cdump: Dump the parsed configuration and exit. + mdump: Dump the module configuration and exit. + userconf: Provide an additional user configuration file. + params: A list of 'key=value' strings to override configuration parameters. + nosvg: Disable SVG output. + nopng: Disable PNG output. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if not conf.is_file(): + raise FileNotFoundError(f"Configuration file not found: {conf}") + if userconf and not userconf.is_file(): + raise FileNotFoundError(f"User configuration file not found: {userconf}") + if params: + for p in params: + if not re.match(r"^\S+=\S+$", p): + raise ValueError(f"Invalid parameter format: '{p}'. Expected 'key=value'.") + + cmd = ["circos"] + cmd.extend(["-conf", str(conf)]) + + if outputfile: + cmd.extend(["-outputfile", outputfile]) + if outputdir: + outputdir.mkdir(parents=True, exist_ok=True) + cmd.extend(["-outputdir", str(outputdir)]) + if debug: + cmd.append("-debug") + if debug_group: + cmd.extend(["-debug_group", debug_group]) + if cdump: + cmd.append("-cdump") + if mdump: + cmd.append("-mdump") + if userconf: + cmd.extend(["-userconf", str(userconf)]) + if params: + for p in params: + cmd.extend(["-param", p]) + if nosvg: + cmd.append("-nosvg") + if nopng: + cmd.append("-nopng") + + command_executed = " ".join(cmd) + + try: + if outputdir: + work_dir = outputdir + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, cwd=work_dir + ) + # Scan the specified output directory for generated files + output_files = [str(p) for p in work_dir.glob("*.*")] + else: + with tempfile.TemporaryDirectory() as temp_dir: + work_dir = Path(temp_dir) + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, cwd=work_dir + ) + # Scan the temporary directory for generated files + output_files = [str(p) for p in work_dir.glob("*.*")] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": sorted(list(set(output_files))) + } + except FileNotFoundError: + raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Circos failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool +def circos_list_colors() -> Dict[str, Any]: + """Lists all available colors in Circos.""" + cmd = ["circos", "-colorlist"] + command_executed = " ".join(cmd) + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Circos failed with exit code {e.returncode}", + } + +@mcp.tool +def circos_list_fonts() -> Dict[str, Any]: + """Lists all available fonts in Circos.""" + cmd = ["circos", "-fontlist"] + command_executed = " ".join(cmd) + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Circos failed with exit code {e.returncode}", + } + +@mcp.tool +def circos_list_items(item_type: str) -> Dict[str, Any]: + """ + Lists available items of a given type (e.g., 'ideogram', 'highlight'). + + Args: + item_type: The type of item to list (e.g., ideogram, highlight, plot, link, rule). + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not item_type: + raise ValueError("item_type cannot be empty.") + + cmd = ["circos", "-list", item_type] + command_executed = " ".join(cmd) + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Circos failed with exit code {e.returncode}", + } + +@mcp.tool +def circos_show_rules(conf: Path) -> Dict[str, Any]: + """ + Shows the evaluation of rules for a given configuration. + + Args: + conf: The Circos configuration file to evaluate rules against. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not conf.is_file(): + raise FileNotFoundError(f"Configuration file not found: {conf}") + + cmd = ["circos", "-rules", "-conf", str(conf)] + command_executed = " ".join(cmd) + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Circos failed with exit code {e.returncode}", + } + +@mcp.tool +def circos_version() -> Dict[str, Any]: + """Shows the Circos version number.""" + cmd = ["circos", "-version"] + command_executed = " ".join(cmd) + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Circos failed with exit code {e.returncode}", + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/circos_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/circos_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5bca6e84d07290ea5e582879ababe257cf7bd6d1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/circos_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/app/circos_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_circos' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e0915b2a07ecf606bcc406087ff447720f8b025a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-circos: + build: . + image: mcp-circos:latest + container_name: mcp-circos + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=circos + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e8a3b56643b3d7d712ea5502944fe3da58e4763a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - circos + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_circos/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eb716cc02b3ed82157b190e6ce990aac387b416d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install clustalo via conda (e.g., from bioconda) +RUN conda install -c bioconda clustalo -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/clustalo_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/clustalo_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/clustalo_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/__pycache__/clustalo_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/__pycache__/clustalo_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a86280731dff47341d592787b681ebde16bbf8b Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/__pycache__/clustalo_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/clustalo_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/clustalo_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d795b1d238f3423c77135f6187db740833b499 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/clustalo_server.py @@ -0,0 +1,248 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Literal + +# @mcp.tool() decorator would be here in a real MCP environment +def clustalo( + infile: Path, + outfile: Optional[Path] = None, + hmm_in: Optional[List[Path]] = None, + hmm_batch: Optional[Path] = None, + dealign: bool = False, + profile1: Optional[Path] = None, + profile2: Optional[Path] = None, + is_profile: bool = False, + seqtype: Optional[Literal["Protein", "RNA", "DNA"]] = None, + infmt: Optional[Literal["a2m", "fasta", "fa", "sta", "clustal", "clu", "msf", "phylip", "phy", "selex", "stockholm", "st", "vienna", "vie"]] = None, + distmat_in: Optional[Path] = None, + distmat_out: Optional[Path] = None, + guidetree_in: Optional[Path] = None, + guidetree_out: Optional[Path] = None, + pileup: bool = False, + full: bool = False, + full_iter: bool = False, + cluster_size: Optional[int] = None, + clustering_out: Optional[Path] = None, + trans: int = 0, + posterior_out: Optional[Path] = None, + use_kimura: bool = False, + percent_id: bool = False, + outfmt: Literal["a2m", "fasta", "fa", "sta", "clustal", "clu", "msf", "phylip", "phy", "selex", "stockholm", "st", "vienna", "vie"] = "fasta", + residuenumber: bool = False, + wrap: Optional[int] = None, + output_order: Optional[Literal["input-order", "tree-order"]] = None, + iterations: Optional[int] = None, + max_guidetree_iterations: Optional[int] = None, + max_hmm_iterations: Optional[int] = None, + maxnumseq: Optional[int] = None, + maxseqlen: Optional[int] = None, + auto: bool = False, + threads: Optional[int] = None, + pseudo: Optional[Path] = None, + log: Optional[Path] = None, + verbose: int = 0, + force: bool = False, + mac_ram: Optional[int] = None, +): + """ + Run Clustal Omega for multiple sequence alignment. + + Clustal Omega is a fast, scalable tool for generating high-quality protein + and nucleic acid multiple sequence alignments. + + Args: + infile: Multiple sequence input file. + outfile: Multiple sequence alignment output file (default: stdout). + hmm_in: HMM input files. + hmm_batch: Specify HMMs for individual sequences. + dealign: Dealign input sequences. + profile1: Pre-aligned multiple sequence file (aligned columns will be kept fixed). + profile2: Pre-aligned multiple sequence file (aligned columns will be kept fixed). + is_profile: Disable check if profile, force profile (default: False). + seqtype: Force a sequence type (default: auto). + infmt: Forced sequence input file format (default: auto). + distmat_in: Pairwise distance matrix input file (skips distance computation). + distmat_out: Pairwise distance matrix output file. + guidetree_in: Guide tree input file (skips guide-tree clustering step). + guidetree_out: Guide tree output file. + pileup: Sequentially align sequences. + full: Use full distance matrix for guide-tree calculation (default: mBed). + full_iter: Use full distance matrix for guide-tree calculation during iteration (default: mBed). + cluster_size: Soft maximum of sequences in sub-clusters. + clustering_out: Clustering output file. + trans: Use transitivity (default: 0). + posterior_out: Posterior probability output file. + use_kimura: Use Kimura distance correction for aligned sequences (default: False). + percent_id: Convert distances into percent identities (default: False). + outfmt: MSA output file format (default: fasta). + residuenumber: In Clustal format, print residue numbers (default: False). + wrap: Number of residues before line-wrap in output. + output_order: MSA output order like in input/guide-tree. + iterations: Number of (combined guide-tree/HMM) iterations. + max_guidetree_iterations: Maximum number of guidetree iterations. + max_hmm_iterations: Maximum number of HMM iterations. + maxnumseq: Maximum allowed number of sequences. + maxseqlen: Maximum allowed sequence length. + auto: Set options automatically (might overwrite some of your options). + threads: Number of processors to use. + pseudo: Input file for pseudo-count parameters. + log: Log all non-essential output to this file. + verbose: Verbose output level (e.g., 1 for -v, 2 for -vv). + force: Force file overwriting. + mac_ram: Set a memory limit (undocumented, platform-specific). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not infile.is_file(): + raise FileNotFoundError(f"Input file not found: {infile}") + + input_files_to_check = { + "hmm_batch": hmm_batch, + "profile1": profile1, + "profile2": profile2, + "distmat_in": distmat_in, + "guidetree_in": guidetree_in, + "pseudo": pseudo, + } + for name, path in input_files_to_check.items(): + if path and not path.is_file(): + raise FileNotFoundError(f"Input file for --{name.replace('_', '-')} not found: {path}") + + if hmm_in: + for hmm_file in hmm_in: + if not hmm_file.is_file(): + raise FileNotFoundError(f"HMM input file not found: {hmm_file}") + + if threads is not None and threads <= 0: + raise ValueError("threads must be a positive integer.") + + if verbose < 0: + raise ValueError("verbose level cannot be negative.") + + # --- Command Construction --- + cmd = ["clustalo"] + output_files = [] + + # Sequence Input + cmd.extend(["--infile", str(infile)]) + if hmm_in: + for hmm_file in hmm_in: + cmd.extend(["--hmm-in", str(hmm_file)]) + if hmm_batch: + cmd.extend(["--hmm-batch", str(hmm_batch)]) + if dealign: + cmd.append("--dealign") + if profile1: + cmd.extend(["--profile1", str(profile1)]) + if profile2: + cmd.extend(["--profile2", str(profile2)]) + if is_profile: + cmd.append("--is-profile") + if seqtype: + cmd.extend(["--seqtype", seqtype]) + if infmt: + cmd.extend(["--infmt", infmt]) + + # Clustering + if distmat_in: + cmd.extend(["--distmat-in", str(distmat_in)]) + if distmat_out: + cmd.extend(["--distmat-out", str(distmat_out)]) + output_files.append(str(distmat_out)) + if guidetree_in: + cmd.extend(["--guidetree-in", str(guidetree_in)]) + if guidetree_out: + cmd.extend(["--guidetree-out", str(guidetree_out)]) + output_files.append(str(guidetree_out)) + if pileup: + cmd.append("--pileup") + if full: + cmd.append("--full") + if full_iter: + cmd.append("--full-iter") + if cluster_size is not None: + cmd.extend(["--cluster-size", str(cluster_size)]) + if clustering_out: + cmd.extend(["--clustering-out", str(clustering_out)]) + output_files.append(str(clustering_out)) + if trans != 0: + cmd.extend(["--trans", str(trans)]) + if posterior_out: + cmd.extend(["--posterior-out", str(posterior_out)]) + output_files.append(str(posterior_out)) + if use_kimura: + cmd.append("--use-kimura") + if percent_id: + cmd.append("--percent-id") + + # Alignment Output + if outfile: + cmd.extend(["--outfile", str(outfile)]) + output_files.append(str(outfile)) + cmd.extend(["--outfmt", outfmt]) + if residuenumber: + cmd.append("--residuenumber") + if wrap is not None: + cmd.extend(["--wrap", str(wrap)]) + if output_order: + cmd.extend(["--output-order", output_order]) + + # Iteration + if iterations is not None: + cmd.extend(["--iterations", str(iterations)]) + if max_guidetree_iterations is not None: + cmd.extend(["--max-guidetree-iterations", str(max_guidetree_iterations)]) + if max_hmm_iterations is not None: + cmd.extend(["--max-hmm-iterations", str(max_hmm_iterations)]) + + # Limits + if maxnumseq is not None: + cmd.extend(["--maxnumseq", str(maxnumseq)]) + if maxseqlen is not None: + cmd.extend(["--maxseqlen", str(maxseqlen)]) + + # Miscellaneous + if auto: + cmd.append("--auto") + if threads is not None: + cmd.extend(["--threads", str(threads)]) + if pseudo: + cmd.extend(["--pseudo", str(pseudo)]) + if log: + cmd.extend(["--log", str(log)]) + output_files.append(str(log)) + if verbose > 0: + cmd.append("-" + "v" * verbose) + if force: + cmd.append("--force") + if mac_ram is not None: + cmd.extend(["--MAC-RAM", str(mac_ram)]) + + # --- Subprocess Execution --- + try: + command_str = " ".join(cmd) + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except FileNotFoundError: + raise RuntimeError("clustalo command not found. Please ensure it is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # Return structured error information + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ClustalO failed with exit code {e.returncode}", + "output_files": [] + } diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/clustalo_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/clustalo_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7dffd7aff37ba6e02547f49edd514faa604e9b4e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/clustalo_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/app/clustalo_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_clustalo' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..50ecbc94d4624b00f0fe687ff464198dc02e71e7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-clustalo: + build: . + image: mcp-clustalo:latest + container_name: mcp-clustalo + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=clustalo + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca423df37f9d284dce831fcf7f072fd41a6a4d5d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - clustalo + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_clustalo/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c132e76a2a5f373203f48eb084dbdc778cdb5ddf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install crisprme via conda (e.g., from bioconda) +RUN conda install -c bioconda crisprme -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/crisprme_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/crisprme_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/crisprme_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/app/__pycache__/crisprme_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/app/__pycache__/crisprme_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c98ab0fac38849d5fd32f01149a2c534e7b8be92 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/app/__pycache__/crisprme_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/app/crisprme_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/app/crisprme_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..83e9ee6d609d1d9d3a899940dc8cfe0ffef8396f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/app/crisprme_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_crisprme/app/crisprme_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_crisprme' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..255cc496a1db6279ebf2ecbebae49444be05be2e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-crisprme: + build: . + image: mcp-crisprme:latest + container_name: mcp-crisprme + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=crisprme + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..303f9ce0932c15fb84df1658113385563d1bae33 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - crisprme + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_crisprme/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2222ff7bf8ac3bffacff217f71e88ee2d6bed932 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install cytoscape via conda (e.g., from bioconda) +RUN conda install -c bioconda cytoscape -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/cytoscape_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/cytoscape_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/cytoscape_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/__pycache__/cytoscape_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/__pycache__/cytoscape_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6807bac16020dfbfcb0586c56182b4aa91c2454 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/__pycache__/cytoscape_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/cytoscape_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/cytoscape_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3acb98117d1d20fa0142c47c7339662871d96805 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/cytoscape_server.py @@ -0,0 +1,145 @@ +import subprocess +from pathlib import Path +from typing import Optional, List +import logging + +# This is a placeholder for the actual MCP decorator. +# The final code should be used in an environment where `mcp` is defined. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_cytoscape' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def launch_cytoscape( + session_file: Optional[Path] = None, + network_files: Optional[List[Path]] = None, + properties_file: Optional[Path] = None, + vizmap_file: Optional[Path] = None, + script_file: Optional[Path] = None, + additional_files: Optional[List[Path]] = None, + rest_port: Optional[int] = None, + show_version: bool = False, + show_help: bool = False, + cytoscape_executable: str = "cytoscape", +) -> dict: + """ + Launches the Cytoscape application with specified command-line options. + + This tool wraps the main Cytoscape executable. It is primarily used to start + Cytoscape with pre-loaded sessions, networks, styles, or to execute a script + for automated, headless workflows. For automation, the `script_file` parameter + is crucial, and the provided script should handle all processing and file output, + concluding with a command to exit Cytoscape. + + Args: + session_file: Path to a Cytoscape session file (.cys) to load. Corresponds to the -s flag. + network_files: A list of paths to network files (e.g., .sif, .gml) to load. Corresponds to one or more -N flags. + properties_file: Path to a properties file (.props) to load. Corresponds to the -P flag. + vizmap_file: Path to a style/vizmap file (.xml) to load. Corresponds to the -V flag. + script_file: Path to a script file to execute upon startup. Essential for automated tasks. Corresponds to the -S flag. + additional_files: A list of paths to any other files (e.g., networks, sessions) to load as positional arguments. + rest_port: Starts Cytoscape and listens for CyREST commands on a specific port. Corresponds to the -R flag. + show_version: If True, prints Cytoscape version information and exits. Corresponds to the -v flag. + show_help: If True, prints the command-line help message and exits. Corresponds to the -h flag. + cytoscape_executable: The name or path of the Cytoscape executable. Defaults to 'cytoscape'. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Note: The `output_files` list will be empty as this wrapper cannot predict what files a user-provided script might generate. + """ + # 1. Input Validation + if show_help and show_version: + raise ValueError("The 'show_help' and 'show_version' parameters are mutually exclusive.") + + if session_file and not session_file.is_file(): + raise FileNotFoundError(f"Session file not found: {session_file}") + if properties_file and not properties_file.is_file(): + raise FileNotFoundError(f"Properties file not found: {properties_file}") + if vizmap_file and not vizmap_file.is_file(): + raise FileNotFoundError(f"VizMap (style) file not found: {vizmap_file}") + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"Script file not found: {script_file}") + + if network_files: + for f in network_files: + if not f.is_file(): + raise FileNotFoundError(f"Network file not found: {f}") + if additional_files: + for f in additional_files: + if not f.is_file(): + raise FileNotFoundError(f"Additional file not found: {f}") + + if rest_port is not None and not (1024 <= rest_port <= 65535): + raise ValueError(f"Invalid REST port: {rest_port}. Must be between 1024 and 65535.") + + # 2. Command Construction + cmd = [cytoscape_executable] + + if show_help: + cmd.append("--help") + elif show_version: + cmd.append("--version") + else: + if session_file: + cmd.extend(["--session", str(session_file)]) + if network_files: + for f in network_files: + cmd.extend(["--network", str(f)]) + if properties_file: + cmd.extend(["--props", str(properties_file)]) + if vizmap_file: + cmd.extend(["--vizmap", str(vizmap_file)]) + if script_file: + cmd.extend(["--script", str(script_file)]) + if rest_port is not None: + cmd.extend(["--rest", str(rest_port)]) + if additional_files: + cmd.extend([str(f) for f in additional_files]) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + error_message = f"Error: The executable '{cytoscape_executable}' was not found. Please ensure Cytoscape is installed and in your system's PATH, or provide the full path via the 'cytoscape_executable' parameter." + logging.error(error_message) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_message, + "output_files": [], + } + except subprocess.CalledProcessError as e: + logging.error(f"Cytoscape execution failed with return code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/cytoscape_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/cytoscape_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..57e8a06c2737dbda09fff2b84daaf60362802285 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/cytoscape_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_cytoscape/app/cytoscape_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_cytoscape' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c7fee9f78634f1510e03a3b47a2da7ca901c63bb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-cytoscape: + build: . + image: mcp-cytoscape:latest + container_name: mcp-cytoscape + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=cytoscape + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e1b5bcf43777bd05c8b83d4f4edee4db8a331311 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - cytoscape + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytoscape/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytotrace2-python/app/cytotrace2-python_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytotrace2-python/app/cytotrace2-python_server.py new file mode 100644 index 0000000000000000000000000000000000000000..016786b0702214f59bd44988413cc2a3d5ff572a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cytotrace2-python/app/cytotrace2-python_server.py @@ -0,0 +1,158 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Assume mcp is imported elsewhere, as per instructions "NO NEED to import mcp" + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_cytotrace2_python' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, + script_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line utility. + + This tool provides an interface to the Rscript command, allowing users to run + R scripts or evaluate R expressions directly from the command line with + various R environment configuration options. + + Args: + script_file: Path to the R script file (.R) to execute. + This parameter is mutually exclusive with 'expressions'. + If provided, the file must exist. + expressions: A list of R expressions (strings) to evaluate. Each string + in the list will be passed with a separate '-e' flag. + This parameter is mutually exclusive with 'script_file'. + verbose: If True, print information on R's progress during execution. + default_packages: A comma-separated list of package names (e.g., "stats,utils") + to load by default, or 'NULL' to load no default packages. + save: If True, save the R workspace at the end of the session. + no_environ: If True, do not read the site and user environment files. + no_site_file: If True, do not read the site-wide Rprofile. + no_init_file: If True, do not read the user R profile. + restore: If True, restore previously saved objects at startup. + vanilla: If True, combine --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ. This option overrides + individual settings for these flags. + script_args: A list of additional arguments (strings) to pass directly + to the R script being executed. These arguments are accessible + within the R script via `commandArgs(trailingOnly=TRUE)`. + + Returns: + A dictionary containing the command executed, standard output, standard error, + and a list of any output files generated (though Rscript itself doesn't + produce named output files unless specified within the R script). + + Raises: + ValueError: If neither 'script_file' nor 'expressions' is provided, + or if both are provided. + FileNotFoundError: If 'script_file' is provided but the file does not exist. + """ + # Input validation for mutually exclusive parameters + if script_file is None and expressions is None: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + if script_file is not None and expressions is not None: + raise ValueError("Cannot provide both 'script_file' and 'expressions'. Choose one.") + + # Validate script_file existence if provided + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"R script file not found: {script_file}") + # Optional: Check for .R extension, though Rscript can run any file + if script_file.suffix.lower() != ".r": + print(f"Warning: Script file '{script_file}' does not have a '.R' extension. " + "Rscript will attempt to execute it regardless.") + + command: List[str] = ["Rscript"] + + # Add Rscript options + if verbose: + command.append("--verbose") + if default_packages is not None: + command.append(f"--default-packages={default_packages}") + if save: + command.append("--save") + if no_environ: + command.append("--no-environ") + if no_site_file: + command.append("--no-site-file") + if no_init_file: + command.append("--no-init-file") + if restore: + command.append("--restore") + if vanilla: + command.append("--vanilla") + + # Add expressions or script file + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + elif script_file: + command.append(str(script_file)) + + # Add arguments to be passed to the R script + if script_args: + command.extend(script_args) + + command_str = " ".join(command) + output_files: List[Path] = [] # Rscript itself doesn't produce standard output files. + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}. " + f"Command: {command_str}", + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Rscript command not found. Please ensure R is installed and Rscript is in your system's PATH.", + "error": "Rscript executable not found.", + "output_files": output_files, + } + except Exception as e: + return { + "command_executed": command_str, + "stdout": "", + "stderr": str(e), + "error": f"An unexpected error occurred during Rscript execution: {e}", + "output_files": output_files, + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7bc8ca72a30291036ba79c135b0f701b43173988 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install deeptools via conda (e.g., from bioconda) +RUN conda install -c bioconda deeptools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/deeptools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/deeptools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/deeptools_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/__pycache__/deeptools_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/__pycache__/deeptools_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ba17cef8eb66986b92fc98656218ef5c6a50b39 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/__pycache__/deeptools_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/deeptools_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/deeptools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..85e7af4a0ed34332b023fa7393abba9235a3f487 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/deeptools_server.py @@ -0,0 +1,107 @@ +import subprocess +import shlex +from pathlib import Path +from typing import List, Optional, Dict, Any + +# The provided documentation for deeptools (web docs extract, conda search info) +# does not contain any specific command-line subcommands or their parameters. +# It describes deeptools as a "suite of python tools" and outlines its general +# capabilities (processing reads, quality checks, creating normalized coverage +# files, visualization), but does not list the actual command-line syntax, +# subcommands like `bamCoverage`, `computeMatrix`, `plotHeatmap`, or their +# respective arguments, types, and default values. + +# Therefore, it is impossible to fulfill the core requirements of the task: +# 1. "Extract all internal subcommands/tools and implement a separate Python function for each" +# 2. "Identify: All CLI parameters (positional & optional), including Input Data, and Advanced options +# Parameter types (str, int, float, bool, Path, etc.) +# Default values (MUST match the parameter’s type) +# Parameter constraints (e.g., value ranges, required if another is set)" +# 3. "Use explicit parameter definitions only (DO NOT USE **kwargs)" + +# Without the actual command-line help output for deeptools and its subcommands +# (e.g., `deeptools --help`, `deeptools bamCoverage --help`), I cannot +# accurately define the functions and their parameters as required by the MCP tool format. + +# As the prompt strictly requires generating production-ready Python code with @mcp.tool decorators, +# and to adhere to the format, a placeholder tool is provided. This tool explicitly +# states the limitation and serves as a template for where actual deeptools subcommands +# and their parameters would be defined if the necessary documentation were available. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_deeptools' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def deeptools_run_generic_command( + subcommand: str, + additional_args: Optional[List[str]] = None, + dry_run: bool = False, +) -> Dict[str, Any]: + """ + A generic placeholder tool for running deeptools subcommands. + + This tool is provided because the input documentation does not contain + specific command-line subcommands or their parameters. + To create fully functional MCP tools for deeptools, please provide + the detailed `--help` output for `deeptools` and its individual subcommands + (e.g., `deeptools bamCoverage --help`, `deeptools computeMatrix --help`). + + Args: + subcommand: The deeptools subcommand to execute (e.g., "bamCoverage", "computeMatrix"). + Note: This parameter is generic due to missing documentation. + additional_args: A list of additional command-line arguments for the subcommand. + These arguments are passed as-is and are not type-validated + or explicitly defined due to missing documentation. + dry_run: If True, the command will be printed but not executed. + """ + if not subcommand: + raise ValueError("Subcommand cannot be empty.") + + command = ["deeptools", subcommand] + if additional_args: + command.extend(additional_args) + + command_str = shlex.join(command) + + if dry_run: + return { + "command_executed": command_str, + "stdout": f"Dry run: Command would be executed: {command_str}", + "stderr": "", + "output_files": [], + } + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'deeptools' command not found. Please ensure deeptools is installed and in your PATH.", + "error": "Deeptools executable not found.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Deeptools subcommand '{subcommand}' failed with exit code {e.returncode}.", + "output_files": [], + } + + # This generic tool cannot predict output files, so it returns an empty list. + # Specific tools would identify and return their expected output files. + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/deeptools_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/deeptools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..661c0ec011e2de648bee2d6cee225357c7625e44 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/deeptools_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_deeptools/app/deeptools_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_deeptools' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2c7342d922cfc82320f25f6b62e17a192d1a593c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-deeptools: + build: . + image: mcp-deeptools:latest + container_name: mcp-deeptools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=deeptools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..86b8dd1dcc8b00a731a56f1e8d833a41069823a5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - deeptools + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..384993aa1611eaf135fe23a9f9db8786601ff9cb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install easy_vitessce via conda (e.g., from bioconda) +RUN conda install -c bioconda easy_vitessce -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/easy_vitessce_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/easy_vitessce_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/easy_vitessce_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/__pycache__/easy_vitessce_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/__pycache__/easy_vitessce_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8dccd410402656f32da03258f072f31db6606c1 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/__pycache__/easy_vitessce_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/easy_vitessce_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/easy_vitessce_server.py new file mode 100644 index 0000000000000000000000000000000000000000..558de9f44b8e5b96e64b851a3dcfdb9972c4f728 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/easy_vitessce_server.py @@ -0,0 +1,283 @@ +from pathlib import Path +import subprocess +import tempfile +import json +from typing import Optional, List, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_easy_vitessce' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def scanpy_embedding_to_vitessce( + adata_path: str, + output_dir: str, + plot_type: str = "umap", + basis: Optional[str] = None, + color: Optional[str] = None, + gene_list: Optional[List[str]] = None, + host_url: str = "http://localhost:8000", +): + """ + Convert a Scanpy AnnData object's embedding plot (UMAP, tSNE, PCA) into an interactive Vitessce visualization. + + :param adata_path: Path to the input .h5ad file. + :param output_dir: Directory where Vitessce data assets and configuration will be exported. + :param plot_type: Type of embedding to visualize ('umap', 'tsne', 'pca', 'embedding'). + :param basis: The name of the embedding to use (required if plot_type is 'embedding', e.g., 'X_draw_graph_fa'). + :param color: Key for annotations (obs) or gene names (var) to color the plot by. + :param gene_list: Optional list of genes to include in the visualization. + :param host_url: The base URL where the exported files will be served (default: http://localhost:8000). + """ + # Input validation + input_path = Path(adata_path) + if not input_path.exists(): + return {"error": f"Input file not found: {adata_path}"} + + out_path = Path(output_dir) + out_path.mkdir(parents=True, exist_ok=True) + + if plot_type == "embedding" and not basis: + return {"error": "Parameter 'basis' is required when plot_type is 'embedding'"} + + valid_plots = ["umap", "tsne", "pca", "embedding"] + if plot_type not in valid_plots: + return {"error": f"Invalid plot_type. Must be one of {valid_plots}"} + + # Construct Python script to execute easy_vitessce + # easy_vitessce patches scanpy.pl on import. + # We capture the returned VitessceConfig and export it. + python_script = f""" +import scanpy as sc +import easy_vitessce as ev +import os + +adata = sc.read_h5ad('{adata_path}') +# easy_vitessce is enabled by default upon import + +# Prepare plotting arguments +kwargs = {{}} +if '{color}': kwargs['color'] = '{color}' +if {gene_list}: kwargs['var_names'] = {gene_list} +if '{basis}' and '{plot_type}' == 'embedding': kwargs['basis'] = '{basis}' + +# Call the patched scanpy plotting function +# In easy_vitessce, these return a VitessceConfig or Widget object +if '{plot_type}' == 'umap': + vc = sc.pl.umap(adata, show=False, **kwargs) +elif '{plot_type}' == 'tsne': + vc = sc.pl.tsne(adata, show=False, **kwargs) +elif '{plot_type}' == 'pca': + vc = sc.pl.pca(adata, show=False, **kwargs) +else: + vc = sc.pl.embedding(adata, show=False, **kwargs) + +# Export the configuration and data +# Note: easy_vitessce objects usually have a .config attribute or are the config themselves +if hasattr(vc, 'config'): + config = vc.config +else: + config = vc + +config.export(targets=['files'], dest='{output_dir}', base_url='{host_url}') +print("Export successful") +""" + + try: + result = subprocess.run( + ["python", "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"easy_vitessce conversion for {plot_type}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(out_path.absolute()), + "vitessce_config_file": str((out_path / "config.json").absolute()) + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to generate Vitessce configuration", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def scanpy_matrix_to_vitessce( + adata_path: str, + output_dir: str, + plot_type: str = "violin", + var_names: Optional[List[str]] = None, + groupby: Optional[str] = None, + host_url: str = "http://localhost:8000", +): + """ + Convert Scanpy matrix-style plots (Violin, Dotplot, Heatmap) into interactive Vitessce visualizations. + + :param adata_path: Path to the input .h5ad file. + :param output_dir: Directory where Vitessce data assets and configuration will be exported. + :param plot_type: Type of plot ('violin', 'dotplot', 'heatmap'). + :param var_names: List of genes/variables to plot. + :param groupby: The key of the observation grouping to consider. + :param host_url: The base URL where the exported files will be served. + """ + input_path = Path(adata_path) + if not input_path.exists(): + return {"error": f"Input file not found: {adata_path}"} + + out_path = Path(output_dir) + out_path.mkdir(parents=True, exist_ok=True) + + valid_plots = ["violin", "dotplot", "heatmap"] + if plot_type not in valid_plots: + return {"error": f"Invalid plot_type. Must be one of {valid_plots}"} + + python_script = f""" +import scanpy as sc +import easy_vitessce as ev + +adata = sc.read_h5ad('{adata_path}') +vars = {var_names if var_names else "adata.var_names[:5].tolist()"} +group = '{groupby}' if '{groupby}' else None + +if '{plot_type}' == 'violin': + vc = sc.pl.violin(adata, keys=vars, groupby=group, show=False) +elif '{plot_type}' == 'dotplot': + vc = sc.pl.dotplot(adata, var_names=vars, groupby=group, show=False) +else: + vc = sc.pl.heatmap(adata, var_names=vars, groupby=group, show=False) + +if hasattr(vc, 'config'): + config = vc.config +else: + config = vc + +config.export(targets=['files'], dest='{output_dir}', base_url='{host_url}') +""" + + try: + result = subprocess.run( + ["python", "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"easy_vitessce matrix conversion for {plot_type}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(out_path.absolute()) + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to generate Vitessce configuration", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def spatialdata_to_vitessce( + sdata_path: str, + output_dir: str, + host_url: str = "http://localhost:8000", +): + """ + Convert a SpatialData object into an interactive Vitessce visualization. + Supports images, labels, shapes, and points. + + :param sdata_path: Path to the SpatialData .zarr store. + :param output_dir: Directory where Vitessce data assets and configuration will be exported. + :param host_url: The base URL where the exported files will be served. + """ + input_path = Path(sdata_path) + if not input_path.exists(): + return {"error": f"SpatialData path not found: {sdata_path}"} + + out_path = Path(output_dir) + out_path.mkdir(parents=True, exist_ok=True) + + python_script = f""" +import spatialdata as sd +import easy_vitessce as ev +import spatialdata_plot + +sdata = sd.read_zarr('{sdata_path}') + +# easy_vitessce patches sdata.pl.render_images, etc. +# Calling the plot method on sdata (via spatialdata-plot) triggers the Vitessce wrapper +# We use a generic render call that easy_vitessce captures +vc = sdata.pl.render_images().pl.show() + +if hasattr(vc, 'config'): + config = vc.config +else: + config = vc + +config.export(targets=['files'], dest='{output_dir}', base_url='{host_url}') +""" + + try: + result = subprocess.run( + ["python", "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "easy_vitessce spatialdata conversion", + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(out_path.absolute()) + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to generate Vitessce configuration for SpatialData", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def toggle_easy_vitessce( + enable: bool = True, + plot_types: Optional[List[str]] = None, +): + """ + Enable or disable interactive Vitessce plots for specific categories. + Note: In this MCP context, this is primarily used to verify configuration. + + :param enable: Whether to enable (True) or disable (False) interactive plots. + :param plot_types: List of plot types to toggle (e.g., ['embedding', 'violin', 'spatialdata-plot']). + If None, toggles all. + """ + action = "enable_plots" if enable else "disable_plots" + types_arg = f"{plot_types}" if plot_types else "" + + python_script = f""" +import easy_vitessce as ev +ev.{action}({types_arg}) +print(f"Successfully called ev.{action}({types_arg})") +""" + + try: + result = subprocess.run( + ["python", "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "status": "success", + "stdout": result.stdout, + "action_performed": action + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to perform {action}", + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/easy_vitessce_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/easy_vitessce_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dce02ed8397f5b9e498415a06622798634274b84 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/easy_vitessce_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_easy_vitessce/app/easy_vitessce_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_easy_vitessce' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8e3b9e245a067a7ff8e1fcfcdd97e572d32b1bec --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-easy_vitessce: + build: . + image: mcp-easy_vitessce:latest + container_name: mcp-easy_vitessce + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=easy_vitessce + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9503765b82532070903068fd3efe9f1bd5103c56 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - easy_vitessce + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_easy_vitessce/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2410f3d89e63390d6b3b112d9cd15cf862195919 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install emboss via conda (e.g., from bioconda) +RUN conda install -c bioconda emboss -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/emboss_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/emboss_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/emboss_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/__pycache__/emboss_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/__pycache__/emboss_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4be49d5391c6f77707239c1883dd83e56e4bfe5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/__pycache__/emboss_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/emboss_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/emboss_server.py new file mode 100644 index 0000000000000000000000000000000000000000..28c9e120d4f63e61703509368511167ee5527b36 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/emboss_server.py @@ -0,0 +1,547 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_emboss' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def seqret( + sequence: str, + outseq: str, + sformat: Optional[str] = None, + osformat: Optional[str] = None, + feature: bool = False, + firstonly: bool = False, +): + """ + Reads and writes (reformats) sequences. Supports a vast array of formats (FASTA, GenBank, EMBL, etc.). + + :param sequence: Input sequence file path or USA (Uniform Sequence Address). + :param outseq: Output sequence file path. + :param sformat: Input sequence format (e.g., 'fasta', 'genbank'). + :param osformat: Output sequence format (e.g., 'fasta', 'embl'). + :param feature: Use feature information if True. + :param firstonly: Read only the first sequence if True. + """ + input_path = Path(sequence) + if not input_path.exists(): + return {"error": f"Input file {sequence} not found."} + + cmd = ["seqret", "-sequence", sequence, "-outseq", outseq, "-auto"] + + if sformat: + cmd.extend(["-sformat", sformat]) + if osformat: + cmd.extend(["-osformat", osformat]) + if feature: + cmd.append("-feature") + if firstonly: + cmd.append("-firstonly") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outseq] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def transeq( + sequence: str, + outseq: str, + frame: str = "1", + table: int = 0, + regions: Optional[str] = None, + trim: bool = False, + clean: bool = False, +): + """ + Translates nucleic acid sequences to protein sequences. + + :param sequence: Input nucleic acid sequence file. + :param outseq: Output protein sequence file. + :param frame: Frame(s) to translate. (1, 2, 3, F, -1, -2, -3, R, 6). Default '1'. + :param table: Genetic code table to use (0-23). 0 is standard. + :param regions: Regions to translate (e.g., '1-100, 200-300'). + :param trim: Stop at first stop codon if True. + :param clean: Change all non-amino acid characters to 'X'. + """ + if not Path(sequence).exists(): + return {"error": f"Input file {sequence} not found."} + + cmd = ["transeq", "-sequence", sequence, "-outseq", outseq, "-frame", frame, "-table", str(table), "-auto"] + + if regions: + cmd.extend(["-regions", regions]) + if trim: + cmd.append("-trim") + if clean: + cmd.append("-clean") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outseq] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def needle( + asequence: str, + bsequence: str, + outfile: str, + gapopen: float = 10.0, + gapextend: float = 0.5, + endweight: bool = False, + endopen: float = 10.0, + endextend: float = 0.5, + aformat: str = "pair", +): + """ + Needleman-Wunsch global alignment of two sequences. + + :param asequence: First sequence file. + :param bsequence: Second sequence file. + :param outfile: Output alignment file. + :param gapopen: Gap opening penalty. + :param gapextend: Gap extension penalty. + :param endweight: Apply end gap penalties if True. + :param endopen: End gap opening penalty. + :param endextend: End gap extension penalty. + :param aformat: Output alignment format (pair, markx0, srspair, etc.). + """ + if not Path(asequence).exists() or not Path(bsequence).exists(): + return {"error": "One or both input sequence files not found."} + + cmd = [ + "needle", "-asequence", asequence, "-bsequence", bsequence, + "-outfile", outfile, "-gapopen", str(gapopen), "-gapextend", str(gapextend), + "-aformat", aformat, "-auto" + ] + + if endweight: + cmd.extend(["-endweight", "-endopen", str(endopen), "-endextend", str(endextend)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def water( + asequence: str, + bsequence: str, + outfile: str, + gapopen: float = 10.0, + gapextend: float = 0.5, + aformat: str = "pair", +): + """ + Smith-Waterman local alignment of two sequences. + + :param asequence: First sequence file. + :param bsequence: Second sequence file. + :param outfile: Output alignment file. + :param gapopen: Gap opening penalty. + :param gapextend: Gap extension penalty. + :param aformat: Output alignment format. + """ + if not Path(asequence).exists() or not Path(bsequence).exists(): + return {"error": "Input files not found."} + + cmd = [ + "water", "-asequence", asequence, "-bsequence", bsequence, + "-outfile", outfile, "-gapopen", str(gapopen), "-gapextend", str(gapextend), + "-aformat", aformat, "-auto" + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def pepstats( + sequence: str, + outfile: str, + termini: bool = True, + mono: bool = False, +): + """ + Calculates statistics of protein properties (MW, pI, charge, etc.). + + :param sequence: Input protein sequence file. + :param outfile: Output report file. + :param termini: Include charge on N and C termini if True. + :param mono: Use monoisotopic weights if True. + """ + if not Path(sequence).exists(): + return {"error": f"Input file {sequence} not found."} + + cmd = ["pepstats", "-sequence", sequence, "-outfile", outfile, "-auto"] + if not termini: + cmd.append("-notermini") + if mono: + cmd.append("-mono") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def getorf( + sequence: str, + outseq: str, + table: int = 0, + minsize: int = 30, + maxsize: int = 1000000, + find: int = 0, + methionine: bool = True, + circular: bool = False, +): + """ + Finds and extracts Open Reading Frames (ORFs). + + :param sequence: Input nucleotide sequence file. + :param outseq: Output sequence file of ORFs. + :param table: Genetic code table (0-23). + :param minsize: Minimum size of ORF to report (nucleotides). + :param maxsize: Maximum size of ORF to report. + :param find: Type of ORF to find (0: Translation between STOPs, 1: Translation between START-STOP, etc.). + :param methionine: START codons must be Methionine if True. + :param circular: Sequence is circular if True. + """ + if not Path(sequence).exists(): + return {"error": f"Input file {sequence} not found."} + + cmd = [ + "getorf", "-sequence", sequence, "-outseq", outseq, + "-table", str(table), "-minsize", str(minsize), "-maxsize", str(maxsize), + "-find", str(find), "-auto" + ] + if not methionine: + cmd.append("-nomethionine") + if circular: + cmd.append("-circular") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outseq] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def infoseq( + sequence: str, + outfile: Optional[str] = None, + name: bool = True, + type: bool = True, + length: bool = True, + pgc: bool = True, + description: bool = True, + heading: bool = True, +): + """ + Displays basic information about sequences. + + :param sequence: Input sequence file. + :param outfile: Output file (if None, returns to stdout). + :param name: Display name column. + :param type: Display type column. + :param length: Display length column. + :param pgc: Display percent GC column. + :param description: Display description column. + :param heading: Display column headings. + """ + if not Path(sequence).exists(): + return {"error": f"Input file {sequence} not found."} + + cmd = ["infoseq", "-sequence", sequence, "-auto"] + if outfile: + cmd.extend(["-outfile", outfile]) + else: + cmd.append("-stdout") + + if not name: cmd.append("-noname") + if not type: cmd.append("-notype") + if not length: cmd.append("-nolength") + if not pgc: cmd.append("-nopgc") + if not description: cmd.append("-nodescription") + if not heading: cmd.append("-noheading") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] if outfile else [] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def fuzznuc( + sequence: str, + pattern: str, + outfile: str, + mismatch: int = 0, + complement: bool = False, +): + """ + Search for patterns in nucleotide sequences using IUPAC ambiguity codes. + + :param sequence: Input nucleotide sequence file. + :param pattern: Search pattern (e.g., 'GAT[CG]A'). + :param outfile: Output report file. + :param mismatch: Number of mismatches allowed. + :param complement: Search the complement of the sequence as well. + """ + if not Path(sequence).exists(): + return {"error": f"Input file {sequence} not found."} + + cmd = [ + "fuzznuc", "-sequence", sequence, "-pattern", pattern, + "-outfile", outfile, "-mismatch", str(mismatch), "-auto" + ] + if complement: + cmd.append("-complement") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def matcher( + asequence: str, + bsequence: str, + outfile: str, + gapopen: int = 14, + gapextend: int = 4, + alternatives: int = 1, +): + """ + Finds significant local alignments between two sequences using the LALIGN algorithm. + + :param asequence: First sequence file. + :param bsequence: Second sequence file. + :param outfile: Output alignment file. + :param gapopen: Gap opening penalty. + :param gapextend: Gap extension penalty. + :param alternatives: Number of alternative alignments to output. + """ + if not Path(asequence).exists() or not Path(bsequence).exists(): + return {"error": "Input files not found."} + + cmd = [ + "matcher", "-asequence", asequence, "-bsequence", bsequence, + "-outfile", outfile, "-gapopen", str(gapopen), "-gapextend", str(gapextend), + "-alternatives", str(alternatives), "-auto" + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def stretcher( + asequence: str, + bsequence: str, + outfile: str, + gapopen: int = 12, + gapextend: int = 2, +): + """ + Finds a global alignment of two sequences using a modified Needleman-Wunsch (faster for long sequences). + + :param asequence: First sequence file. + :param bsequence: Second sequence file. + :param outfile: Output alignment file. + :param gapopen: Gap opening penalty. + :param gapextend: Gap extension penalty. + """ + if not Path(asequence).exists() or not Path(bsequence).exists(): + return {"error": "Input files not found."} + + cmd = [ + "stretcher", "-asequence", asequence, "-bsequence", bsequence, + "-outfile", outfile, "-gapopen", str(gapopen), "-gapextend", str(gapextend), + "-auto" + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def backtranseq( + sequence: str, + outseq: str, + table: int = 0, + codon: Optional[str] = None, +): + """ + Back-translates a protein sequence to a nucleotide sequence. + + :param sequence: Input protein sequence file. + :param outseq: Output nucleotide sequence file. + :param table: Genetic code table (0-23). + :param codon: Codon usage file (optional). + """ + if not Path(sequence).exists(): + return {"error": f"Input file {sequence} not found."} + + cmd = ["backtranseq", "-sequence", sequence, "-outseq", outseq, "-table", str(table), "-auto"] + if codon: + cmd.extend(["-codon", codon]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outseq] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def cpgplot( + sequence: str, + outfile: str, + window: int = 100, + minlen: int = 200, + minpc: float = 50.0, + minoe: float = 0.6, + plot: bool = False, +): + """ + Identifies and plots CpG islands in nucleotide sequences. + + :param sequence: Input nucleotide sequence file. + :param outfile: Output report file. + :param window: Window size for calculation. + :param minlen: Minimum length of a CpG island. + :param minpc: Minimum percentage of G+C. + :param minoe: Minimum observed/expected ratio of CpG. + :param plot: Generate a plot (requires graphical environment). + """ + if not Path(sequence).exists(): + return {"error": f"Input file {sequence} not found."} + + cmd = [ + "cpgplot", "-sequence", sequence, "-outfile", outfile, + "-window", str(window), "-minlen", str(minlen), + "-minpc", str(minpc), "-minoe", str(minoe), "-auto" + ] + if not plot: + cmd.append("-graph") + cmd.append("none") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def wossname( + search: str = "", + explode: bool = False, + embassy: bool = True, +): + """ + Finds EMBOSS programs by keywords in their one-line descriptions. + + :param search: Keyword to search for. If empty, lists all tools. + :param explode: Expand the group names. + :param embassy: Include EMBASSY applications. + """ + cmd = ["wossname", "-auto"] + if search: + cmd.extend(["-search", search]) + if explode: + cmd.append("-explode") + if not embassy: + cmd.append("-noembassy") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/emboss_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/emboss_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bf6a6f211f40806c55d8642e4bc41bf73d7a4067 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/emboss_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_emboss/app/emboss_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_emboss' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9c5aca30ecbab468296c71bd8c158e83260737c8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-emboss: + build: . + image: mcp-emboss:latest + container_name: mcp-emboss + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=emboss + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b79aca885fecaeb2e3b7105f83eb9fdc9af2dc4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - emboss + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_emboss/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_f5c/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_f5c/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eaef5740a5c642df6299aa092a081142acb54aee --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_f5c/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install f5c via conda (e.g., from bioconda) +RUN conda install -c bioconda f5c -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/f5c_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/f5c_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/f5c_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_f5c/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_f5c/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..27e8b4b3b5a91d89ffed73d50a016ff54733c436 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_f5c/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-f5c: + build: . + image: mcp-f5c:latest + container_name: mcp-f5c + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=f5c + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_f5c/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_f5c/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1bf1537b730c60252e18ce645322db7804f478b2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_f5c/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - f5c + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastp/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cba5e72b61d72265377e0d4735c382eaa85788f7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastp/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install fastp via conda (e.g., from bioconda) +RUN conda install -c bioconda fastp -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/fastp_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/fastp_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/fastp_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8c23632ae44c5a2615f351c6239ded235be62a67 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install fwdpy11 via conda (e.g., from bioconda) +RUN conda install -c bioconda fwdpy11 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/fwdpy11_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/fwdpy11_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/fwdpy11_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/__pycache__/fwdpy11_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/__pycache__/fwdpy11_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69a29b1a8ec7705629de8c2eb5176a1318410362 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/__pycache__/fwdpy11_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/fwdpy11_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/fwdpy11_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c66b816a6c60736540af22de12fd408db0f43733 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/fwdpy11_server.py @@ -0,0 +1,205 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# @mcp.tool() decorator is assumed to be available in the environment. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_fwdpy11' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def fwdpy11_list() -> Dict[str, Any]: + """ + Lists the names of available built-in simulations in fwdpy11. + + This corresponds to the `fwdpy11 list` command. + """ + command = ["fwdpy11", "list"] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "available_simulations": result.stdout.strip().split('\n') + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "fwdpy11 not found. Please ensure the tool is installed and in your PATH.", + "error": "FileNotFoundError" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CalledProcessError", + "return_code": e.returncode + } + +@mcp.tool() +def fwdpy11_info(name: str) -> Dict[str, Any]: + """ + Displays detailed information about a specific built-in simulation. + + This corresponds to the `fwdpy11 info ` command. + + Args: + name: The name of the simulation to get information about. + """ + if not name: + raise ValueError("The 'name' of the simulation must be provided.") + + command = ["fwdpy11", "info", name] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "fwdpy11 not found. Please ensure the tool is installed and in your PATH.", + "error": "FileNotFoundError" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CalledProcessError", + "return_code": e.returncode + } + +@mcp.tool() +def fwdpy11_run( + name: str, + nreps: int = 1, + seed: Optional[int] = None, + outfile: Optional[Path] = None, + ts: bool = False, + popsize: Optional[int] = None, + mu: Optional[float] = None, + recrate: Optional[float] = None, + simlen: Optional[int] = None, + parallel: int = 1, + extra_args: Optional[str] = None +) -> Dict[str, Any]: + """ + Runs a specific built-in simulation with the given parameters. + + This corresponds to the `fwdpy11 run [options]` command. + Common simulation parameters are exposed, and any others can be passed via extra_args. + + Args: + name: The name of the simulation to run. + nreps: The number of simulation replicates to perform. + seed: The seed for the random number generator. + outfile: The path to the output file. If not provided, output goes to stdout. + ts: If True, output a tskit.TreeSequence. + popsize: Population size (e.g., N). + mu: The mutation rate per gamete per generation. + recrate: The recombination rate per diploid per generation. + simlen: The length of the simulation in generations. + parallel: The number of cores to use for parallel execution. + extra_args: A string of additional command-line arguments for the simulation. + Example: "--opt 10 --dominance 0.5" + """ + if not name: + raise ValueError("The 'name' of the simulation must be provided.") + if nreps <= 0: + raise ValueError("nreps must be a positive integer.") + if parallel <= 0: + raise ValueError("parallel must be a positive integer.") + + command = ["fwdpy11", "run", name] + output_files = [] + + command.extend(["--nreps", str(nreps)]) + command.extend(["--parallel", str(parallel)]) + + if seed is not None: + command.extend(["--seed", str(seed)]) + + if ts: + command.append("--ts") + + if popsize is not None: + command.extend(["--popsize", str(popsize)]) + + if mu is not None: + command.extend(["--mu", str(mu)]) + + if recrate is not None: + command.extend(["--recrate", str(recrate)]) + + if simlen is not None: + command.extend(["--simlen", str(simlen)]) + + if extra_args: + command.extend(extra_args.split()) + + # Handle output file + if outfile: + # Ensure parent directory exists + outfile.parent.mkdir(parents=True, exist_ok=True) + command.extend(["--outfile", str(outfile)]) + output_files.append(str(outfile)) + stdout_dest = None # Let the process write to the file directly + else: + stdout_dest = subprocess.PIPE + + try: + result = subprocess.run( + command, + stdout=stdout_dest, + stderr=subprocess.PIPE, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout if result.stdout else "", + "stderr": result.stderr, + "output_files": output_files + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "fwdpy11 not found. Please ensure the tool is installed and in your PATH.", + "error": "FileNotFoundError", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout if e.stdout else "", + "stderr": e.stderr, + "error": "CalledProcessError", + "return_code": e.returncode, + "output_files": output_files + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/fwdpy11_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/fwdpy11_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..49c6bb52663b50d270811595f214c63a6c201c58 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/fwdpy11_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_fwdpy11/app/fwdpy11_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_fwdpy11' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8bd12bbbbe5bba551613902180701333d7ea1fff --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-fwdpy11: + build: . + image: mcp-fwdpy11:latest + container_name: mcp-fwdpy11 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=fwdpy11 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c5f53d38bd9bf2e9e2fc7e53127ccc81ac4b1ff4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - fwdpy11 + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fwdpy11/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0ba571fb2528762c712e5ce718471dfb7ecf844c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gatk via conda (e.g., from bioconda) +RUN conda install -c bioconda gatk -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gatk_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gatk_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gatk_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/__pycache__/gatk_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/__pycache__/gatk_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32917b5c3d9b8b6742aedd1706646c2123bdb555 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/__pycache__/gatk_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/gatk_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/gatk_server.py new file mode 100644 index 0000000000000000000000000000000000000000..70c1972f1db4de62f6362def06f4d5fbed3837fc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/gatk_server.py @@ -0,0 +1,391 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import shlex + +def run_gatk_command(tool_name: str, args: List[str]) -> dict: + """ + Helper function to execute GATK commands and return structured output. + """ + full_command = ["gatk", tool_name] + args + + try: + process = subprocess.run( + full_command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(map(shlex.quote, full_command)), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(map(shlex.quote, full_command)), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "exit_code": e.returncode + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_gatk' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def gatk_haplotype_caller( + input_bam: str, + reference: str, + output_vcf: str, + intervals: Optional[str] = None, + emit_ref_confidence: str = "NONE", + ploidy: int = 2, + min_base_quality_score: int = 10, + standard_min_confidence_threshold_for_calling: float = 30.0, +): + """ + Call germline SNPs and indels via local re-assembly of haplotypes. + """ + if not Path(input_bam).exists(): + raise FileNotFoundError(f"Input BAM not found: {input_bam}") + if not Path(reference).exists(): + raise FileNotFoundError(f"Reference FASTA not found: {reference}") + + args = [ + "-I", input_bam, + "-R", reference, + "-O", output_vcf, + "-ploidy", str(ploidy), + "--min-base-quality-score", str(min_base_quality_score), + "-stand-call-conf", str(standard_min_confidence_threshold_for_calling), + "-ERC", emit_ref_confidence + ] + + if intervals: + args.extend(["-L", intervals]) + + result = run_gatk_command("HaplotypeCaller", args) + result["output_files"] = [output_vcf] + return result + +@mcp.tool() +def gatk_mutect2( + input_bam: str, + reference: str, + output_vcf: str, + intervals: Optional[str] = None, + germline_resource: Optional[str] = None, + pon: Optional[str] = None, + normal_sample_name: Optional[str] = None, + f1r2_tar_gz: Optional[str] = None, +): + """ + Call somatic SNPs and indels via local assembly of haplotypes. + """ + if not Path(input_bam).exists(): + raise FileNotFoundError(f"Input BAM not found: {input_bam}") + + args = [ + "-I", input_bam, + "-R", reference, + "-O", output_vcf + ] + + if intervals: args.extend(["-L", intervals]) + if germline_resource: args.extend(["--germline-resource", germline_resource]) + if pon: args.extend(["-pon", pon]) + if normal_sample_name: args.extend(["-normal", normal_sample_name]) + if f1r2_tar_gz: args.extend(["--f1r2-tar-gz", f1r2_tar_gz]) + + result = run_gatk_command("Mutect2", args) + result["output_files"] = [output_vcf] + return result + +@mcp.tool() +def gatk_base_recalibrator( + input_bam: str, + reference: str, + known_sites: List[str], + output_report: str, + intervals: Optional[str] = None, +): + """ + Generate a recalibration table for Base Quality Score Recalibration (BQSR). + """ + if not Path(input_bam).exists(): + raise FileNotFoundError(f"Input BAM not found: {input_bam}") + + args = [ + "-I", input_bam, + "-R", reference, + "-O", output_report + ] + + for site in known_sites: + args.extend(["--known-sites", site]) + + if intervals: + args.extend(["-L", intervals]) + + result = run_gatk_command("BaseRecalibrator", args) + result["output_files"] = [output_report] + return result + +@mcp.tool() +def gatk_apply_bqsr( + input_bam: str, + reference: str, + recal_file: str, + output_bam: str, + static_quantized_quals: List[int] = [], +): + """ + Apply base quality score recalibration to a BAM/SAM/CRAM file. + """ + if not Path(recal_file).exists(): + raise FileNotFoundError(f"Recalibration file not found: {recal_file}") + + args = [ + "-I", input_bam, + "-R", reference, + "--bqsr-recal-file", recal_file, + "-O", output_bam + ] + + for q in static_quantized_quals: + args.extend(["--static-quantized-quals", str(q)]) + + result = run_gatk_command("ApplyBQSR", args) + result["output_files"] = [output_bam] + return result + +@mcp.tool() +def gatk_mark_duplicates( + input_bam: str, + output_bam: str, + metrics_file: str, + remove_duplicates: bool = False, + assume_sort_order: str = "coordinate", +): + """ + Locate and tag duplicate reads in a BAM or SAM file (Picard implementation). + """ + args = [ + "-I", input_bam, + "-O", output_bam, + "-M", metrics_file, + "--REMOVE_DUPLICATES", str(remove_duplicates).lower(), + "--ASSUME_SORT_ORDER", assume_sort_order + ] + + result = run_gatk_command("MarkDuplicates", args) + result["output_files"] = [output_bam, metrics_file] + return result + +@mcp.tool() +def gatk_genotype_gvcfs( + reference: str, + variant_gvcf: str, + output_vcf: str, + dbsnp: Optional[str] = None, + intervals: Optional[str] = None, +): + """ + Perform joint genotyping on one or more samples called with HaplotypeCaller in GVCF mode. + """ + args = [ + "-R", reference, + "-V", variant_gvcf, + "-O", output_vcf + ] + + if dbsnp: args.extend(["-D", dbsnp]) + if intervals: args.extend(["-L", intervals]) + + result = run_gatk_command("GenotypeGVCFs", args) + result["output_files"] = [output_vcf] + return result + +@mcp.tool() +def gatk_variant_filtration( + reference: str, + variant_vcf: str, + output_vcf: str, + filter_expressions: List[str], + filter_names: List[str], +): + """ + Filter variants based on hard-coded expressions. + """ + if len(filter_expressions) != len(filter_names): + raise ValueError("Number of filter expressions must match number of filter names.") + + args = [ + "-R", reference, + "-V", variant_vcf, + "-O", output_vcf + ] + + for expr, name in zip(filter_expressions, filter_names): + args.extend(["--filter-expression", expr, "--filter-name", name]) + + result = run_gatk_command("VariantFiltration", args) + result["output_files"] = [output_vcf] + return result + +@mcp.tool() +def gatk_select_variants( + reference: str, + variant_vcf: str, + output_vcf: str, + select_type: str = "SNP", + exclude_filtered: bool = False, +): + """ + Select a subset of variants from a VCF file. + """ + args = [ + "-R", reference, + "-V", variant_vcf, + "-O", output_vcf, + "--select-type-to-include", select_type + ] + + if exclude_filtered: + args.append("--exclude-filtered") + + result = run_gatk_command("SelectVariants", args) + result["output_files"] = [output_vcf] + return result + +@mcp.tool() +def gatk_combine_gvcfs( + reference: str, + variant_gvcfs: List[str], + output_vcf: str, +): + """ + Merges one or more HaplotypeCaller GVCF files into a single multi-sample GVCF. + """ + args = ["-R", reference, "-O", output_vcf] + for vcf in variant_gvcfs: + args.extend(["-V", vcf]) + + result = run_gatk_command("CombineGVCFs", args) + result["output_files"] = [output_vcf] + return result + +@mcp.tool() +def gatk_get_pileup_summaries( + input_bam: str, + variant_resource: str, + intervals: str, + output_table: str, +): + """ + Summarizes counts of reads that support reference, alternate, and other alleles for Mutect2. + """ + args = [ + "-I", input_bam, + "-V", variant_resource, + "-L", intervals, + "-O", output_table + ] + + result = run_gatk_command("GetPileupSummaries", args) + result["output_files"] = [output_table] + return result + +@mcp.tool() +def gatk_calculate_contamination( + input_table: str, + output_table: str, + matched_normal_table: Optional[str] = None, +): + """ + Calculate the fraction of reads coming from cross-sample contamination. + """ + args = [ + "-I", input_table, + "-O", output_table + ] + + if matched_normal_table: + args.extend(["-matched", matched_normal_table]) + + result = run_gatk_command("CalculateContamination", args) + result["output_files"] = [output_table] + return result + +@mcp.tool() +def gatk_filter_mutect_calls( + reference: str, + variant_vcf: str, + output_vcf: str, + contamination_table: Optional[str] = None, + obias_artifact_priors: Optional[str] = None, +): + """ + Filter somatic variants called by Mutect2. + """ + args = [ + "-R", reference, + "-V", variant_vcf, + "-O", output_vcf + ] + + if contamination_table: + args.extend(["--contamination-table", contamination_table]) + if obias_artifact_priors: + args.extend(["--orientation-bias-artifact-priors", obias_artifact_priors]) + + result = run_gatk_command("FilterMutectCalls", args) + result["output_files"] = [output_vcf] + return result + +@mcp.tool() +def gatk_sort_sam( + input_file: str, + output_file: str, + sort_order: str = "coordinate", + create_index: bool = True, +): + """ + Sorts a SAM or BAM file (Picard implementation). + """ + args = [ + "-I", input_file, + "-O", output_file, + "--SORT_ORDER", sort_order, + "--CREATE_INDEX", str(create_index).lower() + ] + + result = run_gatk_command("SortSam", args) + result["output_files"] = [output_file] + return result + +@mcp.tool() +def gatk_validate_sam_file( + input_file: str, + mode: str = "SUMMARY", + ignore_warnings: bool = False, +): + """ + Validates a SAM or BAM file (Picard implementation). + """ + args = [ + "-I", input_file, + "--MODE", mode + ] + if ignore_warnings: + args.append("--IGNORE_WARNINGS") + + result = run_gatk_command("ValidateSamFile", args) + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/gatk_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/gatk_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..99343f8feef82a234e3badaf023f7816634bf606 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/gatk_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gatk/app/gatk_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_gatk' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..59660b47d572419f9b4fa22bf7fb8eac6e19cfe6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gatk: + build: . + image: mcp-gatk:latest + container_name: mcp-gatk + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gatk + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e2cffbdc534c07ec12913fc119e1cfc224f78155 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gatk + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e0a2a38576c762c568604990f2ca9ba3864bb7a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gatk4 via conda (e.g., from bioconda) +RUN conda install -c bioconda gatk4 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gatk4_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gatk4_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gatk4_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/__pycache__/gatk4_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/__pycache__/gatk4_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8db767a9b794928e67cb94a34ce2c2d87b4b520 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/__pycache__/gatk4_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/__pycache__/gatk4_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/__pycache__/gatk4_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1285597d5209d89179536b7d1414412ab09f0008 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/__pycache__/gatk4_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/gatk4_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/gatk4_server.py new file mode 100644 index 0000000000000000000000000000000000000000..29ca87aa48207f52eeaf909c4cc42e46d9c70313 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/gatk4_server.py @@ -0,0 +1,380 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import os + +def _run_gatk_command(args: List[str]) -> dict: + """ + Internal helper to execute GATK commands and handle errors. + """ + try: + # Ensure gatk is in the path or use an environment variable + # In most bioconda environments, 'gatk' is the entry point + command = ["gatk"] + args + + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True + ) + + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + except FileNotFoundError: + return { + "command_executed": " ".join(args), + "stdout": "", + "stderr": "GATK executable 'gatk' not found in PATH.", + "error": "Executable not found", + "status": "error" + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_gatk4' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def gatk4_list_tools(): + """ + List all available tools in the GATK4 toolkit. + """ + return _run_gatk_command(["--list"]) + +@mcp.tool() +def gatk4_tool_help(tool_name: str): + """ + Get detailed help and parameter descriptions for a specific GATK tool. + + :param tool_name: The name of the GATK tool (e.g., 'HaplotypeCaller', 'Mutect2'). + """ + if not tool_name: + return {"error": "tool_name is required"} + return _run_gatk_command([tool_name, "--help"]) + +@mcp.tool() +def gatk4_haplotype_caller( + reference: str, + input_bam: str, + output_vcf: str, + intervals: Optional[List[str]] = None, + dbsnp: Optional[str] = None, + java_options: str = "-Xmx4G", + extra_args: Optional[List[str]] = None +): + """ + Call germline SNPs and indels via local re-assembly of haplotypes. + + :param reference: Path to the reference genome fasta file. + :param input_bam: Path to the input BAM/CRAM file. + :param output_vcf: Path to the output VCF file. + :param intervals: One or more genomic intervals (e.g., ['chr1', 'chr2:100-200']). + :param dbsnp: Path to a dbSNP VCF file. + :param java_options: JVM options (e.g., memory settings). + :param extra_args: Additional command line arguments for HaplotypeCaller. + """ + # Validation + ref_path = Path(reference) + if not ref_path.exists(): + return {"error": f"Reference file {reference} not found."} + + in_path = Path(input_bam) + if not in_path.exists(): + return {"error": f"Input BAM {input_bam} not found."} + + cmd_args = [] + if java_options: + cmd_args.extend(["--java-options", java_options]) + + cmd_args.extend(["HaplotypeCaller", "-R", reference, "-I", input_bam, "-O", output_vcf]) + + if intervals: + for interval in intervals: + cmd_args.extend(["-L", interval]) + + if dbsnp: + cmd_args.extend(["--dbsnp", dbsnp]) + + if extra_args: + cmd_args.extend(extra_args) + + return _run_gatk_command(cmd_args) + +@mcp.tool() +def gatk4_mutect2( + reference: str, + input_bam: str, + output_vcf: str, + tumor_sample_name: Optional[str] = None, + normal_bam: Optional[str] = None, + normal_sample_name: Optional[str] = None, + germline_resource: Optional[str] = None, + pon: Optional[str] = None, + intervals: Optional[List[str]] = None, + java_options: str = "-Xmx4G", + extra_args: Optional[List[str]] = None +): + """ + Call somatic SNPs and indels via local assembly of haplotypes. + + :param reference: Path to the reference genome fasta file. + :param input_bam: Path to the tumor BAM/CRAM file. + :param output_vcf: Path to the output VCF file. + :param tumor_sample_name: Name of the tumor sample. + :param normal_bam: Path to the normal BAM/CRAM file (for matched analysis). + :param normal_sample_name: Name of the normal sample. + :param germline_resource: Path to a germline resource VCF (e.g., gnomAD). + :param pon: Path to a Panel of Normals VCF. + :param intervals: Genomic intervals to process. + :param java_options: JVM options. + :param extra_args: Additional Mutect2 arguments. + """ + cmd_args = [] + if java_options: + cmd_args.extend(["--java-options", java_options]) + + cmd_args.extend(["Mutect2", "-R", reference, "-I", input_bam, "-O", output_vcf]) + + if tumor_sample_name: + cmd_args.extend(["-tumor", tumor_sample_name]) + if normal_bam: + cmd_args.extend(["-I", normal_bam]) + if normal_sample_name: + cmd_args.extend(["-normal", normal_sample_name]) + if germline_resource: + cmd_args.extend(["--germline-resource", germline_resource]) + if pon: + cmd_args.extend(["-pon", pon]) + if intervals: + for interval in intervals: + cmd_args.extend(["-L", interval]) + if extra_args: + cmd_args.extend(extra_args) + + return _run_gatk_command(cmd_args) + +@mcp.tool() +def gatk4_mark_duplicates( + input_bam: str, + output_bam: str, + metrics_file: str, + java_options: str = "-Xmx4G", + remove_duplicates: bool = False, + extra_args: Optional[List[str]] = None +): + """ + Identifies duplicate reads in a BAM or SAM file. + + :param input_bam: Path to the input BAM file. + :param output_bam: Path to the output BAM file. + :param metrics_file: Path to the file to write duplication metrics. + :param java_options: JVM options. + :param remove_duplicates: If true, remove duplicates instead of just marking them. + :param extra_args: Additional MarkDuplicates arguments. + """ + cmd_args = [] + if java_options: + cmd_args.extend(["--java-options", java_options]) + + cmd_args.extend(["MarkDuplicates", "-I", input_bam, "-O", output_bam, "-M", metrics_file]) + + if remove_duplicates: + cmd_args.append("--REMOVE_DUPLICATES=true") + else: + cmd_args.append("--REMOVE_DUPLICATES=false") + + if extra_args: + cmd_args.extend(extra_args) + + return _run_gatk_command(cmd_args) + +@mcp.tool() +def gatk4_base_recalibrator( + reference: str, + input_bam: str, + known_sites: List[str], + output_table: str, + intervals: Optional[List[str]] = None, + java_options: str = "-Xmx4G", + extra_args: Optional[List[str]] = None +): + """ + Generate a recalibration table for Base Quality Score Recalibration (BQSR). + + :param reference: Path to the reference genome fasta. + :param input_bam: Path to the input BAM file. + :param known_sites: List of paths to VCF files containing known polymorphic sites (e.g., dbSNP, Mills). + :param output_table: Path to the output recalibration report file. + :param intervals: Genomic intervals to process. + :param java_options: JVM options. + :param extra_args: Additional BaseRecalibrator arguments. + """ + cmd_args = [] + if java_options: + cmd_args.extend(["--java-options", java_options]) + + cmd_args.extend(["BaseRecalibrator", "-R", reference, "-I", input_bam, "-O", output_table]) + + for site in known_sites: + cmd_args.extend(["--known-sites", site]) + + if intervals: + for interval in intervals: + cmd_args.extend(["-L", interval]) + + if extra_args: + cmd_args.extend(extra_args) + + return _run_gatk_command(cmd_args) + +@mcp.tool() +def gatk4_apply_bqsr( + reference: str, + input_bam: str, + recal_table: str, + output_bam: str, + java_options: str = "-Xmx4G", + extra_args: Optional[List[str]] = None +): + """ + Apply a recalibration table to a BAM file (BQSR step 2). + + :param reference: Path to the reference genome fasta. + :param input_bam: Path to the input BAM file. + :param recal_table: Path to the recalibration table from BaseRecalibrator. + :param output_bam: Path to the output recalibrated BAM file. + :param java_options: JVM options. + :param extra_args: Additional ApplyBQSR arguments. + """ + cmd_args = [] + if java_options: + cmd_args.extend(["--java-options", java_options]) + + cmd_args.extend(["ApplyBQSR", "-R", reference, "-I", input_bam, "--bqsr-recal-file", recal_table, "-O", output_bam]) + + if extra_args: + cmd_args.extend(extra_args) + + return _run_gatk_command(cmd_args) + +@mcp.tool() +def gatk4_print_reads( + input_bam: str, + output_bam: str, + intervals: Optional[List[str]] = None, + java_options: str = "-Xmx4G", + extra_args: Optional[List[str]] = None +): + """ + Print reads from a BAM/SAM/CRAM file, optionally filtering by interval. + + :param input_bam: Path to the input BAM file. + :param output_bam: Path to the output BAM file. + :param intervals: Genomic intervals to include. + :param java_options: JVM options. + :param extra_args: Additional PrintReads arguments. + """ + cmd_args = [] + if java_options: + cmd_args.extend(["--java-options", java_options]) + + cmd_args.extend(["PrintReads", "-I", input_bam, "-O", output_bam]) + + if intervals: + for interval in intervals: + cmd_args.extend(["-L", interval]) + + if extra_args: + cmd_args.extend(extra_args) + + return _run_gatk_command(cmd_args) + +@mcp.tool() +def gatk4_run_spark_tool( + tool_name: str, + input_bam: str, + output_file: str, + spark_runner: str = "LOCAL", + spark_master: str = "local[*]", + java_options: str = "-Xmx4G", + extra_tool_args: Optional[List[str]] = None, + extra_spark_args: Optional[List[str]] = None +): + """ + Run a GATK Spark-enabled tool (e.g., PrintReadsSpark, HaplotypeCallerSpark). + + :param tool_name: Name of the Spark tool (must end in 'Spark'). + :param input_bam: Path to the input BAM file. + :param output_file: Path to the output file. + :param spark_runner: Spark runner type (LOCAL, SPARK, or DATAPROC). + :param spark_master: Spark master URL (e.g., 'local[4]' or 'yarn'). + :param java_options: JVM options. + :param extra_tool_args: Arguments passed to the GATK tool itself. + :param extra_spark_args: Arguments passed to Spark (after the -- separator). + """ + if not tool_name.endswith("Spark"): + return {"error": "Tool name must end with 'Spark' for this function."} + + cmd_args = [] + if java_options: + cmd_args.extend(["--java-options", java_options]) + + cmd_args.extend([tool_name, "-I", input_bam, "-O", output_file]) + + if extra_tool_args: + cmd_args.extend(extra_tool_args) + + # Spark specific separator + cmd_args.append("--") + + cmd_args.extend(["--spark-runner", spark_runner]) + if spark_master: + cmd_args.extend(["--spark-master", spark_master]) + + if extra_spark_args: + cmd_args.extend(extra_spark_args) + + return _run_gatk_command(cmd_args) + +@mcp.tool() +def gatk4_generic_tool_runner( + tool_name: str, + arguments: List[str], + java_options: str = "-Xmx4G", + gatk_config_file: Optional[str] = None +): + """ + A generic runner for any GATK4 tool not explicitly covered by other functions. + + :param tool_name: The name of the GATK tool to run. + :param arguments: A list of all command line arguments for the tool. + :param java_options: JVM options (e.g., '-Xmx4G'). + :param gatk_config_file: Path to a GATK configuration file. + """ + cmd_args = [] + if java_options: + cmd_args.extend(["--java-options", java_options]) + + if gatk_config_file: + cmd_args.extend(["--gatk-config-file", gatk_config_file]) + + cmd_args.append(tool_name) + cmd_args.extend(arguments) + + return _run_gatk_command(cmd_args) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/gatk4_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/gatk4_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ca9f973b56333518fc418e3f5d35f5069e8077b3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/gatk4_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gatk4/app/gatk4_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_gatk4' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bdede95a6672c9af18c55749782c23a9d623b5cc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gatk4: + build: . + image: mcp-gatk4:latest + container_name: mcp-gatk4 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gatk4 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9ff69ad53a7ec37fdbf212a6e447d116ce1356de --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gatk4 + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..645610c98d6e90ef28cfd2502d1cbffb49f64d27 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gneiss via conda (e.g., from bioconda) +RUN conda install -c bioconda gneiss -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gneiss_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gneiss_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gneiss_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/__pycache__/gneiss_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/__pycache__/gneiss_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c521c0e80d38c14e91dd70a3dd531b135ab1a1a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/__pycache__/gneiss_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/gneiss_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/gneiss_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0c2130595e6aa780044d1b54361f57cf016f0e78 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/gneiss_server.py @@ -0,0 +1,335 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# It is assumed that 'mcp' is a pre-defined decorator. +# For standalone testing, you could use a mock decorator: +# +# class mcp: +# @staticmethod +# def tool(): +# def decorator(func): +# return func +# return decorator + +logging.basicConfig(level=logging.INFO) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_gneiss' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def correlation_clustering( + in_biom: Path, + output_tree: Path, + correlation_method: str = 'spearman', + clustering_method: str = 'ward' +) -> dict: + """ + Performs hierarchical clustering on features using their correlation. + + This is useful for creating a hierarchy of features based on their co-occurrence + patterns across samples. + """ + if not in_biom.exists(): + raise FileNotFoundError(f"Input biom table not found: {in_biom}") + + # Ensure output directory exists + output_tree.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "correlation-clustering", + "--in-biom", str(in_biom), + "--output-tree", str(output_tree), + "--correlation-method", correlation_method, + "--clustering-method", clustering_method + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_tree)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss correlation-clustering failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def dendrogram_heatmap( + in_biom: Path, + in_tree: Path, + in_meta: Path, + category: str, + output_viz: Path, + vmin: Optional[float] = None, + vmax: Optional[float] = None, + cmap: str = 'YlGnBu' +) -> dict: + """ + Builds a heatmap visualization of a biom table, ordered by a dendrogram. + + This tool is useful for visualizing the relationship between feature balances + and sample metadata categories. + """ + for input_file in [in_biom, in_tree, in_meta]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if not category: + raise ValueError("Metadata category must be a non-empty string.") + + # Ensure output directory exists + output_viz.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "dendrogram-heatmap", + "--in-biom", str(in_biom), + "--in-tree", str(in_tree), + "--in-meta", str(in_meta), + "--category", category, + "--output-viz", str(output_viz), + "--cmap", cmap + ] + + if vmin is not None: + cmd.extend(["--vmin", str(vmin)]) + if vmax is not None: + cmd.extend(["--vmax", str(vmax)]) + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_viz)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss dendrogram-heatmap failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def ilr_hierarchical( + in_biom: Path, + in_tree: Path, + output_biom: Path +) -> dict: + """ + Performs isometric log-ratio (ILR) transformation on a table using a hierarchical tree. + + This transforms compositional data into a real-valued space of balances, + which is suitable for standard statistical analyses. + """ + for input_file in [in_biom, in_tree]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Ensure output directory exists + output_biom.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "ilr-hierarchical", + "--in-biom", str(in_biom), + "--in-tree", str(in_tree), + "--output-biom", str(output_biom) + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_biom)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss ilr-hierarchical failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def ilr_phylogenetic( + in_biom: Path, + in_tree: Path, + output_biom: Path +) -> dict: + """ + Performs isometric log-ratio (ILR) transformation on a table using a phylogenetic tree. + + This is similar to ilr-hierarchical but specifically uses a phylogenetic tree + to define the balances, incorporating evolutionary relationships. + """ + for input_file in [in_biom, in_tree]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Ensure output directory exists + output_biom.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "ilr-phylogenetic", + "--in-biom", str(in_biom), + "--in-tree", str(in_tree), + "--output-biom", str(output_biom) + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_biom)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss ilr-phylogenetic failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def lme_regression( + in_biom: Path, + in_meta: Path, + formula: str, + groups: str, + output_dir: Path +) -> dict: + """ + Performs Linear Mixed Effects (LME) regression on balances. + + This models the relationship between balances and metadata variables while + accounting for random effects, such as repeated measures from subjects. + """ + for input_file in [in_biom, in_meta]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if not formula: + raise ValueError("Formula must be a non-empty string.") + if not groups: + raise ValueError("Groups must be a non-empty string.") + + # Ensure output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "lme-regression", + "--in-biom", str(in_biom), + "--in-meta", str(in_meta), + "--formula", formula, + "--groups", groups, + "--output-dir", str(output_dir) + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # Gneiss regression outputs multiple files, so we return the directory + output_files = [str(p) for p in output_dir.glob('*')] + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss lme-regression failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def ols_regression( + in_biom: Path, + in_meta: Path, + formula: str, + output_dir: Path +) -> dict: + """ + Performs Ordinary Least Squares (OLS) regression on balances. + + This models the linear relationship between balances (response variables) + and metadata variables (predictors). + """ + for input_file in [in_biom, in_meta]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if not formula: + raise ValueError("Formula must be a non-empty string.") + + # Ensure output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "ols-regression", + "--in-biom", str(in_biom), + "--in-meta", str(in_meta), + "--formula", formula, + "--output-dir", str(output_dir) + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # Gneiss regression outputs multiple files, so we return the directory + output_files = [str(p) for p in output_dir.glob('*')] + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss ols-regression failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/gneiss_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/gneiss_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..879718bc6ab4b36f49d6db85bd936ec6661d8d9b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/gneiss_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/gneiss_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_gneiss' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8188b23a6e770bcf257b16fd7c0ac7d7841a2500 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gneiss: + build: . + image: mcp-gneiss:latest + container_name: mcp-gneiss + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gneiss + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61580b9529e067472a95fde20dfcd5e18fbe7fff --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gneiss + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gneiss/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..654ab93c8fe816b5153cf4d183021d0447c40e95 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install goleft via conda (e.g., from bioconda) +RUN conda install -c bioconda goleft -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/goleft_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/goleft_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/goleft_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/__pycache__/goleft_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/__pycache__/goleft_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00bbfc9558bd285a45e8f7b9a5af3c38fc02bcc9 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/__pycache__/goleft_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/goleft_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/goleft_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a64b8fe79983ac513f7e73fd368007612b1666 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/goleft_server.py @@ -0,0 +1,435 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# NOTE: The @mcp.tool decorator is a placeholder. +# In a real MCP environment, it would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def goleft_covstats( + bams: List[Path], + denominator: str = "target-size", + n_reads: int = 25000000, + procs: int = 4, + reference: Optional[Path] = None, + target_bed: Optional[Path] = None, +): + """ + Estimate coverage and insert-size statistics on BAM/CRAM files by sampling. + + Args: + bams: List of input BAM/CRAM files. + denominator: Calculate coverage as reads / denominator. Must be 'target-size' or 'genome-size'. + n_reads: Number of reads to sample from each BAM. + procs: Number of processors to use. + reference: Optional reference FASTA for CRAM files. + target_bed: Optional BED file of target regions. + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + if denominator not in ["target-size", "genome-size"]: + raise ValueError("Denominator must be one of 'target-size' or 'genome-size'.") + if n_reads <= 0: + raise ValueError("n_reads must be a positive integer.") + if procs <= 0: + raise ValueError("procs must be a positive integer.") + if reference and not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + if target_bed and not target_bed.is_file(): + raise FileNotFoundError(f"Target BED file not found: {target_bed}") + + cmd = [ + "goleft", "covstats", + "--denominator", denominator, + "--nreads", str(n_reads), + "--procs", str(procs), + ] + + if reference: + cmd.extend(["--reference", str(reference)]) + if target_bed: + cmd.extend(["--targetbed", str(target_bed)]) + + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft covstats failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_depth( + bams: List[Path], + fai: Path, + output_dir: Path, + bed: Optional[Path] = None, + gaps: int = 2000, + procs: int = 4, + map_quality: int = 10, + base_quality: int = 10, + reference: Optional[Path] = None, + window_size: int = 5000, + min_cov: int = 1, + s_flags: int = 1796, + f_flags: int = 0, +): + """ + Parallelize calls to samtools depth in user-defined windows. + + Args: + bams: List of input BAM/CRAM files. + fai: FAI file of the reference genome. + output_dir: Directory to write depth files. + bed: Optional BED file of regions to process. + gaps: Number of bases to pad between windows for discordant pairs. + procs: Number of processors to use. + map_quality: Only count reads with mapping quality of at least this value. + base_quality: Only count bases with base quality of at least this value. + reference: Optional reference FASTA for CRAM files. + window_size: Window size for coverage depth reporting. + min_cov: Only report windows with coverage at least this value. + s_flags: Samtools flags to skip reads (e.g., 1796 for QCFAIL, DUP, SECONDARY, SUPPLEMENTARY). + f_flags: Samtools flags to filter reads (e.g., 2 to count only proper pairs). + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + if not fai.is_file(): + raise FileNotFoundError(f"FAI file not found: {fai}") + if bed and not bed.is_file(): + raise FileNotFoundError(f"BED file not found: {bed}") + if reference and not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "goleft", "depth", + "--fai", str(fai), + "--dir", str(output_dir), + "--gaps", str(gaps), + "--procs", str(procs), + "-q", str(map_quality), + "-Q", str(base_quality), + "--windowsize", str(window_size), + "--mincov", str(min_cov), + "--sflags", str(s_flags), + "--fflags", str(f_flags), + ] + + if bed: + cmd.extend(["--bed", str(bed)]) + if reference: + cmd.extend(["--reference", str(reference)]) + + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [output_dir / f"{bam.stem}.depth.bed.gz" for bam in bams] + final_output_files = [str(f) for f in output_files if f.exists()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft depth failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_depthwed( + depth_files: List[Path], + bed: Path, + prefix: str, + output_dir: Optional[Path] = None, +): + """ + Matricize output from 'goleft depth' to n-sites * n-samples. + + Args: + depth_files: List of depth files generated by 'goleft depth'. + bed: BED file of regions used to create the depth files. + prefix: Prefix for output files (e.g., 'my_cohort'). + output_dir: Directory to write output files. Defaults to a temporary directory. + """ + # Input validation + if not depth_files: + raise ValueError("At least one depth file must be provided.") + for df in depth_files: + if not df.is_file(): + raise FileNotFoundError(f"Input depth file not found: {df}") + if not bed.is_file(): + raise FileNotFoundError(f"BED file not found: {bed}") + if not prefix.strip(): + raise ValueError("Prefix cannot be empty.") + + with tempfile.TemporaryDirectory() as temp_dir: + work_dir = output_dir or Path(temp_dir) + work_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "goleft", "depthwed", + "--bed", str(bed), + "--prefix", prefix, + ] + cmd.extend([str(p) for p in depth_files]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=work_dir, + ) + + expected_files = [ + work_dir / f"{prefix}.depth.tsv", + work_dir / f"{prefix}.sites.bed.gz", + work_dir / f"{prefix}.samples.tsv" + ] + output_files = [str(f) for f in expected_files if f.exists()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft depthwed failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_indexcov( + bams: List[Path], + fai: Path, + output_dir: Path, + procs: int = 4, + sex_file: Optional[Path] = None, + window_size: str = "16K", +): + """ + Quick coverage estimate using only the BAM/CRAM index. + + Args: + bams: List of input BAM/CRAM files (and their .bai/.crai indexes). + fai: FAI file of the reference genome. + output_dir: Directory to write output files (HTML report, etc.). + procs: Number of processors to use. + sex_file: Optional file containing sample\tsex mapping. + window_size: Window size for coverage depth reporting (e.g., '16K', '1M'). + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + index_bai = bam.with_suffix(bam.suffix + ".bai") + index_crai = bam.with_suffix(".crai") + if not (index_bai.exists() or index_crai.exists()): + raise FileNotFoundError(f"Index file (.bai or .crai) not found for {bam}") + if not fai.is_file(): + raise FileNotFoundError(f"FAI file not found: {fai}") + if sex_file and not sex_file.is_file(): + raise FileNotFoundError(f"Sex file not found: {sex_file}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "goleft", "indexcov", + "--fai", str(fai), + "--dir", str(output_dir), + "--procs", str(procs), + "--windowsize", window_size, + ] + + if sex_file: + cmd.extend(["--sex", str(sex_file)]) + + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + html_report = output_dir / "indexcov.html" + output_files = [str(p) for p in output_dir.glob('**/*') if p.is_file()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + "main_report": str(html_report) if html_report.exists() else None + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft indexcov failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_indexsplit( + bams: List[Path], + fai: Path, + n_chunks: int = 100, + output_file: Optional[Path] = None, + procs: int = 4, +): + """ + Generate regions of even data across a cohort for parallelization. + + Args: + bams: List of input BAM/CRAM files. + fai: FAI file of the reference genome. + n_chunks: Number of chunks to create. + output_file: File to write regions to. If None, writes to stdout. + procs: Number of processors to use. + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + if not fai.is_file(): + raise FileNotFoundError(f"FAI file not found: {fai}") + if n_chunks <= 0: + raise ValueError("n_chunks must be a positive integer.") + if procs <= 0: + raise ValueError("procs must be a positive integer.") + + cmd = [ + "goleft", "indexsplit", + "--fai", str(fai), + "-N", str(n_chunks), + "--procs", str(procs), + ] + + output_files_list = [] + if output_file: + cmd.extend(["--out", str(output_file)]) + output_files_list.append(str(output_file)) + + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft indexsplit failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_samplename( + bams: List[Path], +): + """ + Report samplename(s) from a BAM/CRAM file's SM tag in the header. + + Args: + bams: List of input BAM/CRAM files. + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + + cmd = ["goleft", "samplename"] + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft samplename failed with exit code {e.returncode}", + "output_files": [], + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/goleft_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/goleft_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bd6e062c19067fff91869e360d26f2c5411f9ba3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/goleft_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/goleft_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_goleft' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..be5348e342deeffe41b34a8051fd7f83e9ac76d3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-goleft: + build: . + image: mcp-goleft:latest + container_name: mcp-goleft + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=goleft + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fc842e11ccefeccf5dc031cbffa31a8e6486189e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - goleft + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_goleft/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6dddfd57f06bcbce0153d4eafc7cf08b91ad7817 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gromacs via conda (e.g., from bioconda) +RUN conda install -c bioconda gromacs -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gromacs_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gromacs_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gromacs_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/__pycache__/gromacs_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/__pycache__/gromacs_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea3305f108357571bf19aff868e414be8fc8ef6e Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/__pycache__/gromacs_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/gromacs_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/gromacs_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2b697c405df96ee73aea3d259529313e6a06157e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/gromacs_server.py @@ -0,0 +1,511 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_gromacs' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def gmx_pdb2gmx( + f: str, + o: str = "processed.gro", + p: str = "topol.top", + i: str = "posre.itp", + ff: str = "oplsaa", + water: str = "spce", + ignh: bool = False, + missing: bool = False, +): + """ + Converts PDB files to GROMACS coordinate and topology files. + + Args: + f: Input structure file (.pdb, .gro, etc.) + o: Output structure file + p: Output topology file + i: Output position restraint file + ff: Force field to use (e.g., 'oplsaa', 'amber99sb-ildn') + water: Water model (e.g., 'spce', 'tip3p') + ignh: Ignore hydrogen atoms in the PDB file + missing: Allow missing atoms + """ + input_path = Path(f) + if not input_path.exists(): + return {"error": f"Input file {f} not found"} + + cmd = [ + "gmx", "pdb2gmx", + "-f", str(input_path), + "-o", o, + "-p", p, + "-i", i, + "-ff", ff, + "-water", water + ] + + if ignh: + cmd.append("-ignh") + if missing: + cmd.append("-missing") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o, p, i] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_editconf( + f: str, + o: str = "box.gro", + c: bool = True, + d: float = 1.0, + bt: str = "cubic", + box: Optional[str] = None, + princ: bool = False, +): + """ + Edits the simulation box and centers the system. + + Args: + f: Input structure file + o: Output structure file + c: Center molecule in box + d: Distance between the solute and the box edge (nm) + bt: Box type: 'cubic', 'triclinic', 'magical', 'octahedron', 'dodecahedron' + box: Box vector lengths (x, y, z) as a string + princ: Orient molecule along principal axes + """ + input_path = Path(f) + if not input_path.exists(): + return {"error": f"Input file {f} not found"} + + cmd = ["gmx", "editconf", "-f", str(input_path), "-o", o, "-bt", bt] + + if c: + cmd.append("-c") + if d > 0: + cmd.extend(["-d", str(d)]) + if box: + cmd.extend(["-box", box]) + if princ: + cmd.append("-princ") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_solvate( + cp: str, + cs: str = "spc216.gro", + p: str = "topol.top", + o: str = "solvated.gro", + maxsol: int = 0, +): + """ + Solvates a system by adding water molecules. + + Args: + cp: Input structure file (solute) + cs: Solvent structure file + p: Topology file (will be updated) + o: Output structure file + maxsol: Maximum number of solvent molecules to add (0 for all) + """ + cp_path = Path(cp) + p_path = Path(p) + if not cp_path.exists(): + return {"error": f"Solute file {cp} not found"} + if not p_path.exists(): + return {"error": f"Topology file {p} not found"} + + cmd = [ + "gmx", "solvate", + "-cp", str(cp_path), + "-cs", cs, + "-p", str(p_path), + "-o", o + ] + + if maxsol > 0: + cmd.extend(["-maxsol", str(maxsol)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o, p] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_grompp( + f: str, + c: str, + p: str, + o: str = "topol.tpr", + r: Optional[str] = None, + n: Optional[str] = None, + maxwarn: int = 0, +): + """ + The GROMACS preprocessor: generates a run input file (.tpr). + + Args: + f: Input MD parameter file (.mdp) + c: Input structure file (.gro) + p: Input topology file (.top) + o: Output run input file (.tpr) + r: Structure file for restraints + n: Index file (.ndx) + maxwarn: Number of allowed warnings + """ + f_path = Path(f) + c_path = Path(c) + p_path = Path(p) + + for path in [f_path, c_path, p_path]: + if not path.exists(): + return {"error": f"Required file {path} not found"} + + cmd = [ + "gmx", "grompp", + "-f", str(f_path), + "-c", str(c_path), + "-p", str(p_path), + "-o", o, + "-maxwarn", str(maxwarn) + ] + + if r: + cmd.extend(["-r", r]) + if n: + cmd.extend(["-n", n]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_genion( + s: str, + p: str, + o: str = "solvated_ions.gro", + pname: str = "NA", + nname: str = "CL", + neutral: bool = True, + conc: float = 0.0, + selection: str = "SOL", +): + """ + Adds ions to a solvated system to neutralize it or reach a concentration. + + Args: + s: Input run input file (.tpr) + p: Topology file (will be updated) + o: Output structure file + pname: Name of the positive ion + nname: Name of the negative ion + neutral: Add ions to neutralize the system + conc: Specify salt concentration (mol/liter) + selection: Group to replace with ions (usually 'SOL' or '13') + """ + s_path = Path(s) + p_path = Path(p) + if not s_path.exists(): + return {"error": f"TPR file {s} not found"} + + cmd = [ + "gmx", "genion", + "-s", str(s_path), + "-p", str(p_path), + "-o", o, + "-pname", pname, + "-nname", nname + ] + + if neutral: + cmd.append("-neutral") + if conc > 0: + cmd.extend(["-conc", str(conc)]) + + try: + # genion requires interactive selection of the solvent group + result = subprocess.run( + cmd, + input=selection, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o, p] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_mdrun( + s: str = "topol.tpr", + deffnm: str = "md", + v: bool = True, + nt: int = 0, + nb: str = "auto", + pme: str = "auto", + gpu_id: Optional[str] = None, +): + """ + Executes the molecular dynamics simulation. + + Args: + s: Input run input file (.tpr) + deffnm: Default filename for all outputs + v: Verbose output + nt: Number of threads to use (0 for auto) + nb: Calculate non-bonded interactions on: 'auto', 'cpu', 'gpu' + pme: Calculate PME on: 'auto', 'cpu', 'gpu' + gpu_id: List of GPU device IDs to use + """ + s_path = Path(s) + if not s_path.exists(): + return {"error": f"TPR file {s} not found"} + + cmd = [ + "gmx", "mdrun", + "-s", str(s_path), + "-deffnm", deffnm, + "-nb", nb, + "-pme", pme + ] + + if v: + cmd.append("-v") + if nt > 0: + cmd.extend(["-nt", str(nt)]) + if gpu_id: + cmd.extend(["-gpu_id", gpu_id]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [f"{deffnm}.log", f"{deffnm}.xtc", f"{deffnm}.edr", f"{deffnm}.gro"] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_energy( + f: str = "ener.edr", + o: str = "energy.xvg", + selection: str = "Potential", +): + """ + Extracts energy terms from an energy file (.edr). + + Args: + f: Input energy file + o: Output graph file (.xvg) + selection: Energy term to extract (e.g., 'Potential', 'Temperature', 'Pressure') + """ + f_path = Path(f) + if not f_path.exists(): + return {"error": f"Energy file {f} not found"} + + cmd = ["gmx", "energy", "-f", str(f_path), "-o", o] + + try: + # selection is piped to stdin (e.g., "Potential 0" to select Potential and end) + input_str = f"{selection}\n0\n" + result = subprocess.run( + cmd, + input=input_str, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_rms( + s: str, + f: str, + o: str = "rms.xvg", + selection: str = "Backbone Backbone", +): + """ + Calculates Root Mean Square Deviation (RMSD). + + Args: + s: Reference structure file (.tpr, .gro) + f: Trajectory file (.xtc, .trr) + o: Output graph file (.xvg) + selection: Groups for fitting and calculation (e.g., 'Backbone Backbone') + """ + s_path = Path(s) + f_path = Path(f) + if not s_path.exists() or not f_path.exists(): + return {"error": "Input files not found"} + + cmd = ["gmx", "rms", "-s", str(s_path), "-f", str(f_path), "-o", o] + + try: + # selection usually requires two groups: one for fitting, one for calculation + result = subprocess.run( + cmd, + input=selection, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_trjconv( + f: str, + s: str, + o: str = "output.xtc", + pbc: str = "mol", + center: bool = True, + ur: str = "compact", + selection: str = "System", +): + """ + Converts and manipulates trajectory files (PBC treatment, centering). + + Args: + f: Input trajectory file + s: Input structure/tpr file + o: Output trajectory/structure file + pbc: PBC treatment: 'none', 'mol', 'res', 'atom', 'nojump', 'cluster' + center: Center the system + ur: Unit cell representation: 'rect', 'tric', 'compact' + selection: Group to write to output + """ + f_path = Path(f) + s_path = Path(s) + if not f_path.exists() or not s_path.exists(): + return {"error": "Input files not found"} + + cmd = [ + "gmx", "trjconv", + "-f", str(f_path), + "-s", str(s_path), + "-o", o, + "-pbc", pbc, + "-ur", ur + ] + + if center: + cmd.append("-center") + + try: + # trjconv often needs selection for centering and for output + input_str = f"{selection}\n{selection}\n" if center else f"{selection}\n" + result = subprocess.run( + cmd, + input=input_str, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/gromacs_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/gromacs_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c65fc1afa09348e1cf9caec8d7f4485e0cdab1b1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/gromacs_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/gromacs_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_gromacs' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c75b9cbb5170acf7f24af3b2a63598fc518eddce --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gromacs: + build: . + image: mcp-gromacs:latest + container_name: mcp-gromacs + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gromacs + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..12eba8048e391284b3123e62844fe8b04ae88e91 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gromacs + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gromacs/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2edda10ca7d458317d95614e371bbcc8d4c139b1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install harpy via conda (e.g., from bioconda) +RUN conda install -c bioconda harpy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/harpy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/harpy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/harpy_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/__pycache__/harpy_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/__pycache__/harpy_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9d1a60c6a315f630579c5ec9e3da74244a22967 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/__pycache__/harpy_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/harpy_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/harpy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5852c6584072056c08d0ffea0e03694795ac363c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/harpy_server.py @@ -0,0 +1,861 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP-compliant tool definitions for harpy + +# --- Data Processing Subcommands --- + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_harpy' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def align( + reads_r1: Path, + reads_r2: Path, + reference: Path, + sample: str, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Aligns sample sequences to a reference genome assembly using Harpy. + + This function wraps the 'harpy align' command. It takes paired-end reads, + a reference genome, and a sample name to produce alignment files. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "align", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--reference", str(reference), + "--sample", sample, + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Assuming the primary output is a BAM file named after the sample + output_bam = output_dir / f"{sample}.bam" + output_files = [str(output_bam)] if output_bam.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy align command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def assemble( + reads_r1: Path, + reads_r2: Path, + sample: str, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Creates a genome assembly from linked-reads using Harpy. + + This function wraps the 'harpy assemble' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "assemble", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--sample", sample, + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Assuming the primary output is a FASTA file + output_fasta = output_dir / f"{sample}_assembly.fasta" + output_files = [str(output_fasta)] if output_fasta.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy assemble command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def deconvolve( + bam: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Resolves barcode sharing in unrelated molecules from a BAM file. + + This function wraps the 'harpy deconvolve' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "deconvolve", + "--bam", str(bam), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Assuming output is a new BAM file + output_bam = output_dir / f"{bam.stem}.deconvolved.bam" + output_files = [str(output_bam)] if output_bam.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy deconvolve command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def demultiplex( + reads_r1: Path, + reads_r2: Path, + barcodes: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Demultiplexes haplotagged FASTQ files using Harpy. + + This function wraps the 'harpy demultiplex' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if not barcodes.is_file(): + raise FileNotFoundError(f"Barcodes file not found: {barcodes}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "demultiplex", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--barcodes", str(barcodes), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Output is likely a set of demultiplexed FASTQ files + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_dir.glob("*.fastq.gz")], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy demultiplex command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def impute( + vcf: Path, + bam: Path, + reference: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Imputes variant genotypes from alignments using Harpy. + + This function wraps the 'harpy impute' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not vcf.is_file(): + raise FileNotFoundError(f"Input VCF file not found: {vcf}") + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "impute", + "--vcf", str(vcf), + "--bam", str(bam), + "--reference", str(reference), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_vcf = output_dir / f"{vcf.stem}.imputed.vcf.gz" + output_files = [str(output_vcf)] if output_vcf.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy impute command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def metassembly( + reads_r1: Path, + reads_r2: Path, + sample: str, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Creates a metagenome assembly from linked-reads using Harpy. + + This function wraps the 'harpy metassembly' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "metassembly", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--sample", sample, + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_fasta = output_dir / f"{sample}_metassembly.fasta" + output_files = [str(output_fasta)] if output_fasta.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy metassembly command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def phase( + vcf: Path, + bam: Path, + reference: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Phases SNPs into haplotypes using Harpy. + + This function wraps the 'harpy phase' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not vcf.is_file(): + raise FileNotFoundError(f"Input VCF file not found: {vcf}") + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "phase", + "--vcf", str(vcf), + "--bam", str(bam), + "--reference", str(reference), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_vcf = output_dir / f"{vcf.stem}.phased.vcf.gz" + output_files = [str(output_vcf)] if output_vcf.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy phase command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def qc( + reads_r1: Path, + reads_r2: Path, + sample: str, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Performs adapter removal, quality filtering, etc., on FASTQ files. + + This function wraps the 'harpy qc' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "qc", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--sample", sample, + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Assuming output is a pair of trimmed FASTQ files + out_r1 = output_dir / f"{sample}_R1.trimmed.fastq.gz" + out_r2 = output_dir / f"{sample}_R2.trimmed.fastq.gz" + output_files = [] + if out_r1.exists(): + output_files.append(str(out_r1)) + if out_r2.exists(): + output_files.append(str(out_r2)) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy qc command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def simulate( + reference: Path, + output_dir: Path, + seed: Optional[int] = None, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Simulates genomic variants or linked reads using Harpy. + + This function wraps the 'harpy simulate' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "simulate", + "--reference", str(reference), + "--output", str(output_dir), + ] + if seed is not None: + cmd.extend(["--seed", str(seed)]) + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_dir.iterdir()], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy simulate command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def snp( + bam: Path, + reference: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Calls SNPs and small indels from alignments using Harpy. + + This function wraps the 'harpy snp' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "snp", + "--bam", str(bam), + "--reference", str(reference), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_vcf = output_dir / f"{bam.stem}.vcf.gz" + output_files = [str(output_vcf)] if output_vcf.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy snp command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def sv( + bam: Path, + reference: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Calls large structural variants (inversions, deletions, duplications). + + This function wraps the 'harpy sv' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "sv", + "--bam", str(bam), + "--reference", str(reference), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_vcf = output_dir / f"{bam.stem}.sv.vcf.gz" + output_files = [str(output_vcf)] if output_vcf.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy sv command failed", + "return_code": e.returncode, + } + +# --- Other and Troubleshooting Subcommands --- + +@mcp.tool() +def template( + workflow: str, + output_dir: Path, + hpc_profile: Optional[str] = None, +) -> dict: + """ + Creates template files and HPC configs for Harpy workflows. + + This function wraps the 'harpy template' command. + """ + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = ["harpy", "template", workflow, "--output", str(output_dir)] + if hpc_profile: + cmd.extend(["--hpc-profile", hpc_profile]) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_dir.iterdir()], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy template command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def deps(force: bool = False) -> dict: + """ + Locally installs workflow dependencies for Harpy. + + This function wraps the 'harpy deps' command. + """ + cmd = ["harpy", "deps"] + if force: + cmd.append("--force") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy deps command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def diagnose(workflow_dir: Path) -> dict: + """ + Attempts to resolve errors in a failed Harpy workflow. + + This function wraps the 'harpy diagnose' command. + """ + if not workflow_dir.is_dir(): + raise NotADirectoryError(f"Workflow directory not found: {workflow_dir}") + + cmd = ["harpy", "diagnose", str(workflow_dir)] + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy diagnose command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def resume(workflow_dir: Path) -> dict: + """ + Continues an incomplete Harpy workflow. + + This function wraps the 'harpy resume' command. + """ + if not workflow_dir.is_dir(): + raise NotADirectoryError(f"Workflow directory not found: {workflow_dir}") + + cmd = ["harpy", "resume", str(workflow_dir)] + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy resume command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def validate(input_file: Path, file_type: str) -> dict: + """ + Runs various format checks for FASTQ, BAM, and other files. + + This function wraps the 'harpy validate' command. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + valid_types = ["fastq", "bam", "vcf"] + if file_type.lower() not in valid_types: + raise ValueError(f"file_type must be one of {valid_types}") + + cmd = ["harpy", "validate", file_type, str(input_file)] + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy validate command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def view(workflow: str, output_file: Optional[Path] = None) -> dict: + """ + Views a workflow's components, such as its DAG. + + This function wraps the 'harpy view' command. + """ + cmd = ["harpy", "view", workflow] + if output_file: + cmd.extend(["--output", str(output_file)]) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_files = [str(output_file)] if output_file and output_file.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy view command failed", + "return_code": e.returncode, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/harpy_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/harpy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6779332ce7310c34f7f575f71735667a2dde116c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/harpy_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/harpy_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_harpy' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ffd8498021f6e49151afb302a037f6f8aa7de3e7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-harpy: + build: . + image: mcp-harpy:latest + container_name: mcp-harpy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=harpy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..297e3c0ea533df263cfa11e50be4ef5ab3382e80 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - harpy + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_harpy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..83409c9f7a291dca9975cd20229c0bdb2c16adc7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install hicexplorer via conda (e.g., from bioconda) +RUN conda install -c bioconda hicexplorer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/hicexplorer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/hicexplorer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/hicexplorer_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/__pycache__/hicexplorer_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/__pycache__/hicexplorer_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67bd748f254bdbe4a410c497a30bae60ecfd1d72 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/__pycache__/hicexplorer_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/hicexplorer_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/hicexplorer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fc6a415ef7b272f607b4a564506d1393c47e4f10 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/hicexplorer_server.py @@ -0,0 +1,691 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() - This decorator is commented out as per the instructions. +# In a real MCP environment, it would be uncommented. + +def hic_build_matrix( + sam_files: List[Path], + out_file_name: Path, + bin_size: int = 10000, + threads: int = 4, + restriction_sequence: Optional[str] = None, + restriction_file: Optional[Path] = None, + dangling_ends: Optional[str] = None, + min_mapping_quality: int = 10, + keep_self_circles: bool = False, + keep_self_ligations: bool = False, + keep_duplicates: bool = False, + min_sequence_length: int = 25, + max_sequence_length: int = 0, + min_insert_size: int = 100, + max_insert_size: int = 0, + min_coverage: int = 0, + max_coverage: int = 1000, + stats_file: Optional[Path] = None, + qc_folder: Optional[Path] = None, + chromosome_sizes: Optional[Path] = None, + region: Optional[str] = None, + matrix_format: str = "cool", + tmp_dir: Optional[Path] = None, + enforce_sorted: bool = False, + short_read_names: bool = False, + center_read: bool = False, + quiet: bool = False, +) -> dict: + """ + Builds a Hi-C contact matrix from aligned sequencing reads. + + This tool processes SAM/BAM files from Hi-C experiments to create a binned contact matrix. + It includes steps for filtering reads based on quality, length, and ligation artifacts. + """ + # Input validation + if not all(f.is_file() for f in sam_files): + raise FileNotFoundError("One or more input SAM/BAM files not found.") + if restriction_file and not restriction_file.is_file(): + raise FileNotFoundError(f"Restriction file not found: {restriction_file}") + if chromosome_sizes and not chromosome_sizes.is_file(): + raise FileNotFoundError(f"Chromosome sizes file not found: {chromosome_sizes}") + if bin_size <= 0: + raise ValueError("bin_size must be a positive integer.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if matrix_format not in ["cool", "h5"]: + raise ValueError("matrix_format must be either 'cool' or 'h5'.") + + cmd = [ + "hicBuildMatrix", + "--samFiles", *[str(f) for f in sam_files], + "--outFileName", str(out_file_name), + "--binSize", str(bin_size), + "--threads", str(threads), + "--minMappingQuality", str(min_mapping_quality), + "--minSequenceLength", str(min_sequence_length), + "--minInsertSize", str(min_insert_size), + "--minCoverage", str(min_coverage), + "--maxCoverage", str(max_coverage), + ] + + if restriction_sequence: + cmd.extend(["--restrictionSequence", restriction_sequence]) + if restriction_file: + cmd.extend(["--restrictionFile", str(restriction_file)]) + if dangling_ends: + cmd.extend(["--danglingEnds", dangling_ends]) + if keep_self_circles: + cmd.append("--keepSelfCircles") + if keep_self_ligations: + cmd.append("--keepSelfLigations") + if keep_duplicates: + cmd.append("--keepDuplicates") + if max_sequence_length > 0: + cmd.extend(["--maxSequenceLength", str(max_sequence_length)]) + if max_insert_size > 0: + cmd.extend(["--maxInsertSize", str(max_insert_size)]) + if stats_file: + cmd.extend(["--statsFile", str(stats_file)]) + if qc_folder: + cmd.extend(["--qcFolder", str(qc_folder)]) + if chromosome_sizes: + cmd.extend(["--chromosomeSizes", str(chromosome_sizes)]) + if region: + cmd.extend(["--region", region]) + if matrix_format: + cmd.extend(["--matrixFormat", matrix_format]) + if tmp_dir: + cmd.extend(["--tmpDir", str(tmp_dir)]) + if enforce_sorted: + cmd.append("--enforceSorted") + if short_read_names: + cmd.append("--shortReadNames") + if center_read: + cmd.append("--center_read") + if quiet: + cmd.append("--quiet") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(out_file_name)] + if stats_file: + output_files.append(str(stats_file)) + if qc_folder: + # This is a directory, so we might list its contents or just return the path + output_files.append(str(qc_folder)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicBuildMatrix failed with exit code {e.returncode}", + "output_files": [], + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_hicexplorer' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def hic_correct_matrix( + matrix: Path, + out_file_name: Path, + correction_method: str, + filter_threshold: Optional[List[float]] = None, + chromosome: Optional[str] = None, + iterations: Optional[int] = None, + threads: int = 1, + dump_correction_factors: Optional[Path] = None, + load_correction_factors: Optional[Path] = None, + correction_factor_format: str = "hdf5", + version: bool = False, +) -> dict: + """ + Corrects a Hi-C matrix using methods like ICE or KR. + + This tool applies normalization to a raw Hi-C matrix to remove biases, + such as those from restriction enzyme sites, GC content, and mappability. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if correction_method not in ["ICE", "KR"]: + raise ValueError("correction_method must be either 'ICE' or 'KR'.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if correction_factor_format not in ["hdf5", "tsv"]: + raise ValueError("correction_factor_format must be 'hdf5' or 'tsv'.") + + cmd = [ + "hicCorrectMatrix", + "correct", + "--matrix", str(matrix), + "--correctionMethod", correction_method, + "--outFileName", str(out_file_name), + "--threads", str(threads), + "--correctionFactorFormat", correction_factor_format, + ] + + if filter_threshold: + cmd.extend(["--filterThreshold", *[str(f) for f in filter_threshold]]) + if chromosome: + cmd.extend(["--chromosome", chromosome]) + if iterations is not None: + cmd.extend(["--iterations", str(iterations)]) + if dump_correction_factors: + cmd.extend(["--dumpCorrectionFactors", str(dump_correction_factors)]) + if load_correction_factors: + cmd.extend(["--loadCorrectionFactors", str(load_correction_factors)]) + if version: + cmd.append("--version") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(out_file_name)] + if dump_correction_factors: + output_files.append(str(dump_correction_factors)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicCorrectMatrix failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hic_find_tads( + matrix: Path, + out_prefix: str, + correct_for_depth: bool = False, + min_depth: int = 10000, + max_depth: int = 100000, + step: int = 10000, + threshold_comparisons: float = 0.01, + delta: float = 0.01, + correct_for_multiple_testing: Optional[str] = None, + z_score_threshold: float = -2.0, + threads: int = 4, + tad_separation_threshold: float = 0.0, +) -> dict: + """ + Identifies Topologically Associating Domains (TADs) in a Hi-C matrix. + + This tool uses an insulation score-based method to find TAD boundaries and domains. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if correct_for_multiple_testing and correct_for_multiple_testing not in ["fdr", "bonferroni"]: + raise ValueError("correct_for_multiple_testing must be 'fdr' or 'bonferroni'.") + + cmd = [ + "hicFindTADs", + "--matrix", str(matrix), + "--outPrefix", out_prefix, + "--minDepth", str(min_depth), + "--maxDepth", str(max_depth), + "--step", str(step), + "--thresholdComparisons", str(threshold_comparisons), + "--delta", str(delta), + "--zscore_threshold", str(z_score_threshold), + "--threads", str(threads), + "--TAD_separation_threshold", str(tad_separation_threshold), + ] + + if correct_for_depth: + cmd.append("--correctForDepth") + if correct_for_multiple_testing: + cmd.extend(["--correctForMultipleTesting", correct_for_multiple_testing]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # Expected output files based on prefix + output_files = [ + f"{out_prefix}_zscore_matrix.h5", + f"{out_prefix}_score.bm", + f"{out_prefix}_boundaries.bed", + f"{out_prefix}_domains.bed", + f"{out_prefix}_TAD_separation_score.bm", + ] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicFindTADs failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hic_plot_matrix( + matrix: Path, + out_file_name: Path, + region: Optional[str] = None, + region2: Optional[str] = None, + chromosome: Optional[str] = None, + title: Optional[str] = None, + v_min: Optional[float] = None, + v_max: Optional[float] = None, + color_map: str = "RdYlBu_r", + log1p: bool = False, + clear_masked_bins: bool = False, + show_masked_bins: bool = False, + loops: Optional[Path] = None, + dpi: int = 300, + bigwig: Optional[Path] = None, + bigwig_y_min: Optional[float] = None, + bigwig_y_max: Optional[float] = None, + bigwig_color: str = "black", + per_chromosome: bool = False, + pca: Optional[Path] = None, + tads: Optional[Path] = None, + scale_factor: float = 1.0, +) -> dict: + """ + Plots a Hi-C contact matrix for a specified region. + + This tool generates a heatmap visualization of a Hi-C matrix, with options to overlay + TADs, loops, PCA eigenvectors (A/B compartments), and bigWig tracks. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if loops and not loops.is_file(): + raise FileNotFoundError(f"Loops file not found: {loops}") + if bigwig and not bigwig.is_file(): + raise FileNotFoundError(f"Bigwig file not found: {bigwig}") + if pca and not pca.is_file(): + raise FileNotFoundError(f"PCA file not found: {pca}") + if tads and not tads.is_file(): + raise FileNotFoundError(f"TADs file not found: {tads}") + if dpi <= 0: + raise ValueError("DPI must be a positive integer.") + + cmd = [ + "hicPlotMatrix", + "--matrix", str(matrix), + "--outFileName", str(out_file_name), + "--colorMap", color_map, + "--dpi", str(dpi), + "--scaleFactor", str(scale_factor), + ] + + if region: + cmd.extend(["--region", region]) + if region2: + cmd.extend(["--region2", region2]) + if chromosome: + cmd.extend(["--chromosome", chromosome]) + if title: + cmd.extend(["--title", title]) + if v_min is not None: + cmd.extend(["--vMin", str(v_min)]) + if v_max is not None: + cmd.extend(["--vMax", str(v_max)]) + if log1p: + cmd.append("--log1p") + if clear_masked_bins: + cmd.append("--clearMaskedBins") + if show_masked_bins: + cmd.append("--show_masked_bins") + if loops: + cmd.extend(["--loops", str(loops)]) + if bigwig: + cmd.extend(["--bigwig", str(bigwig)]) + if bigwig_y_min is not None: + cmd.extend(["--bigwig_y_min", str(bigwig_y_min)]) + if bigwig_y_max is not None: + cmd.extend(["--bigwig_y_max", str(bigwig_y_max)]) + cmd.extend(["--bigwig_color", bigwig_color]) + if per_chromosome: + cmd.append("--perChromosome") + if pca: + cmd.extend(["--pca", str(pca)]) + if tads: + cmd.extend(["--TADs", str(tads)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_file_name)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicPlotMatrix failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hic_pca( + matrix: Path, + out_file_name_bigwig: Path, + out_file_name_bedgraph: Path, + format: str = "bigwig", + chromosomes: Optional[List[str]] = None, + number_of_eigenvectors: int = 1, + threads: int = 4, +) -> dict: + """ + Computes A/B compartments using Principal Component Analysis (PCA). + + This tool calculates the first few eigenvectors of the observed/expected-transformed + and Pearson-correlation-transformed Hi-C matrix to identify genomic compartments. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if format not in ["bigwig", "bedgraph"]: + raise ValueError("Format must be 'bigwig' or 'bedgraph'.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if number_of_eigenvectors <= 0: + raise ValueError("number_of_eigenvectors must be a positive integer.") + + cmd = [ + "hicPCA", + "--matrix", str(matrix), + "--format", format, + "--numberOfEigenvectors", str(number_of_eigenvectors), + "--threads", str(threads), + ] + + if format == "bigwig": + cmd.extend(["--outputFileName", str(out_file_name_bigwig)]) + else: # bedgraph + cmd.extend(["--outputFileName", str(out_file_name_bedgraph)]) + + if chromosomes: + cmd.extend(["--chromosomes", *chromosomes]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [] + if format == "bigwig": + output_files.append(str(out_file_name_bigwig)) + else: + output_files.append(str(out_file_name_bedgraph)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicPCA failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hic_compare_matrices( + matrices: List[Path], + out_file_name: Path, + operation: str, + region: Optional[str] = None, + chromosome: Optional[str] = None, + v_min: Optional[float] = None, + v_max: Optional[float] = None, + color_map: str = "jet", + log1p: bool = False, + plot_title: Optional[str] = None, + dpi: int = 300, +) -> dict: + """ + Compares two or more Hi-C matrices using various operations. + + This tool can compute the difference, ratio, or log2ratio between two matrices, + or find the mean of multiple matrices. The result is saved as a new matrix and a plot. + """ + # Input validation + if len(matrices) < 2: + raise ValueError("At least two matrices are required for comparison.") + if not all(f.is_file() for f in matrices): + raise FileNotFoundError("One or more input matrix files not found.") + if operation not in ["difference", "ratio", "log2ratio", "mean"]: + raise ValueError("Operation must be one of 'difference', 'ratio', 'log2ratio', 'mean'.") + if dpi <= 0: + raise ValueError("DPI must be a positive integer.") + + cmd = [ + "hicCompareMatrices", + "--matrices", *[str(m) for m in matrices], + "--outFileName", str(out_file_name), + "--operation", operation, + "--colorMap", color_map, + "--dpi", str(dpi), + ] + + if region: + cmd.extend(["--region", region]) + if chromosome: + cmd.extend(["--chromosome", chromosome]) + if v_min is not None: + cmd.extend(["--vMin", str(v_min)]) + if v_max is not None: + cmd.extend(["--vMax", str(v_max)]) + if log1p: + cmd.append("--log1p") + if plot_title: + cmd.extend(["--plotTitle", plot_title]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # The tool creates a matrix (.h5 or .cool) and a plot (.png, .pdf, etc.) + # We return the path provided by the user, assuming the extension is correct. + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_file_name)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicCompareMatrices failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hic_convert_format( + in_file_name: Path, + out_file_name: Path, + in_format: str, + out_format: str, + threads: int = 1, + load_as_cooler: bool = False, + store_as_cooler: bool = False, +) -> dict: + """ + Converts Hi-C matrices between different formats. + + Supported formats include homer, hic-pro, cool, and h5 (HiCExplorer's format). + """ + # Input validation + if not in_file_name.is_file(): + raise FileNotFoundError(f"Input file not found: {in_file_name}") + supported_formats = ["homer", "hicpro", "cool", "h5"] + if in_format not in supported_formats: + raise ValueError(f"Input format '{in_format}' is not supported.") + if out_format not in supported_formats: + raise ValueError(f"Output format '{out_format}' is not supported.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + + cmd = [ + "hicConvertFormat", + "--inFileName", str(in_file_name), + "--outFileName", str(out_file_name), + "--inputFormat", in_format, + "--outputFormat", out_format, + "--threads", str(threads), + ] + + if load_as_cooler: + cmd.append("--load_as_cooler") + if store_as_cooler: + cmd.append("--store_as_cooler") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_file_name)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicConvertFormat failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hic_detect_loops( + matrix: Path, + out_file_name: Path, + window_size: int = 10, + peak_width: int = 6, + p_value_threshold: float = 0.01, + threads: int = 4, + chromosomes: Optional[List[str]] = None, +) -> dict: + """ + Detects chromatin loops in a Hi-C matrix using the HiCCUPS algorithm. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if window_size <= 0: + raise ValueError("window_size must be a positive integer.") + if peak_width <= 0: + raise ValueError("peak_width must be a positive integer.") + if not (0 < p_value_threshold <= 1): + raise ValueError("p_value_threshold must be between 0 and 1.") + + cmd = [ + "hicDetectLoops", + "--matrix", str(matrix), + "--outputFile", str(out_file_name), + "--windowSize", str(window_size), + "--peakWidth", str(peak_width), + "--pValue", str(p_value_threshold), + "--threads", str(threads), + ] + + if chromosomes: + cmd.extend(["--chromosomes", *chromosomes]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_file_name)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicDetectLoops failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hic_quick_qc( + bam_files: List[Path], + out_prefix: str, + threads: int = 4, + bin_size: int = 500000, + tmp_dir: Optional[Path] = None, + config_file: Optional[Path] = None, +) -> dict: + """ + Generates a comprehensive QC report for one or more Hi-C datasets. + """ + # Input validation + if not all(f.is_file() for f in bam_files): + raise FileNotFoundError("One or more input BAM files not found.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if bin_size <= 0: + raise ValueError("bin_size must be a positive integer.") + if config_file and not config_file.is_file(): + raise FileNotFoundError(f"Config file not found: {config_file}") + + cmd = [ + "hicQuickQC", + "--bamfiles", *[str(f) for f in bam_files], + "--outPrefix", out_prefix, + "--threads", str(threads), + "--binSize", str(bin_size), + ] + + if tmp_dir: + cmd.extend(["--tmpdir", str(tmp_dir)]) + if config_file: + cmd.extend(["--configFile", str(config_file)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # The tool creates an HTML report and a folder with data + output_files = [f"{out_prefix}.html", f"{out_prefix}_qc"] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicQuickQC failed with exit code {e.returncode}", + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/hicexplorer_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/hicexplorer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9b88d9ca46046541af6a5f01f7ff484b36676cfa --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/hicexplorer_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/hicexplorer_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_hicexplorer' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..94500985754dd7519d7f0306df52ae97de438691 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-hicexplorer: + build: . + image: mcp-hicexplorer:latest + container_name: mcp-hicexplorer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=hicexplorer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..84541a801de77aab09c16dd83dfc8b7cc14dec8d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - hicexplorer + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hicexplorer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4ebb15fcc60ad53ded034507a9613530b7d6d0a3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install igv via conda (e.g., from bioconda) +RUN conda install -c bioconda igv -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/igv_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/igv_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/igv_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/__pycache__/igv_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/__pycache__/igv_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33c17a30c1fbb02dd69a22dd9d414d39da3a467c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/__pycache__/igv_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/igv_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/igv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c6f3b892009c52946b1adc36698d1c59eb87c2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/igv_server.py @@ -0,0 +1,317 @@ +import subprocess +from pathlib import Path +from typing import List, Optional + +# MCP-related imports are intentionally omitted as per instructions. +# from mcp import tool as mcp_tool +# +# class mcp: +# @staticmethod +# def tool(func): +# return func + + +@mcp.tool +def to_tdf( + input_file: Path, + output_file: Path, + genome: str, + max_zoom: int = 7, + probe_window: Optional[int] = None, + window_size: Optional[int] = None, + tmp_dir: Optional[Path] = None, + verbose: bool = False, +): + """ + Converts sorted data files to the Tiled Data Format (.tdf) using igvtools. + + Args: + input_file: Path to the input file (e.g., .wig, .cn, .snp, .igv, .gct). + output_file: Path for the output .tdf file. + genome: A genome ID (e.g., 'hg19') or path to a .genome or chromosome sizes file. + max_zoom: Maximum zoom level to pre-compute. + probe_window: The window size for probe-based array data. + window_size: The window size for density computation. + tmp_dir: Path to a temporary directory. + verbose: If True, enables verbose output. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if max_zoom < 0: + raise ValueError("max_zoom must be a non-negative integer.") + + cmd = ["igvtools", "toTDF"] + + cmd.extend(["-z", str(max_zoom)]) + + if probe_window is not None: + if probe_window <= 0: + raise ValueError("probe_window must be a positive integer.") + cmd.extend(["-p", str(probe_window)]) + + if window_size is not None: + if window_size <= 0: + raise ValueError("window_size must be a positive integer.") + cmd.extend(["-w", str(window_size)]) + + if tmp_dir: + if not tmp_dir.is_dir(): + raise NotADirectoryError(f"Temporary directory not found: {tmp_dir}") + cmd.extend(["--tmpDir", str(tmp_dir)]) + + if verbose: + cmd.extend(["--verbose", "true"]) + + cmd.extend([str(input_file), str(output_file), genome]) + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"igvtools toTDF failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool +def count( + input_file: Path, + output_file: Path, + genome: str, + max_zoom: int = 7, + window_size: int = 25, + ext_factor: Optional[int] = None, + pre_ext_factor: Optional[int] = None, + post_ext_factor: Optional[int] = None, + bases: bool = False, + query: Optional[str] = None, + min_map_quality: int = 0, + include_duplicates: bool = False, + pairs: bool = False, + strands: Optional[str] = None, + tmp_dir: Optional[Path] = None, + verbose: bool = False, +): + """ + Computes coverage from an alignment file using igvtools. + + Args: + input_file: Path to the input alignment file (.bam, .sam, .aligned). + output_file: Path for the output file (.wig or .tdf). + genome: A genome ID (e.g., 'hg19') or path to a .genome or chromosome sizes file. + max_zoom: Maximum zoom level to pre-compute (for .tdf output). + window_size: The window size for coverage calculation. + ext_factor: The read extension factor. + pre_ext_factor: The read pre-extension factor (upstream). + post_ext_factor: The read post-extension factor (downstream). + bases: If True, count bases instead of fragments. + query: Restricts computation to a region, e.g., 'chr1:100-200'. + min_map_quality: Minimum mapping quality for reads to be included. + include_duplicates: If True, include reads marked as duplicates. + pairs: If True, compute coverage from paired reads only. + strands: Specifies which strand to use for paired-end reads ('read', 'first', or 'second'). + tmp_dir: Path to a temporary directory. + verbose: If True, enables verbose output. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if max_zoom < 0: + raise ValueError("max_zoom must be a non-negative integer.") + if window_size <= 0: + raise ValueError("window_size must be a positive integer.") + if min_map_quality < 0: + raise ValueError("min_map_quality must be a non-negative integer.") + if strands and strands not in ["read", "first", "second"]: + raise ValueError("strands must be one of 'read', 'first', or 'second'.") + + cmd = ["igvtools", "count"] + + cmd.extend(["-z", str(max_zoom)]) + cmd.extend(["-w", str(window_size)]) + cmd.extend(["--minMapQuality", str(min_map_quality)]) + + if ext_factor is not None: + cmd.extend(["-e", str(ext_factor)]) + if pre_ext_factor is not None: + cmd.extend(["--preExtFactor", str(pre_ext_factor)]) + if post_ext_factor is not None: + cmd.extend(["--postExtFactor", str(post_ext_factor)]) + if bases: + cmd.append("--bases") + if query: + cmd.extend(["--query", query]) + if include_duplicates: + cmd.append("--includeDuplicates") + if pairs: + cmd.append("--pairs") + if strands: + cmd.extend(["--strands", strands]) + if tmp_dir: + if not tmp_dir.is_dir(): + raise NotADirectoryError(f"Temporary directory not found: {tmp_dir}") + cmd.extend(["--tmpDir", str(tmp_dir)]) + if verbose: + cmd.extend(["--verbose", "true"]) + + cmd.extend([str(input_file), str(output_file), genome]) + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"igvtools count failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool +def index(input_file: Path): + """ + Creates an index for an alignment file using igvtools. + + Args: + input_file: Path to the alignment file to index (.sam, .bam, .aligned). + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Determine expected output index file name + suffix = input_file.suffix.lower() + output_index_file = None + if suffix == ".bam": + output_index_file = input_file.with_suffix(input_file.suffix + ".bai") + elif suffix in [".sam", ".aligned"]: + output_index_file = input_file.with_suffix(input_file.suffix + ".sai") + + cmd = ["igvtools", "index", str(input_file)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + + output_files = [] + if output_index_file and output_index_file.exists(): + output_files.append(str(output_index_file)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"igvtools index failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool +def sort( + input_file: Path, + output_file: Path, + max_records: int = 500000, + tmp_dir: Optional[Path] = None, +): + """ + Sorts an alignment file by genomic position using igvtools. + + Args: + input_file: Path to the input alignment file (.sam, .bam, .aligned). + output_file: Path for the sorted output file. + max_records: Maximum number of records to keep in memory. + tmp_dir: Path to a temporary directory. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if max_records <= 0: + raise ValueError("max_records must be a positive integer.") + + cmd = ["igvtools", "sort"] + + if tmp_dir: + if not tmp_dir.is_dir(): + raise NotADirectoryError(f"Temporary directory not found: {tmp_dir}") + cmd.extend(["--tmpDir", str(tmp_dir)]) + + cmd.extend(["-m", str(max_records)]) + cmd.extend([str(input_file), str(output_file)]) + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"igvtools sort failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool +def version(): + """ + Prints the version number of igvtools. + """ + cmd = ["igvtools", "version"] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"igvtools version failed with exit code {e.returncode}", + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/igv_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/igv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a204c3664afa2cd0a11a8bac8d75b56df47410a9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/igv_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/igv_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_igv' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..93f2cf9f9f5c536dbc54732b4bdb1dae6af6b8cb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-igv: + build: . + image: mcp-igv:latest + container_name: mcp-igv + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=igv + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f420d6ff28c3a95cac0a84b5a71f97c23b9393a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - igv + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_igv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d28dd788a839b3000c541c1c4f1aaa37ee7fbbab --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install infernal via conda (e.g., from bioconda) +RUN conda install -c bioconda infernal -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/infernal_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/infernal_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/infernal_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/__pycache__/infernal_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/__pycache__/infernal_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6635fd048dfd62d53e31e992cd3abfc147c7b5ab Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/__pycache__/infernal_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/infernal_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/infernal_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1ec537176b5ca5df37a7c0fb6bb1bc8e5712fc0f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/infernal_server.py @@ -0,0 +1,595 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal, Optional + +# Helper function to handle subprocess execution and error reporting +def _run_command(cmd: List[str]): + """Executes a command using subprocess and returns a structured output.""" + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Command failed with exit code {e.returncode}", + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_infernal' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cmbuild( + msafile: Path, + cmfile_out: Path, + force: bool = False, + name: Optional[str] = None, + informat: Optional[Literal["stockholm", "afa", "selex", "pfam"]] = None, + outformat: Optional[Literal["stockholm", "afa", "selex", "pfam"]] = None, + refine_output: Optional[Path] = None, + alignment_output: Optional[Path] = None, + use_rf: bool = False, + use_hand: bool = False, + small_memory: bool = False, + weighting_strategy: Literal["none", "pb", "blosum", "given"] = "pb", + gsc_id_threshold: float = 0.62, + entropy_weighting: Literal["none", "set", "ent", "ere"] = "ere", + entropy_set_value: float = 0.0, + prior_strategy: Literal["none", "laplace", "dirichlet"] = "dirichlet", + prior_file: Optional[Path] = None, + fast: bool = False, + null_model_file: Optional[Path] = None, + cpu: int = 1, +) -> dict: + """ + Build a covariance model (CM) from a multiple sequence alignment. + + Args: + msafile: Path to the input multiple sequence alignment file in Stockholm format. + cmfile_out: Path to the output CM file. + force: Force overwrite of the output CM file if it exists. + name: Name the new CM. + informat: Assert that the input msafile is in the specified format. + outformat: Set the format of the output alignment. + refine_output: Refine the alignment, saving the new alignment to this file. + alignment_output: Save the alignment used to build the model to this file. + use_rf: Use reference annotation (#=GC RF) for consensus structure. + use_hand: Use hand-annotated consensus structure from the alignment file. + small_memory: Use a small memory dynamic programming implementation. + weighting_strategy: Set the sequence weighting strategy. + gsc_id_threshold: Set the identity threshold for GSC weights. + entropy_weighting: Set the entropy weighting strategy. + entropy_set_value: Set the entropy weight value when entropy_weighting is 'set'. + prior_strategy: Set the prior strategy. + prior_file: Use a Dirichlet prior from this file. Required if prior_strategy is 'dirichlet'. + fast: Use a heuristic model construction pipeline for faster building. + null_model_file: Read a null model from this file. + cpu: Number of parallel threads to use. + """ + if not msafile.exists(): + raise FileNotFoundError(f"Input MSA file not found: {msafile}") + if cmfile_out.exists() and not force: + raise FileExistsError(f"Output file {cmfile_out} exists. Use force=True to overwrite.") + if sum([use_rf, use_hand, refine_output is not None]) > 1: + raise ValueError("At most one of use_rf, use_hand, or refine_output may be used.") + if gsc_id_threshold < 0.0 or gsc_id_threshold > 1.0: + raise ValueError("gsc_id_threshold must be between 0.0 and 1.0.") + if prior_strategy == "dirichlet" and not prior_file: + raise ValueError("prior_file must be provided when prior_strategy is 'dirichlet'.") + if prior_file and not prior_file.exists(): + raise FileNotFoundError(f"Prior file not found: {prior_file}") + if null_model_file and not null_model_file.exists(): + raise FileNotFoundError(f"Null model file not found: {null_model_file}") + + cmd = ["cmbuild"] + if force: cmd.append("-F") + if name: cmd.extend(["-n", name]) + if informat: cmd.extend(["--informat", informat]) + if outformat: cmd.extend(["--outformat", outformat]) + if refine_output: cmd.extend(["--refine", str(refine_output)]) + if alignment_output: cmd.extend(["-o", str(alignment_output)]) + if use_rf: cmd.append("--rf") + if use_hand: cmd.append("--hand") + if small_memory: cmd.append("--small") + if fast: cmd.append("--fast") + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + + # Weighting strategy + if weighting_strategy == "none": cmd.append("--wnone") + elif weighting_strategy == "pb": cmd.append("--wpb") + elif weighting_strategy == "blosum": cmd.append("--wblosum") + elif weighting_strategy == "given": cmd.append("--wgiven") + if weighting_strategy == "pb": cmd.extend(["--wid", str(gsc_id_threshold)]) + + # Entropy weighting + if entropy_weighting == "none": cmd.append("--enone") + elif entropy_weighting == "set": cmd.extend(["--eset", str(entropy_set_value)]) + elif entropy_weighting == "ent": cmd.append("--eent") + elif entropy_weighting == "ere": cmd.append("--ere") + + # Prior strategy + if prior_strategy == "none": cmd.append("--pnone") + elif prior_strategy == "laplace": cmd.append("--plaplace") + elif prior_strategy == "dirichlet" and prior_file: + cmd.extend(["--pdirichlet", str(prior_file)]) + + if null_model_file: cmd.extend(["--null", str(null_model_file)]) + + cmd.extend([str(cmfile_out), str(msafile)]) + + result = _run_command(cmd) + + output_files = {"output_cm": str(cmfile_out)} + if refine_output: + output_files["refined_alignment"] = str(refine_output) + if alignment_output: + output_files["output_alignment"] = str(alignment_output) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmalign( + cmfile: Path, + seqfile: Path, + output_alignment: Optional[Path] = None, + alignment_mode: Literal["global", "local"] = "local", + informat: Optional[str] = None, + outformat: Literal["stockholm", "afa", "selex", "pfam"] = "stockholm", + map_alignment: Optional[Path] = None, + map_consensus_structure: bool = False, + small_memory: bool = False, + sub_scores_only: bool = False, + nonbanded: bool = False, + algorithm: Literal["cyk", "inside"] = "cyk", + optimal_accuracy: bool = False, + sample: bool = False, + num_samples: int = 1, + random_seed: int = 0, + cpu: int = 1, +) -> dict: + """ + Align sequences to a covariance model. + + Args: + cmfile: Path to the input CM file. + seqfile: Path to the sequence file to align. + output_alignment: Path to save the output alignment. If None, prints to stdout. + alignment_mode: Set the alignment mode ('global' or 'local'). + informat: Assert that the input seqfile is in the specified format. + outformat: Set the format for the output alignment. + map_alignment: Map an existing alignment to the CM. + map_consensus_structure: Map the consensus structure to the alignment. + small_memory: Use a small memory dynamic programming implementation. + sub_scores_only: Use substitution scores only, ignoring insertion/deletion scores. + nonbanded: Use non-banded dynamic programming for higher accuracy but slower speed. + algorithm: Use either the 'cyk' or 'inside' algorithm for alignment. + optimal_accuracy: Use optimal accuracy alignment. + sample: Sample an alignment from the posterior distribution. + num_samples: If sample is True, generate this many samples. + random_seed: Set the random number seed. + cpu: Number of parallel threads to use. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + if not seqfile.exists(): + raise FileNotFoundError(f"Input sequence file not found: {seqfile}") + if map_alignment and not map_alignment.exists(): + raise FileNotFoundError(f"Map alignment file not found: {map_alignment}") + + cmd = ["cmalign"] + if output_alignment: cmd.extend(["-o", str(output_alignment)]) + if alignment_mode == "global": cmd.append("-g") + if alignment_mode == "local": cmd.append("-l") + if informat: cmd.extend(["--informat", informat]) + cmd.extend(["--outformat", outformat]) + if map_alignment: cmd.extend(["--mapali", str(map_alignment)]) + if map_consensus_structure: cmd.append("--mapstr") + if small_memory: cmd.append("--small") + if sub_scores_only: cmd.append("--sub") + if nonbanded: cmd.append("--nonbanded") + if algorithm == "inside": cmd.append("--inside") + if optimal_accuracy: cmd.append("--optacc") + if sample: + cmd.append("--sample") + cmd.extend(["--psample", str(num_samples)]) + if random_seed > 0: cmd.extend(["--seed", str(random_seed)]) + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(cmfile), str(seqfile)]) + + result = _run_command(cmd) + + output_files = {} + if output_alignment: + output_files["output_alignment"] = str(output_alignment) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmsearch( + cmfile: Path, + seqdb: Path, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tabular_output: Optional[Path] = None, + e_value_threshold: float = 10.0, + bitscore_threshold: float = 0.0, + report_all_clan_hits: bool = False, + toponly: bool = False, + bottomonly: bool = False, + no_glocal_search: bool = False, + no_qdb: bool = False, + no_hbanded: bool = False, + rfam: bool = False, + max_sensitivity: bool = False, + cpu: int = 1, +) -> dict: + """ + Search a sequence database with a covariance model. + + Args: + cmfile: Path to the input CM file. + seqdb: Path to the sequence database file. + output_file: Path to save the main output. If None, prints to stdout. + alignment_output: Path to save the alignment of all significant hits. + tabular_output: Path to save a tabular summary of top hits. + e_value_threshold: Report hits with an E-value <= this threshold. + bitscore_threshold: Report hits with a bit score >= this threshold. + report_all_clan_hits: Report all hits, including those within overlapping clans. + toponly: Search only the top strand of the DNA sequence database. + bottomonly: Search only the bottom strand of the DNA sequence database. + no_glocal_search: Turn off the glocal search heuristic filter. + no_qdb: Turn off query-dependent banding. + no_hbanded: Turn off HMM-banded dynamic programming. + rfam: Use strict filtering pipeline settings used by Rfam. + max_sensitivity: Turn off all heuristics to maximize sensitivity. + cpu: Number of parallel threads to use. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + if not seqdb.exists(): + raise FileNotFoundError(f"Sequence database file not found: {seqdb}") + + cmd = ["cmsearch"] + if output_file: cmd.extend(["-o", str(output_file)]) + if alignment_output: cmd.extend(["-A", str(alignment_output)]) + if tabular_output: cmd.extend(["--tblout", str(tabular_output)]) + if e_value_threshold != 10.0: cmd.extend(["-E", str(e_value_threshold)]) + if bitscore_threshold != 0.0: cmd.extend(["-T", str(bitscore_threshold)]) + if report_all_clan_hits: cmd.append("--all-clans") + if toponly: cmd.append("--toponly") + if bottomonly: cmd.append("--bottomonly") + if no_glocal_search: cmd.append("--no-glsearch") + if no_qdb: cmd.append("--no-qdb") + if no_hbanded: cmd.append("--no-hbanded") + if rfam: cmd.append("--rfam") + if max_sensitivity: cmd.append("--max") + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(cmfile), str(seqdb)]) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["main_output"] = str(output_file) + if alignment_output: + output_files["alignment_output"] = str(alignment_output) + if tabular_output: + output_files["tabular_output"] = str(tabular_output) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmscan( + cmdb: Path, + seqfile: Path, + output_file: Optional[Path] = None, + tabular_output: Optional[Path] = None, + e_value_threshold: float = 10.0, + bitscore_threshold: float = 0.0, + glocal: bool = False, + clan_info_file: Optional[Path] = None, + no_overlap_correction: bool = False, + toponly: bool = False, + bottomonly: bool = False, + rfam: bool = False, + max_sensitivity: bool = False, + cpu: int = 1, +) -> dict: + """ + Search sequence(s) against a covariance model database. + + Args: + cmdb: Path to the CM database file (must be pressed with cmpress). + seqfile: Path to the sequence file to search. + output_file: Path to save the main output. If None, prints to stdout. + tabular_output: Path to save a tabular summary of top hits. + e_value_threshold: Report hits with an E-value <= this threshold. + bitscore_threshold: Report hits with a bit score >= this threshold. + glocal: Use glocal alignment mode (local with respect to query, global to target). + clan_info_file: Use clan information from this file for overlap correction. + no_overlap_correction: Turn off all overlap correction. + toponly: Search only the top strand of the DNA sequence. + bottomonly: Search only the bottom strand of the DNA sequence. + rfam: Use strict filtering pipeline settings used by Rfam. + max_sensitivity: Turn off all heuristics to maximize sensitivity. + cpu: Number of parallel threads to use. + """ + if not cmdb.exists(): + raise FileNotFoundError(f"Input CM database not found: {cmdb}") + if not seqfile.exists(): + raise FileNotFoundError(f"Input sequence file not found: {seqfile}") + if clan_info_file and not clan_info_file.exists(): + raise FileNotFoundError(f"Clan info file not found: {clan_info_file}") + + cmd = ["cmscan"] + if output_file: cmd.extend(["-o", str(output_file)]) + if tabular_output: cmd.extend(["--tblout", str(tabular_output)]) + if e_value_threshold != 10.0: cmd.extend(["-E", str(e_value_threshold)]) + if bitscore_threshold != 0.0: cmd.extend(["-T", str(bitscore_threshold)]) + if glocal: cmd.append("--glocal") + if clan_info_file: cmd.extend(["--clanin", str(clan_info_file)]) + if no_overlap_correction: cmd.append("--onone") + if toponly: cmd.append("--toponly") + if bottomonly: cmd.append("--bottomonly") + if rfam: cmd.append("--rfam") + if max_sensitivity: cmd.append("--max") + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(cmdb), str(seqfile)]) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["main_output"] = str(output_file) + if tabular_output: + output_files["tabular_output"] = str(tabular_output) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmpress( + cmfile: Path, + force: bool = False, +) -> dict: + """ + Prepare a CM file for use with cmscan by creating index files. + + Args: + cmfile: Path to the CM file to press. + force: Force overwrite of existing index files. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmpress"] + if force: cmd.append("-F") + cmd.append(str(cmfile)) + + result = _run_command(cmd) + + base = str(cmfile) + output_files = { + "cm_database": base, + "index_f": f"{base}.i1f", + "index_m": f"{base}.i1m", + "index_p": f"{base}.i1p", + "index_i": f"{base}.i1i", + } + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmcalibrate( + cmfile: Path, + num_sequences: int = 2000, + sequence_length: int = 100, + random_seed: int = 0, + cpu: int = 1, +) -> dict: + """ + Calibrate a CM file to fit exponential tail parameters for E-values. + This modifies the input cmfile in-place. + + Args: + cmfile: Path to the CM file to calibrate. + num_sequences: Number of random sequences to generate for calibration. + sequence_length: Length of random sequences to generate. + random_seed: Set the random number seed. + cpu: Number of parallel threads to use. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmcalibrate"] + if num_sequences != 2000: cmd.extend(["-N", str(num_sequences)]) + if sequence_length != 100: cmd.extend(["-L", str(sequence_length)]) + if random_seed > 0: cmd.extend(["--seed", str(random_seed)]) + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + cmd.append(str(cmfile)) + + result = _run_command(cmd) + result["output_files"] = {"calibrated_cm": str(cmfile)} + + return result + +@mcp.tool() +def cmstat( + cmfile: Path, + list_names: bool = False, +) -> dict: + """ + Show summary statistics for a CM file. + + Args: + cmfile: Path to the CM file. + list_names: Show a list of CM names in the file instead of statistics. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmstat"] + if list_names: cmd.append("-l") + cmd.append(str(cmfile)) + + result = _run_command(cmd) + result["output_files"] = {} + return result + +@mcp.tool() +def cmemit( + cmfile: Path, + num_sequences: int = 1, + output_file: Optional[Path] = None, + aligned: bool = False, + consensus: bool = False, + unaligned: bool = False, + sequence_length: Optional[int] = None, + random_seed: int = 0, +) -> dict: + """ + Sample sequences from a covariance model. + + Args: + cmfile: Path to the CM file. + num_sequences: Number of sequences to sample. + output_file: Path to save the output sequences. If None, prints to stdout. + aligned: Generate aligned sequences. + consensus: Generate the consensus sequence. + unaligned: Generate unaligned sequences. + sequence_length: Generate sequences of a fixed length. + random_seed: Set the random number seed. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + if sum([aligned, consensus, unaligned]) > 1: + raise ValueError("Only one of 'aligned', 'consensus', or 'unaligned' can be True.") + + cmd = ["cmemit"] + if num_sequences != 1: cmd.extend(["-N", str(num_sequences)]) + if output_file: cmd.extend(["-o", str(output_file)]) + if aligned: cmd.append("-a") + if consensus: cmd.append("-c") + if unaligned: cmd.append("-u") + if sequence_length: cmd.extend(["-L", str(sequence_length)]) + if random_seed > 0: cmd.extend(["--seed", str(random_seed)]) + cmd.append(str(cmfile)) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["emitted_sequences"] = str(output_file) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmfetch( + cmfile: Path, + keys: List[str], + output_file: Optional[Path] = None, + keys_from_file: bool = False, +) -> dict: + """ + Retrieve one or more CMs from a CM file. + + Args: + cmfile: Path to the CM file (must be indexed with --index first or have a .ssi file). + keys: List of names or accessions of CMs to retrieve. If keys_from_file is True, this should be a single path to a file containing keys. + output_file: Path to save the fetched CM(s). If None, prints to stdout. + keys_from_file: If True, 'keys' argument is treated as a path to a file containing keys. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + if not Path(f"{cmfile}.ssi").exists(): + raise FileNotFoundError(f"Index file {cmfile}.ssi not found. Run cmfetch_index first.") + if keys_from_file: + if len(keys) != 1 or not Path(keys[0]).exists(): + raise FileNotFoundError(f"Key file not found or multiple paths provided: {keys}") + + cmd = ["cmfetch"] + if output_file: cmd.extend(["-o", str(output_file)]) + if keys_from_file: cmd.append("-f") + + cmd.append(str(cmfile)) + cmd.extend(keys) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["fetched_cm"] = str(output_file) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmfetch_index(cmfile: Path) -> dict: + """ + Create a binary SSI index for a CM file for use with cmfetch. + + Args: + cmfile: Path to the CM file to index. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmfetch", "--index", str(cmfile)] + result = _run_command(cmd) + result["output_files"] = {"ssi_index": f"{cmfile}.ssi"} + return result + +@mcp.tool() +def cmconvert( + cmfile: Path, + output_file: Optional[Path] = None, + outformat: Optional[str] = None, +) -> dict: + """ + Convert a CM file to a different format version. + + Args: + cmfile: Path to the input CM file. + output_file: Path to save the converted CM file. If None, prints to stdout. + outformat: The output format to convert to (e.g., '1.1'). + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmconvert"] + if output_file: cmd.extend(["-o", str(output_file)]) + if outformat: cmd.extend(["--outfmt", outformat]) + cmd.append(str(cmfile)) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["converted_cm"] = str(output_file) + result["output_files"] = output_files + + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/infernal_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/infernal_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4a81df0f2aa57ceb34829a2e98ab041cceaf9df6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/infernal_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/infernal_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_infernal' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c6ded46c289b6320b59c14c8436e850705e0e4f7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-infernal: + build: . + image: mcp-infernal:latest + container_name: mcp-infernal + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=infernal + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8aede6ab663f5e590c4e7c529b989fff4e48a7c7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - infernal + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_infernal/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3ddc187860d0f99c303e059198f662efff2d4793 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install intarna via conda (e.g., from bioconda) +RUN conda install -c bioconda intarna -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/intarna_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/intarna_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/intarna_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/__pycache__/intarna_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/__pycache__/intarna_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3eb33d5c30e49e667a5f5785d071055112312296 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/__pycache__/intarna_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/intarna_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/intarna_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ea0c14ac6e581a1ca209e30cd7417bc059562ebf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/intarna_server.py @@ -0,0 +1,318 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_intarna' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def intarna( + query: Path, + target: Path, + # OUTPUT + n_best: int = 100, + out: Optional[Path] = None, + out_mode: str = "C", + out_overlap: str = "N", + out_csv_cols: Optional[str] = None, + out_max_e: Optional[float] = None, + out_min_pu1: float = 0.0, + out_min_pu2: float = 0.0, + out_best: int = 1, + out_sub_opt: Optional[str] = None, + out_per_tar: int = 0, + out_per_qry: int = 0, + out_no_lp: bool = False, + # INTERACTION + q_acc: str = "W", + q_acc_file: Optional[Path] = None, + q_acc_w: int = 150, + q_acc_l: int = 100, + q_acc_constr: Optional[str] = None, + q_int_len_max: int = 150, + q_int_loop: int = 16, + q_max_bp: int = 200, + q_region: Optional[str] = None, + q_idx_pos: Optional[str] = None, + q_idx_file: Optional[Path] = None, + t_acc: str = "W", + t_acc_file: Optional[Path] = None, + t_acc_w: int = 150, + t_acc_l: int = 100, + t_acc_constr: Optional[str] = None, + t_int_len_max: int = 150, + t_int_loop: int = 16, + t_max_bp: int = 200, + t_region: Optional[str] = None, + t_idx_pos: Optional[str] = None, + t_idx_file: Optional[Path] = None, + interaction_span: Optional[str] = None, + interaction_type: str = "I", + energy: str = "V", + temperature: float = 37.0, + no_gu_end: bool = False, + no_closing_gu: bool = False, + max_loop: int = 16, + max_bp: int = 200, + no_lpi: bool = False, + lp: bool = False, + # SEED + seed_bp: int = 2, + seed_max_up: int = 0, + seed_q_max_up: int = 0, + seed_t_max_up: int = 0, + seed_u_left: int = 0, + seed_u_right: int = 0, + seed_q_region: Optional[str] = None, + seed_t_region: Optional[str] = None, + seed_constraint: Optional[str] = None, + seed_ref: Optional[str] = None, + seed_s1: float = 1.0, + seed_s2: float = 1.0, + no_seed: bool = False, + # MISC + verbose: bool = False, + threads: int = 0, +) -> Dict: + """ + Predicts RNA-RNA interactions using IntaRNA. + + This tool wraps the IntaRNA command-line interface to predict interactions + between a query and a target RNA sequence. + + Args: + query: Path to the query sequence(s) in FASTA format. + target: Path to the target sequence(s) in FASTA format. + n_best: Number of best interactions to report. + out: Path to the output file. If not provided, a temporary file is created. + out_mode: Output format ('c', 'C', 'd', 'D', 's'). + out_overlap: Overlap handling for suboptimal interactions ('N', 'Q', 'T'). + out_csv_cols: Comma-separated list of column IDs for CSV output. + out_max_e: Report only interactions with energy at most this value. + out_min_pu1: Report only interactions with accessibility Pu1 at least this value. + out_min_pu2: Report only interactions with accessibility Pu2 at least this value. + out_best: Number of best interactions to report per query-target-pair. + out_sub_opt: Energy range of suboptimal interactions, e.g., 'f(E_opt)=E_opt+2.5'. + out_per_tar: Number of best interactions to report per target. + out_per_qry: Number of best interactions to report per query. + out_no_lp: Suppress calculation of interaction probability for full length sequences. + q_acc: Accessibility computation for query ('W', 'C', 'S', 'N', 'R'). + q_acc_file: File to read query accessibility from (if q_acc='R'). + q_acc_w: Window size for query accessibility computation. + q_acc_l: Maximal loop length for query accessibility computation. + q_acc_constr: RNAplfold constraints for query accessibility computation. + q_int_len_max: Maximal interaction length for query. + q_int_loop: Maximal loop length in query interaction. + q_max_bp: Maximal number of base pairs in an interaction for query. + q_region: Subregion of query to consider, e.g., '10-50'. + q_idx_pos: Comma-separated list of query positions to consider. + q_idx_file: File with query positions to consider. + t_acc: Accessibility computation for target ('W', 'C', 'S', 'N', 'R'). + t_acc_file: File to read target accessibility from (if t_acc='R'). + t_acc_w: Window size for target accessibility computation. + t_acc_l: Maximal loop length for target accessibility computation. + t_acc_constr: RNAplfold constraints for target accessibility computation. + t_int_len_max: Maximal interaction length for target. + t_int_loop: Maximal loop length in target interaction. + t_max_bp: Maximal number of base pairs in an interaction for target. + t_region: Subregion of target to consider, e.g., '10-50'. + t_idx_pos: Comma-separated list of target positions to consider. + t_idx_file: File with target positions to consider. + interaction_span: Maximal distance between interaction sites, e.g., 'i-j' or 'i+j'. + interaction_type: Type of interaction to predict ('H', 'I', 'B'). + energy: Energy computation model ('V', 'S'). + temperature: Temperature in Celsius for energy computation. + no_gu_end: Disallow GU pairs at the end of helices. + no_closing_gu: Disallow GU pairs at the ends of loops. + max_loop: Maximal number of unpaired bases in a loop. + max_bp: Maximal number of base pairs in the interaction. + no_lpi: Suppress penalization of lonely base pairs. + lp: Enable calculation of interaction probability for full length sequences (slow). + seed_bp: Minimal number of base pairs in the seed. + seed_max_up: Maximal number of unpaired bases in the seed. + seed_q_max_up: Maximal number of unpaired bases in the query part of the seed. + seed_t_max_up: Maximal number of unpaired bases in the target part of the seed. + seed_u_left: Maximal number of unpaired bases in the left part of the seed. + seed_u_right: Maximal number of unpaired bases in the right part of the seed. + seed_q_region: Subregion of query for seed prediction. + seed_t_region: Subregion of target for seed prediction. + seed_constraint: Seed constraint to apply, e.g., 'E:-10'. + seed_ref: Reference seed for constraint evaluation, e.g., '10-20:30-40'. + seed_s1: Sensitivity weight for query accessibility. + seed_s2: Sensitivity weight for target accessibility. + no_seed: Disable seed constraint. + verbose: Be verbose. + threads: Maximal number of threads for parallel computation. + + Returns: + A dictionary containing the executed command, stdout, stderr, and output file paths. + """ + # Input validation + if not query.is_file(): + raise FileNotFoundError(f"Query file not found: {query}") + if not target.is_file(): + raise FileNotFoundError(f"Target file not found: {target}") + + # Validate choice parameters + valid_out_modes = ['c', 'C', 'd', 'D', 's'] + if out_mode not in valid_out_modes: + raise ValueError(f"Invalid out_mode '{out_mode}'. Must be one of {valid_out_modes}") + + valid_out_overlaps = ['N', 'Q', 'T'] + if out_overlap not in valid_out_overlaps: + raise ValueError(f"Invalid out_overlap '{out_overlap}'. Must be one of {valid_out_overlaps}") + + valid_acc_modes = ['W', 'C', 'S', 'N', 'R'] + if q_acc not in valid_acc_modes: + raise ValueError(f"Invalid q_acc '{q_acc}'. Must be one of {valid_acc_modes}") + if t_acc not in valid_acc_modes: + raise ValueError(f"Invalid t_acc '{t_acc}'. Must be one of {valid_acc_modes}") + + if q_acc == 'R' and (q_acc_file is None or not q_acc_file.is_file()): + raise ValueError("q_acc_file must be provided and exist when q_acc is 'R'") + if t_acc == 'R' and (t_acc_file is None or not t_acc_file.is_file()): + raise ValueError("t_acc_file must be provided and exist when t_acc is 'R'") + + if q_idx_file and not q_idx_file.is_file(): + raise FileNotFoundError(f"Query index file not found: {q_idx_file}") + if t_idx_file and not t_idx_file.is_file(): + raise FileNotFoundError(f"Target index file not found: {t_idx_file}") + + valid_interaction_types = ['H', 'I', 'B'] + if interaction_type not in valid_interaction_types: + raise ValueError(f"Invalid interaction_type '{interaction_type}'. Must be one of {valid_interaction_types}") + + valid_energy_models = ['V', 'S'] + if energy not in valid_energy_models: + raise ValueError(f"Invalid energy model '{energy}'. Must be one of {valid_energy_models}") + + # Command construction + cmd = ["IntaRNA", f"--query={query}", f"--target={target}"] + + # Output handling + output_files = {} + if out: + output_path = out + else: + tmp_out = tempfile.NamedTemporaryFile(delete=False, mode='w', suffix=".csv") + tmp_out.close() + output_path = Path(tmp_out.name) + + output_files["predictions"] = str(output_path) + cmd.append(f"--out={output_path}") + + # Add optional parameters if they differ from the default + if n_best != 100: cmd.append(f"--nBest={n_best}") + if out_mode != "C": cmd.append(f"--outMode={out_mode}") + if out_overlap != "N": cmd.append(f"--outOverlap={out_overlap}") + if out_csv_cols is not None: cmd.append(f'--outCsvCols="{out_csv_cols}"') + if out_max_e is not None: cmd.append(f"--outMaxE={out_max_e}") + if out_min_pu1 != 0.0: cmd.append(f"--outMinPu1={out_min_pu1}") + if out_min_pu2 != 0.0: cmd.append(f"--outMinPu2={out_min_pu2}") + if out_best != 1: cmd.append(f"--outBest={out_best}") + if out_sub_opt is not None: cmd.append(f'--outSubOpt="{out_sub_opt}"') + if out_per_tar != 0: cmd.append(f"--outPerTar={out_per_tar}") + if out_per_qry != 0: cmd.append(f"--outPerQry={out_per_qry}") + if out_no_lp: cmd.append("--outNoLP") + + # Interaction parameters + if q_acc != "W": cmd.append(f"--qAcc={q_acc}") + if q_acc_file: cmd.append(f"--qAccFile={q_acc_file}") + if q_acc_w != 150: cmd.append(f"--qAccW={q_acc_w}") + if q_acc_l != 100: cmd.append(f"--qAccL={q_acc_l}") + if q_acc_constr: cmd.append(f'--qAccConstr="{q_acc_constr}"') + if q_int_len_max != 150: cmd.append(f"--qIntLenMax={q_int_len_max}") + if q_int_loop != 16: cmd.append(f"--qIntLoop={q_int_loop}") + if q_max_bp != 200: cmd.append(f"--qMaxBP={q_max_bp}") + if q_region: cmd.append(f"--qRegion={q_region}") + if q_idx_pos: cmd.append(f"--qIdxPos={q_idx_pos}") + if q_idx_file: cmd.append(f"--qIdxFile={q_idx_file}") + + if t_acc != "W": cmd.append(f"--tAcc={t_acc}") + if t_acc_file: cmd.append(f"--tAccFile={t_acc_file}") + if t_acc_w != 150: cmd.append(f"--tAccW={t_acc_w}") + if t_acc_l != 100: cmd.append(f"--tAccL={t_acc_l}") + if t_acc_constr: cmd.append(f'--tAccConstr="{t_acc_constr}"') + if t_int_len_max != 150: cmd.append(f"--tIntLenMax={t_int_len_max}") + if t_int_loop != 16: cmd.append(f"--tIntLoop={t_int_loop}") + if t_max_bp != 200: cmd.append(f"--tMaxBP={t_max_bp}") + if t_region: cmd.append(f"--tRegion={t_region}") + if t_idx_pos: cmd.append(f"--tIdxPos={t_idx_pos}") + if t_idx_file: cmd.append(f"--tIdxFile={t_idx_file}") + + if interaction_span: cmd.append(f"--interactionSpan={interaction_span}") + if interaction_type != "I": cmd.append(f"--interactionType={interaction_type}") + if energy != "V": cmd.append(f"--energy={energy}") + if temperature != 37.0: cmd.append(f"--temperature={temperature}") + if no_gu_end: cmd.append("--noGUend") + if no_closing_gu: cmd.append("--noClosingGU") + if max_loop != 16: cmd.append(f"--maxLoop={max_loop}") + if max_bp != 200: cmd.append(f"--maxBP={max_bp}") + if no_lpi: cmd.append("--noLPI") + if lp: cmd.append("--lp") + + # Seed parameters + if seed_bp != 2: cmd.append(f"--seedBP={seed_bp}") + if seed_max_up != 0: cmd.append(f"--seedMaxUP={seed_max_up}") + if seed_q_max_up != 0: cmd.append(f"--seedQMaxUP={seed_q_max_up}") + if seed_t_max_up != 0: cmd.append(f"--seedTMaxUP={seed_t_max_up}") + if seed_u_left != 0: cmd.append(f"--seedULeft={seed_u_left}") + if seed_u_right != 0: cmd.append(f"--seedURight={seed_u_right}") + if seed_q_region: cmd.append(f"--seedQRegion={seed_q_region}") + if seed_t_region: cmd.append(f"--seedTRegion={seed_t_region}") + if seed_constraint: cmd.append(f'--seedConstraint="{seed_constraint}"') + if seed_ref: cmd.append(f"--seedRef={seed_ref}") + if seed_s1 != 1.0: cmd.append(f"--seedS1={seed_s1}") + if seed_s2 != 1.0: cmd.append(f"--seedS2={seed_s2}") + if no_seed: cmd.append("--noSeed") + + # Misc parameters + if verbose: cmd.append("--verbose") + if threads != 0: cmd.append(f"--threads={threads}") + + # Subprocess execution + try: + command_str = " ".join(map(str, cmd)) + result = subprocess.run( + command_str, + shell=True, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + if not out and output_path.exists(): + output_path.unlink() + return { + "error": "IntaRNA execution failed", + "command_executed": " ".join(map(str, cmd)), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode + } + except FileNotFoundError: + return { + "error": "IntaRNA executable not found in PATH.", + "command_executed": " ".join(map(str, cmd)), + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/intarna_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/intarna_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf1a533d805a806d95e46f65b395818e77ddbc1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/intarna_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/intarna_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_intarna' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..19d358cc3aca89575326009f64ef9deb40dec94e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-intarna: + build: . + image: mcp-intarna:latest + container_name: mcp-intarna + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=intarna + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c555c6076e1b547beff2356ff99d5e5f8c1a7ca8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - intarna + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_intarna/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..699480338aaa62c52b977276664b04ea089856da --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install iow via conda (e.g., from bioconda) +RUN conda install -c bioconda iow -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/iow_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/iow_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/iow_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/__pycache__/iow_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/__pycache__/iow_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ab215d19fa8b43f29a08669a0efc6e2746639c8 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/__pycache__/iow_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/iow_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/iow_server.py new file mode 100644 index 0000000000000000000000000000000000000000..08d8348b2d5d22f75f70489cc989d8eec5b3c478 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/iow_server.py @@ -0,0 +1,104 @@ +import subprocess +from pathlib import Path +from typing import Literal, Dict + +# @mcp.tool() is a placeholder for the MCP decorator. +# The actual MCP framework would provide this. +# For this exercise, we'll define a dummy decorator to make the code runnable. +def tool_decorator_dummy(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': tool_decorator_dummy}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_iow' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def placement( + placements: Path, + output: Path, + method: Literal["fully-resolved", "multifurcating"], +) -> Dict: + """ + Handles fragment insertions from a jplace file into a tree using the 'bp' command. + + This tool supports two methods for inserting fragments: + - 'fully-resolved': The edge placed against is broken N times, where N is the number of fragments on the edge. + - 'multifurcating': A new node is constructed as the average of the distal length for the N fragments, + and a separate multifurcation node is added which encompasses the placed fragments. + Note: The 'multifurcating' method requires the 'iow-gpl' package. + + Args: + placements (Path): Path to the input jplace formatted data file. + output (Path): Path where the resulting newick file will be written. + method (Literal["fully-resolved", "multifurcating"]): The method to use for fragment insertion. + + Returns: + Dict: A dictionary containing the execution details and output file path. + """ + # 1. Input Validation + if not placements.is_file(): + raise FileNotFoundError(f"Input placements file not found: {placements}") + + # The 'method' parameter is validated by the Literal type hint at static analysis time. + # A runtime check is included for robustness. + if method not in ["fully-resolved", "multifurcating"]: + raise ValueError(f"Invalid method '{method}'. Must be 'fully-resolved' or 'multifurcating'.") + + # Ensure the output directory exists + try: + output.parent.mkdir(parents=True, exist_ok=True) + except Exception as e: + raise IOError(f"Could not create output directory {output.parent}: {e}") + + # 2. Command Construction + cmd = [ + "bp", "placement", + "--placements", str(placements), + "--output", str(output), + "--method", method, + ] + command_executed = " ".join(cmd) + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"output_newick": str(output)} + } + except FileNotFoundError: + # This error is caught if the 'bp' command is not found in the system's PATH. + error_message = "Error: 'bp' command not found. Make sure the 'iow' package is installed and its bin directory is in the system's PATH." + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_message, + "output_files": {} + } + except subprocess.CalledProcessError as e: + # This error is caught if the tool returns a non-zero exit code. + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {} + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/iow_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/iow_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be2147f9590b1cd0133207f2759278fe680cce78 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/iow_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/iow_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_iow' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6344efa4829bddca1fb42cc9fe17879837337f8e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-iow: + build: . + image: mcp-iow:latest + container_name: mcp-iow + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=iow + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3713b5ea0dc47a5b42a80767a15a281bebdfb59 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - iow + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_iow/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5236eebe1d864c12b08ae081475cf4ca6463f409 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ipyrad via conda (e.g., from bioconda) +RUN conda install -c bioconda ipyrad -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ipyrad_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ipyrad_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ipyrad_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/__pycache__/ipyrad_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/__pycache__/ipyrad_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49227507fbfe065d7b9e505b5fcc6b34e534a43e Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/__pycache__/ipyrad_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/ipyrad_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/ipyrad_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8660813ad3a9eabcc975f658fdbfe88fb10e4815 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/ipyrad_server.py @@ -0,0 +1,243 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# Set up logging for better debugging in a server environment +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# MCP decorator is assumed to be provided by the execution environment. +# This is a placeholder for the actual decorator. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def ipyrad_new_params( + name: str, + force: bool = False, + output_dir: Optional[Path] = None +) -> dict: + """ + Creates a new ipyrad parameters file (params-.txt). + + This corresponds to the command `ipyrad -n -p new`. + + Args: + name: The project name for the analysis. + force: If True, overwrite an existing params file with the same name (-f). + output_dir: Directory where the params file will be created. Defaults to the current working directory. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the created params file. + """ + # Input validation + if not name or not name.strip(): + raise ValueError("Project name must be a non-empty string.") + + cmd = ["ipyrad", "-n", name, "-p", "new"] + if force: + cmd.append("-f") + + # Determine the working directory for the command + work_dir = output_dir if output_dir else Path.cwd() + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed} in {work_dir}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=work_dir, + ) + + output_file = work_dir / f"params-{name}.txt" + if not output_file.exists(): + raise FileNotFoundError( + f"ipyrad command ran successfully but the expected output file was not found: {output_file}\n" + f"STDOUT: {result.stdout}\nSTDERR: {result.stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + + except FileNotFoundError: + err_msg = "Error: 'ipyrad' command not found. Make sure ipyrad is installed and in your system's PATH." + logging.error(err_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": err_msg, + "output_files": [] + } + except subprocess.CalledProcessError as e: + logging.error(f"ipyrad failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool +def ipyrad_run_analysis( + name: str, + params: Path, + steps: str, + cores: int = 1, + threads: int = 1, + force: bool = False, + debug: bool = False, + custom_map: Optional[Path] = None, +) -> dict: + """ + Runs the ipyrad analysis pipeline for one or more steps. + + This corresponds to the command `ipyrad -n -p -s -r ...`. + + Args: + name: The project name for the analysis (must match the name in the params file). + params: Path to the ipyrad parameters file (e.g., 'params-myproject.txt'). + steps: A string of digits representing the steps to run (e.g., '123' or '34567'). + cores: Number of cores to use for parallel jobs (-c). + threads: Number of threads per core for parallel jobs (-t). + force: If True, force overwrite of existing data for the specified steps (-f). + debug: If True, print debug messages to the terminal (-d). + custom_map: Path to a file with ipyrad -n and -p info for many jobs (-m). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the main output directory. + """ + # Input validation + if not name or not name.strip(): + raise ValueError("Project name must be a non-empty string.") + if not params.is_file(): + raise FileNotFoundError(f"Parameters file not found at: {params}") + if not steps or not steps.isdigit() or any(c not in "1234567" for c in steps): + raise ValueError("Steps must be a string containing only digits from 1 to 7 (e.g., '123').") + if cores < 1: + raise ValueError("Number of cores must be a positive integer.") + if threads < 1: + raise ValueError("Number of threads must be a positive integer.") + if custom_map and not custom_map.is_file(): + raise FileNotFoundError(f"Custom map file not found at: {custom_map}") + + cmd = [ + "ipyrad", + "-n", name, + "-p", str(params.resolve()), + "-s", steps, + "-c", str(cores), + "-t", str(threads), + "-r" # The -r flag is essential to execute the run + ] + + if force: + cmd.append("-f") + if debug: + cmd.append("-d") + if custom_map: + cmd.extend(["-m", str(custom_map.resolve())]) + + # ipyrad creates its output directory relative to the current working directory. + # It's best practice to run it from the directory containing the params file. + work_dir = params.parent + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed} in {work_dir}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=work_dir, + ) + + # The primary output is a directory named after the project + output_directory = work_dir / name + output_files = [str(output_directory)] if output_directory.is_dir() else [] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + + except FileNotFoundError: + err_msg = "Error: 'ipyrad' command not found. Make sure ipyrad is installed and in your system's PATH." + logging.error(err_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": err_msg, + "output_files": [] + } + except subprocess.CalledProcessError as e: + logging.error(f"ipyrad failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool +def ipyrad_version() -> dict: + """ + Gets the installed version of ipyrad. + + This corresponds to the command `ipyrad -v`. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the parsed version string. + """ + cmd = ["ipyrad", "-v"] + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # The version is usually the only thing in stdout, e.g., "ipyrad 0.9.87" + version_string = result.stdout.strip().split()[-1] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "version": version_string + } + except FileNotFoundError: + err_msg = "Error: 'ipyrad' command not found. Make sure ipyrad is installed and in your system's PATH." + logging.error(err_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": err_msg, + "version": None + } + except (subprocess.CalledProcessError, IndexError) as e: + stderr = e.stderr if hasattr(e, 'stderr') else str(e) + stdout = e.stdout if hasattr(e, 'stdout') else "" + logging.error(f"ipyrad -v failed: {stderr}") + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "version": None + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/ipyrad_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/ipyrad_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..19f6a420287add5b291a876e1c82a2488d4b2bfa --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/ipyrad_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/ipyrad_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_ipyrad' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..48be8956727034a48aecd5dd60fa915f08cde466 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ipyrad: + build: . + image: mcp-ipyrad:latest + container_name: mcp-ipyrad + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ipyrad + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..104c5fae4ae2884880d9269acc6df2dfb115fc74 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ipyrad + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipyrad/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e78a2d7a1f6cf1e5bbc56c5606c41daa80bbfaf7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kaiju via conda (e.g., from bioconda) +RUN conda install -c bioconda kaiju -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kaiju_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kaiju_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kaiju_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/__pycache__/kaiju_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/__pycache__/kaiju_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea8b64c8ebcb759b10c101695a285dd2648123b3 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/__pycache__/kaiju_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/__pycache__/kaiju_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/__pycache__/kaiju_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9b5d17e3d49dfdc4a76b81e36d1a11c0759ce9d Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/__pycache__/kaiju_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/kaiju_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/kaiju_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab4f4a01aa55b00c215a77322daee8de9607fc3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/kaiju_server.py @@ -0,0 +1,862 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Literal, Union +import os +import tempfile + +# Helper function for running commands +def _run_command(cmd: List[str], cwd: Optional[str] = None) -> dict: + """ + Executes a shell command and returns its stdout, stderr, and exit code. + """ + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + cwd=cwd, + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Command '{cmd[0]}' not found. Please ensure Kaiju and its sub-tools are installed and in your PATH.", + "error": "Command not found", + "returncode": 127, + "output_files": [], + } + +# Helper for path validation +def _validate_input_file(file_path: Path, param_name: str): + if not file_path.exists(): + raise ValueError(f"Input file for '{param_name}' not found: {file_path}") + if not file_path.is_file(): + raise ValueError(f"Input path for '{param_name}' is not a file: {file_path}") + +def _validate_output_file(file_path: Path, param_name: str): + if file_path.exists() and not file_path.is_file(): + raise ValueError(f"Output path for '{param_name}' exists but is not a file: {file_path}") + if not file_path.parent.exists(): + # Attempt to create parent directory if it doesn't exist + try: + file_path.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise ValueError(f"Could not create output directory for '{param_name}': {file_path.parent}. Error: {e}") + if not os.access(file_path.parent, os.W_OK): + raise ValueError(f"Output directory for '{param_name}' is not writable: {file_path.parent}") + +def _validate_directory(dir_path: Path, param_name: str, must_exist: bool = True, must_be_writable: bool = False): + if must_exist and not dir_path.exists(): + raise ValueError(f"Directory for '{param_name}' not found: {dir_path}") + if dir_path.exists() and not dir_path.is_dir(): + raise ValueError(f"Path for '{param_name}' is not a directory: {dir_path}") + if not dir_path.exists(): + try: + dir_path.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise ValueError(f"Could not create directory for '{param_name}': {dir_path}. Error: {e}") + if must_be_writable and not os.access(dir_path, os.W_OK): + raise ValueError(f"Directory for '{param_name}' is not writable: {dir_path}") + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_kaiju' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def kaiju_classify( + nodes_dmp_file: Path, + fmi_file: Path, + input_file: Path, + second_input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + threads: int = 1, + mismatches: int = 3, + e_value: float = 0.01, + min_match_len: int = 11, + min_match_score: int = 65, + run_mode: Literal["greedy", "mem"] = "greedy", + protein_input: bool = False, + enable_seg_filter: bool = True, + verbose_output: bool = False, +) -> dict: + """ + Performs fast and sensitive taxonomic classification of high-throughput sequencing reads. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + fmi_file: Path to the Kaiju database index (.fmi) file. + input_file: Path to the input FASTQ/FASTA file for single-end reads or first mate of paired-end reads. + second_input_file: Optional path to the second input FASTQ/FASTA file for paired-end reads. + output_file: Optional path to the output file. If not provided, output will be printed to STDOUT. + threads: Number of parallel threads to use. Must be >= 1. + mismatches: Number of allowed mismatches in Greedy mode. Must be >= 0. + e_value: E-value threshold for classification in Greedy mode. Must be > 0. + min_match_len: Minimum required match length in MEM mode. Must be >= 1. + min_match_score: Minimum required match score in Greedy mode. Must be >= 0. + run_mode: The classification run mode, either 'greedy' or 'mem'. + protein_input: If True, input sequences are treated as protein sequences (disables translation). + enable_seg_filter: If True, enables filtering of query sequences containing low-complexity regions using SEG. + Enabled by default. Set to False to disable. + verbose_output: If True, enables verbose output with additional columns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(fmi_file, "fmi_file") + _validate_input_file(input_file, "input_file") + if second_input_file: + _validate_input_file(second_input_file, "second_input_file") + if output_file: + _validate_output_file(output_file, "output_file") + + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if mismatches < 0: + raise ValueError("Number of mismatches must be non-negative.") + if e_value <= 0: + raise ValueError("E-value must be greater than 0.") + if min_match_len < 1: + raise ValueError("Minimum match length must be at least 1.") + if min_match_score < 0: + raise ValueError("Minimum match score must be non-negative.") + + cmd = [ + "kaiju", + "-t", str(nodes_dmp_file), + "-f", str(fmi_file), + "-i", str(input_file), + "-z", str(threads), + ] + + if second_input_file: + cmd.extend(["-j", str(second_input_file)]) + if output_file: + cmd.extend(["-o", str(output_file)]) + + # Run mode specific options + if run_mode == "greedy": + cmd.extend(["-e", str(mismatches)]) + cmd.extend(["-E", str(e_value)]) + cmd.extend(["-s", str(min_match_score)]) + elif run_mode == "mem": + cmd.extend(["-a", "mem"]) + cmd.extend(["-m", str(min_match_len)]) + + if protein_input: + cmd.append("-p") + + # SEG filter: -x enables, -X disables. It's enabled by default. + # So, only add -X if enable_seg_filter is False. + if not enable_seg_filter: + cmd.append("-X") + + if verbose_output: + cmd.append("-v") + + result = _run_command(cmd) + if output_file and "error" not in result: + result["output_files"].append(str(output_file)) + return result + + +@mcp.tool() +def kaiju_makedb( + source_database: Literal[ + "refseq", "refseq_nr", "refseq_ref", "progenomes", "viruses", + "plasmids", "fungi", "nr", "nr_euk", "rvdb" + ], + output_dir: Path, + threads: int = 5, +) -> dict: + """ + Downloads reference databases and builds Kaiju's database index. + + Args: + source_database: The name of the reference database to download and build. + Available options: 'refseq', 'refseq_nr', 'refseq_ref', + 'progenomes', 'viruses', 'plasmids', 'fungi', 'nr', 'nr_euk', 'rvdb'. + output_dir: Directory where the database files and index will be created. + Requires at least 500 GB of free space for large databases. + threads: Number of parallel threads for index construction. A higher number + increases memory usage during construction. Must be >= 1. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_directory(output_dir, "output_dir", must_exist=False, must_be_writable=True) + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + + cmd = [ + "kaiju-makedb", + "-s", source_database, + "-t", str(threads), + ] + + # Run the command in the specified output directory + result = _run_command(cmd, cwd=str(output_dir)) + + if "error" not in result: + # Identify expected output files. + # The docs state that for "-s refseq", the index is "refseq/kaiju_db_refseq.fmi". + # This implies a subdirectory named after the source database. + db_subdir = output_dir / source_database + fmi_file = db_subdir / f"kaiju_db_{source_database}.fmi" + nodes_file = output_dir / "nodes.dmp" + names_file = output_dir / "names.dmp" + + # Check if they exist before adding + if fmi_file.exists(): + result["output_files"].append(str(fmi_file)) + if nodes_file.exists(): + result["output_files"].append(str(nodes_file)) + if names_file.exists(): + result["output_files"].append(str(names_file)) + + return result + + +@mcp.tool() +def kaiju_mkbwt( + input_fasta: Path, + output_prefix: str, + threads: int = 5, + alphabet: str = "ACDEFGHIKLMNPQRSTVWY", +) -> dict: + """ + Builds the Burrows-Wheeler Transform (BWT) for a custom protein database. + This is the first step in creating a custom Kaiju index. + + Args: + input_fasta: Path to the input FASTA file containing protein sequences. + Headers must be numeric NCBI taxon identifiers, optionally prefixed by an identifier and underscore. + output_prefix: Prefix for the output BWT and SA files (e.g., 'proteins' will create proteins.bwt, proteins.sa). + threads: Number of parallel threads to use. Must be >= 1. + alphabet: The alphabet of protein sequences. Defaults to standard 20 amino acids. + Only uppercase characters are allowed. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(input_fasta, "input_fasta") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if not alphabet.isupper() or not alphabet.isalpha(): + raise ValueError("Alphabet must contain only uppercase alphabetic characters.") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + + cmd = [ + "kaiju-mkbwt", + "-n", str(threads), + "-a", alphabet, + "-o", output_prefix, + str(input_fasta), + ] + + result = _run_command(cmd) + if "error" not in result: + # kaiju-mkbwt creates .bwt and .sa files + bwt_file = Path(f"{output_prefix}.bwt") + sa_file = Path(f"{output_prefix}.sa") + if bwt_file.exists(): + result["output_files"].append(str(bwt_file)) + if sa_file.exists(): + result["output_files"].append(str(sa_file)) + return result + + +@mcp.tool() +def kaiju_mkfmi( + input_prefix: str, +) -> dict: + """ + Builds the FM-index from BWT and SA files created by kaiju-mkbwt. + This is the second step in creating a custom Kaiju index. + + Args: + input_prefix: The prefix used for the BWT and SA files (e.g., 'proteins' + if kaiju-mkbwt created proteins.bwt and proteins.sa). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not input_prefix: + raise ValueError("Input prefix cannot be empty.") + + # Check if intermediate files exist + bwt_file = Path(f"{input_prefix}.bwt") + sa_file = Path(f"{input_prefix}.sa") + if not bwt_file.exists(): + raise ValueError(f"Required BWT file not found: {bwt_file}. Run kaiju_mkbwt first.") + if not sa_file.exists(): + raise ValueError(f"Required SA file not found: {sa_file}. Run kaiju_mkbwt first.") + + cmd = [ + "kaiju-mkfmi", + input_prefix, + ] + + result = _run_command(cmd) + if "error" not in result: + # kaiju-mkfmi creates the .fmi file + fmi_file = Path(f"{input_prefix}.fmi") + if fmi_file.exists(): + result["output_files"].append(str(fmi_file)) + return result + + +@mcp.tool() +def kaiju_multi_classify( + nodes_dmp_file: Path, + fmi_file: Path, + input_files: List[Path], + second_input_files: Optional[List[Path]] = None, + output_files: Optional[List[Path]] = None, + threads: int = 1, + mismatches: int = 3, + e_value: float = 0.01, + min_match_len: int = 11, + min_match_score: int = 65, + run_mode: Literal["greedy", "mem"] = "greedy", + protein_input: bool = False, + enable_seg_filter: bool = True, + verbose_output: bool = False, +) -> dict: + """ + Performs fast and sensitive taxonomic classification for multiple samples simultaneously. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + fmi_file: Path to the Kaiju database index (.fmi) file. + input_files: A list of paths to input FASTQ/FASTA files for single-end reads + or first mates of paired-end reads. + second_input_files: Optional list of paths to second input FASTQ/FASTA files + for paired-end reads. If provided, its length must match `input_files`. + output_files: Optional list of paths to output files. If not provided, output will be + printed to STDOUT (merged if multiple inputs). If provided, its length + must match `input_files`. + threads: Number of parallel threads to use. Must be >= 1. + mismatches: Number of allowed mismatches in Greedy mode. Must be >= 0. + e_value: E-value threshold for classification in Greedy mode. Must be > 0. + min_match_len: Minimum required match length in MEM mode. Must be >= 1. + min_match_score: Minimum required match score in Greedy mode. Must be >= 0. + run_mode: The classification run mode, either 'greedy' or 'mem'. + protein_input: If True, input sequences are treated as protein sequences (disables translation). + enable_seg_filter: If True, enables filtering of query sequences containing low-complexity regions using SEG. + Enabled by default. Set to False to disable. + verbose_output: If True, enables verbose output with additional columns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(fmi_file, "fmi_file") + + if not input_files: + raise ValueError("At least one input file must be provided.") + for f in input_files: + _validate_input_file(f, "input_files") + + if second_input_files: + if len(input_files) != len(second_input_files): + raise ValueError("Number of first input files must match number of second input files.") + for f in second_input_files: + _validate_input_file(f, "second_input_files") + + if output_files: + if len(input_files) != len(output_files): + raise ValueError("Number of input files must match number of output files.") + for f in output_files: + _validate_output_file(f, "output_files") + + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if mismatches < 0: + raise ValueError("Number of mismatches must be non-negative.") + if e_value <= 0: + raise ValueError("E-value must be greater than 0.") + if min_match_len < 1: + raise ValueError("Minimum match length must be at least 1.") + if min_match_score < 0: + raise ValueError("Minimum match score must be non-negative.") + + cmd = [ + "kaiju-multi", + "-t", str(nodes_dmp_file), + "-f", str(fmi_file), + "-i", ",".join(str(p) for p in input_files), + "-z", str(threads), + ] + + if second_input_files: + cmd.extend(["-j", ",".join(str(p) for p in second_input_files)]) + if output_files: + cmd.extend(["-o", ",".join(str(p) for p in output_files)]) + + # Run mode specific options + if run_mode == "greedy": + cmd.extend(["-e", str(mismatches)]) + cmd.extend(["-E", str(e_value)]) + cmd.extend(["-s", str(min_match_score)]) + elif run_mode == "mem": + cmd.extend(["-a", "mem"]) + cmd.extend(["-m", str(min_match_len)]) + + if protein_input: + cmd.append("-p") + + if not enable_seg_filter: + cmd.append("-X") + + if verbose_output: + cmd.append("-v") + + result = _run_command(cmd) + if output_files and "error" not in result: + result["output_files"].extend([str(f) for f in output_files]) + return result + + +@mcp.tool() +def kaiju2krona( + nodes_dmp_file: Path, + names_dmp_file: Path, + input_kaiju_output: Path, + output_krona_file: Path, + print_full_taxon_path: bool = False, +) -> dict: + """ + Converts Kaiju's tab-separated output file into a Krona-compatible text file. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + names_dmp_file: Path to the NCBI taxonomy names.dmp file. + input_kaiju_output: Path to the Kaiju classification output file. + output_krona_file: Path to the output Krona-compatible text file. + print_full_taxon_path: If True, print the full taxon path instead of just the taxon name. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(names_dmp_file, "names_dmp_file") + _validate_input_file(input_kaiju_output, "input_kaiju_output") + _validate_output_file(output_krona_file, "output_krona_file") + + cmd = [ + "kaiju2krona", + "-t", str(nodes_dmp_file), + "-n", str(names_dmp_file), + "-i", str(input_kaiju_output), + "-o", str(output_krona_file), + ] + + if print_full_taxon_path: + cmd.append("-l") # The doc says -l for kaiju2krona prints full path. + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_krona_file)) + return result + + +@mcp.tool() +def kaiju2table( + nodes_dmp_file: Path, + names_dmp_file: Path, + taxonomic_rank: str, + output_summary_file: Path, + input_kaiju_outputs: List[Path], + min_percentage: float = 0.0, + min_count: int = 0, + exclude_unclassified: bool = False, + print_full_taxon_path: bool = False, + specific_ranks_for_path: Optional[List[str]] = None, +) -> dict: + """ + Converts Kaiju's output file(s) into a summary table for a given taxonomic rank. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + names_dmp_file: Path to the NCBI taxonomy names.dmp file. + taxonomic_rank: The taxonomic rank for which to create the summary table (e.g., 'genus', 'species'). + output_summary_file: Path to the output summary table file (TSV format). + input_kaiju_outputs: A list of paths to one or more Kaiju classification output files. + min_percentage: Minimum percentage of total reads for a taxon to be included in the summary. Must be >= 0.0. + min_count: Minimum absolute read count for a taxon to be included in the summary. Must be >= 0. + exclude_unclassified: If True, unclassified reads are not counted towards the total + when calculating percentages. + print_full_taxon_path: If True, print the full taxon path instead of just the taxon name. + specific_ranks_for_path: Optional list of specific ranks to print in the taxon path + (e.g., ['superkingdom', 'phylum', 'class']). Overrides `print_full_taxon_path` if set. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(names_dmp_file, "names_dmp_file") + _validate_output_file(output_summary_file, "output_summary_file") + if not input_kaiju_outputs: + raise ValueError("At least one Kaiju output file must be provided.") + for f in input_kaiju_outputs: + _validate_input_file(f, "input_kaiju_outputs") + + if min_percentage < 0.0: + raise ValueError("Minimum percentage must be non-negative.") + if min_count < 0: + raise ValueError("Minimum count must be non-negative.") + if not taxonomic_rank: + raise ValueError("Taxonomic rank cannot be empty.") + + cmd = [ + "kaiju2table", + "-t", str(nodes_dmp_file), + "-n", str(names_dmp_file), + "-r", taxonomic_rank, + "-o", str(output_summary_file), + ] + cmd.extend([str(f) for f in input_kaiju_outputs]) + + if min_percentage > 0.0: + cmd.extend(["-m", str(min_percentage)]) + if min_count > 0: + cmd.extend(["-c", str(min_count)]) + if exclude_unclassified: + cmd.append("-u") + + if specific_ranks_for_path: + cmd.extend(["-l", ",".join(specific_ranks_for_path)]) + elif print_full_taxon_path: + cmd.append("-p") + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_summary_file)) + return result + + +@mcp.tool() +def kaiju_add_taxon_names( + nodes_dmp_file: Path, + names_dmp_file: Path, + input_kaiju_output: Path, + output_file_with_names: Path, + omit_unclassified_reads: bool = False, + print_full_taxon_path: bool = False, + specific_ranks_for_path: Optional[List[str]] = None, +) -> dict: + """ + Appends taxon names or full taxon paths to Kaiju's output file. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + names_dmp_file: Path to the NCBI taxonomy names.dmp file. + input_kaiju_output: Path to the Kaiju classification output file. + output_file_with_names: Path to the output file with appended taxon names/paths. + omit_unclassified_reads: If True, unclassified reads will be omitted from the output. + print_full_taxon_path: If True, print the full taxon path instead of just the taxon name. + specific_ranks_for_path: Optional list of specific ranks to print in the path + (e.g., ['phylum', 'genus']). Overrides `print_full_taxon_path` if set. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(names_dmp_file, "names_dmp_file") + _validate_input_file(input_kaiju_output, "input_kaiju_output") + _validate_output_file(output_file_with_names, "output_file_with_names") + + cmd = [ + "kaiju-addTaxonNames", + "-t", str(nodes_dmp_file), + "-n", str(names_dmp_file), + "-i", str(input_kaiju_output), + "-o", str(output_file_with_names), + ] + + if omit_unclassified_reads: + cmd.append("-u") + + if specific_ranks_for_path: + cmd.extend(["-r", ",".join(specific_ranks_for_path)]) + elif print_full_taxon_path: + cmd.append("-p") + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_file_with_names)) + return result + + +@mcp.tool() +def kaiju_merge_outputs( + input_file1: Path, + input_file2: Path, + output_merged_file: Path, + verbose_output: bool = False, + conflict_strategy: Literal["1", "2", "lca", "lowest"] = "lca", + nodes_dmp_file: Optional[Path] = None, + precedence_by_score: bool = False, +) -> dict: + """ + Merges two tab-separated output files (Kaiju or Kraken format) based on read names. + Input files must be sorted by read name (e.g., using `sort -k2,2`). + + Args: + input_file1: Path to the first sorted input file. + input_file2: Path to the second sorted input file. + output_merged_file: Path to the output merged file. + verbose_output: If True, prints all columns from input files (otherwise only first three). + conflict_strategy: Strategy to resolve conflicting taxon identifiers for a classified read: + '1': Use taxon identifier from the first input file. + '2': Use taxon identifier from the second input file. + 'lca': Use the least common ancestor of the taxon identifiers (default). + 'lowest': Use the lowest ranking of the two taxon identifiers if they are + within the same lineage, otherwise use LCA. + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. Required if `conflict_strategy` + is 'lca' or 'lowest'. + precedence_by_score: If True, gives precedence to the classification result with the higher score + (requires 4th column in input files). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(input_file1, "input_file1") + _validate_input_file(input_file2, "input_file2") + _validate_output_file(output_merged_file, "output_merged_file") + + if conflict_strategy in ["lca", "lowest"] and not nodes_dmp_file: + raise ValueError(f"nodes_dmp_file is required when conflict_strategy is '{conflict_strategy}'.") + if nodes_dmp_file: + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + + cmd = [ + "kaiju-mergeOutputs", + "-i", str(input_file1), + "-j", str(input_file2), + "-o", str(output_merged_file), + "-c", conflict_strategy, + ] + + if nodes_dmp_file: + cmd.extend(["-t", str(nodes_dmp_file)]) + if verbose_output: + cmd.append("-v") + if precedence_by_score: + cmd.append("-s") + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_merged_file)) + return result + + +@mcp.tool() +def kaijux_search( + fmi_file: Path, + input_file: Path, + second_input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + threads: int = 1, + mismatches: int = 3, + e_value: float = 0.01, + min_match_len: int = 11, + min_match_score: int = 65, + run_mode: Literal["greedy", "mem"] = "greedy", + enable_seg_filter: bool = True, + verbose_output: bool = False, +) -> dict: + """ + Searches translated nucleotide reads against a protein database without taxonomic classification. + Prints the name of the best matching database sequence. + + Args: + fmi_file: Path to the Kaiju database index (.fmi) file. + input_file: Path to the input FASTQ/FASTA file for single-end reads or first mate of paired-end reads. + (Nucleotide sequences). + second_input_file: Optional path to the second input FASTQ/FASTA file for paired-end reads. + output_file: Optional path to the output file. If not provided, output will be printed to STDOUT. + threads: Number of parallel threads to use. Must be >= 1. + mismatches: Number of allowed mismatches in Greedy mode. Must be >= 0. + e_value: E-value threshold for classification in Greedy mode. Must be > 0. + min_match_len: Minimum required match length in MEM mode. Must be >= 1. + min_match_score: Minimum required match score in Greedy mode. Must be >= 0. + run_mode: The classification run mode, either 'greedy' or 'mem'. + enable_seg_filter: If True, enables filtering of query sequences containing low-complexity regions using SEG. + Enabled by default. Set to False to disable. + verbose_output: If True, enables verbose output with additional columns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + _validate_input_file(fmi_file, "fmi_file") + _validate_input_file(input_file, "input_file") + if second_input_file: + _validate_input_file(second_input_file, "second_input_file") + if output_file: + _validate_output_file(output_file, "output_file") + + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if mismatches < 0: + raise ValueError("Number of mismatches must be non-negative.") + if e_value <= 0: + raise ValueError("E-value must be greater than 0.") + if min_match_len < 1: + raise ValueError("Minimum match length must be at least 1.") + if min_match_score < 0: + raise ValueError("Minimum match score must be non-negative.") + + cmd = [ + "kaijux", + "-f", str(fmi_file), + "-i", str(input_file), + "-z", str(threads), + ] + + if second_input_file: + cmd.extend(["-j", str(second_input_file)]) + if output_file: + cmd.extend(["-o", str(output_file)]) + + # Run mode specific options + if run_mode == "greedy": + cmd.extend(["-e", str(mismatches)]) + cmd.extend(["-E", str(e_value)]) + cmd.extend(["-s", str(min_match_score)]) + elif run_mode == "mem": + cmd.extend(["-a", "mem"]) + cmd.extend(["-m", str(min_match_len)]) + + if not enable_seg_filter: + cmd.append("-X") + + if verbose_output: + cmd.append("-v") + + result = _run_command(cmd) + if output_file and "error" not in result: + result["output_files"].append(str(output_file)) + return result + + +@mcp.tool() +def kaijup_search( + fmi_file: Path, + input_file: Path, + second_input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + threads: int = 1, + mismatches: int = 3, + e_value: float = 0.01, + min_match_len: int = 11, + min_match_score: int = 65, + run_mode: Literal["greedy", "mem"] = "greedy", + enable_seg_filter: bool = True, + verbose_output: bool = False, +) -> dict: + """ + Searches protein queries against a protein database without taxonomic classification. + Prints the name of the best matching database sequence. + + Args: + fmi_file: Path to the Kaiju database index (.fmi) file. + input_file: Path to the input FASTA file for single-end protein queries or first mate of paired-end. + second_input_file: Optional path to the second input FASTA file for paired-end protein queries. + output_file: Optional path to the output file. If not provided, output will be printed to STDOUT. + threads: Number of parallel threads to use. Must be >= 1. + mismatches: Number of allowed mismatches in Greedy mode. Must be >= 0. + e_value: E-value threshold for classification in Greedy mode. Must be > 0. + min_match_len: Minimum required match length in MEM mode. Must be >= 1. + min_match_score: Minimum required match score in Greedy mode. Must be >= 0. + run_mode: The classification run mode, either 'greedy' or 'mem'. + enable_seg_filter: If True, enables filtering of query sequences containing low-complexity regions using SEG. + Enabled by default. Set to False to disable. + verbose_output: If True, enables verbose output with additional columns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + _validate_input_file(fmi_file, "fmi_file") + _validate_input_file(input_file, "input_file") + if second_input_file: + _validate_input_file(second_input_file, "second_input_file") + if output_file: + _validate_output_file(output_file, "output_file") + + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if mismatches < 0: + raise ValueError("Number of mismatches must be non-negative.") + if e_value <= 0: + raise ValueError("E-value must be greater than 0.") + if min_match_len < 1: + raise ValueError("Minimum match length must be at least 1.") + if min_match_score < 0: + raise ValueError("Minimum match score must be non-negative.") + + cmd = [ + "kaijup", + "-f", str(fmi_file), + "-i", str(input_file), + "-z", str(threads), + ] + + if second_input_file: + cmd.extend(["-j", str(second_input_file)]) + if output_file: + cmd.extend(["-o", str(output_file)]) + + # Run mode specific options + if run_mode == "greedy": + cmd.extend(["-e", str(mismatches)]) + cmd.extend(["-E", str(e_value)]) + cmd.extend(["-s", str(min_match_score)]) + elif run_mode == "mem": + cmd.extend(["-a", "mem"]) + cmd.extend(["-m", str(min_match_len)]) + + if not enable_seg_filter: + cmd.append("-X") + + if verbose_output: + cmd.append("-v") + + result = _run_command(cmd) + if output_file and "error" not in result: + result["output_files"].append(str(output_file)) + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/kaiju_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/kaiju_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..253ae04ee856435f1bb042770ad37e0613d9f859 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/kaiju_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/kaiju_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_kaiju' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a1ad5b20456123671a7101563711cad806372e4c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kaiju: + build: . + image: mcp-kaiju:latest + container_name: mcp-kaiju + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kaiju + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68716f85534f2bc339b296d5dad3f29d3b5c87be --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kaiju + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kaiju/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d817ef4d35cdea14a55f427149a015850feb8d09 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kalign2 via conda (e.g., from bioconda) +RUN conda install -c bioconda kalign2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kalign2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kalign2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kalign2_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/__pycache__/kalign2_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/__pycache__/kalign2_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..977ca962db6595f5232a80aa72a0c49282390d25 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/__pycache__/kalign2_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/kalign2_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/kalign2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3719c36752648af957db19290e1bba6490216be2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/kalign2_server.py @@ -0,0 +1,118 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_kalign2' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def kalign2_align( + input_fasta: Path, + output_fasta: Path, +) -> Dict[str, Any]: + """ + Performs multiple sequence alignment using kalign2. + + This function aligns protein or DNA/RNA sequences from an input FASTA file + and writes the alignment to an output FASTA file. + + NOTE: The provided documentation for kalign2 (web docs extract and conda info) + did not include detailed command-line help or manual pages. Therefore, this + implementation assumes the most basic usage pattern: `kalign2 ` + which typically prints the alignment to standard output. The output is then + redirected to the specified `output_fasta` file. + + No specific parameters for gap penalties, scoring matrices, sequence type, + or output format could be extracted from the provided documentation. + A more comprehensive MCP tool would require the full `--help` output + or a detailed manual page for kalign2 to expose these options. + + Args: + input_fasta: Path to the input FASTA file containing sequences to align. + This file must exist and be readable. + output_fasta: Path to the output FASTA file where the aligned sequences + will be written. This file will be created or overwritten. + The parent directory will be created if it does not exist. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + a list of generated output files. + + Raises: + ValueError: If `input_fasta` does not exist or is not a file. + subprocess.CalledProcessError: If kalign2 execution fails with a non-zero exit code. + FileNotFoundError: If the `kalign2` executable is not found in the system's PATH. + """ + # Input validation + if not isinstance(input_fasta, Path): + raise TypeError(f"input_fasta must be a Path object, got {type(input_fasta)}") + if not input_fasta.is_file(): + raise ValueError(f"Input FASTA file not found or is not a file: {input_fasta}") + + if not isinstance(output_fasta, Path): + raise TypeError(f"output_fasta must be a Path object, got {type(output_fasta)}") + + # Ensure output directory exists + output_fasta.parent.mkdir(parents=True, exist_ok=True) + + command = ["kalign2", str(input_fasta)] + + stdout_content = "" + stderr_content = "" + output_files: List[Path] = [] + + try: + # Execute kalign2. Assuming it prints the alignment to stdout by default. + # Redirect stdout to the specified output_fasta file. + with open(output_fasta, "w") as outfile: + process = subprocess.run( + command, + stdout=outfile, # Redirect stdout to the output file + stderr=subprocess.PIPE, + check=True, + text=True, + encoding="utf-8", + ) + + # Since stdout is redirected, process.stdout will be empty. + # We provide a descriptive message for stdout_content. + stdout_content = f"Alignment successfully written to {output_fasta}" + stderr_content = process.stderr + output_files.append(output_fasta) + + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "kalign2 executable not found. Please ensure it is installed and in your system's PATH.", + "output_files": [], + "error": "kalign2 executable not found.", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, # This will be empty if stdout was redirected + "stderr": e.stderr, + "output_files": [], + "error": f"kalign2 execution failed with exit code {e.returncode}. Stderr: {e.stderr}", + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": stdout_content, + "stderr": stderr_content, + "output_files": [], + "error": f"An unexpected error occurred during kalign2 execution: {str(e)}", + } + + return { + "command_executed": " ".join(command), + "stdout": stdout_content, + "stderr": stderr_content, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/kalign2_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/kalign2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9ac3316e31aac800e6eb4ff555b4f3e5dc863d6c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/kalign2_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/kalign2_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_kalign2' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d051ea54c55891614f7f2b8586113f748cf13278 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kalign2: + build: . + image: mcp-kalign2:latest + container_name: mcp-kalign2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kalign2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8cb94499dd106cee9e6d985c91ed3388171d77ee --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kalign2 + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kalign2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..048ebcc61c1a8d3b158d40d450cd92b24573b7c0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kb-python via conda (e.g., from bioconda) +RUN conda install -c bioconda kb-python -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY kb-python_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kb-python_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kb-python_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/app/__pycache__/kb-python_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/app/__pycache__/kb-python_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d78a75327b632bd5da1d1e0b679e3a9cb933cb69 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/app/__pycache__/kb-python_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/app/kb-python_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/app/kb-python_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2d9ed1e807cd26ed40366df647ebf6ba879f6f5a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/app/kb-python_server.py @@ -0,0 +1,306 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import os + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_kb_python' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def kb_info(): + """ + Display kb-python package and citation information, including versions of + kallisto and bustools and their installation locations. + """ + cmd = ["kb", "info"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_list(): + """ + List all supported single-cell technologies/assays for kb-python. + """ + cmd = ["kb", "--list"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_compile(): + """ + Compile kallisto and bustools binaries from source. + Note: This is usually not required as binaries are included with the package. + """ + cmd = ["kb", "compile"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_ref( + index_path: str, + t2g_path: str, + fasta_path: Optional[str] = None, + species: Optional[str] = None, + genome_fasta: Optional[str] = None, + genome_annotation: Optional[str] = None, + workflow: str = "standard", + feature_barcodes: Optional[str] = None, + tmp_dir: Optional[str] = None, + keep_tmp: bool = False, + overwrite: bool = False +): + """ + Build a kallisto index and transcript-to-gene mapping. + + Args: + index_path: Path to the generated index file. + t2g_path: Path to the generated transcript-to-gene mapping file. + fasta_path: Path to the generated transcriptome FASTA file. + species: Species name to download pre-built reference (e.g., 'human', 'mouse'). + genome_fasta: Path to the genome FASTA file (required if species is not provided). + genome_annotation: Path to the genome GTF file (required if species is not provided). + workflow: The workflow to use (standard, lamanno, nucleus, kite). Default is 'standard'. + feature_barcodes: Path to the feature barcodes file (required for 'kite' workflow). + tmp_dir: Path to temporary directory. + keep_tmp: Whether to keep temporary files. + overwrite: Whether to overwrite existing files. + """ + cmd = ["kb", "ref", "-i", index_path, "-g", t2g_path] + + if fasta_path: + cmd.extend(["-f1", fasta_path]) + if species: + cmd.extend(["-d", species]) + if workflow != "standard": + cmd.extend(["--workflow", workflow]) + if tmp_dir: + cmd.extend(["--tmp", tmp_dir]) + if keep_tmp: + cmd.append("--keep-tmp") + if overwrite: + cmd.append("--overwrite") + + # Positional arguments handling + if workflow == "kite": + if not feature_barcodes: + return {"error": "feature_barcodes is required for kite workflow"} + if not Path(feature_barcodes).exists(): + return {"error": f"Feature barcodes file not found: {feature_barcodes}"} + cmd.append(feature_barcodes) + elif not species: + if not genome_fasta or not genome_annotation: + return {"error": "genome_fasta and genome_annotation are required if species is not provided"} + if not Path(genome_fasta).exists(): + return {"error": f"Genome FASTA not found: {genome_fasta}"} + if not Path(genome_annotation).exists(): + return {"error": f"Genome annotation not found: {genome_annotation}"} + cmd.extend([genome_fasta, genome_annotation]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [index_path, t2g_path] + ([fasta_path] if fasta_path else []) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_count( + index_path: str, + t2g_path: str, + output_dir: str, + technology: str, + fastqs: List[str], + workflow: str = "standard", + h5ad: bool = False, + loom: bool = False, + tcc: bool = False, + mm: bool = False, + filter: bool = False, + tmp_dir: Optional[str] = None, + keep_tmp: bool = False, + overwrite: bool = False, + threads: int = 8 +): + """ + Generate count matrices from a set of single-cell FASTQ files. + + Args: + index_path: Path to the kallisto index. + t2g_path: Path to the transcript-to-gene mapping. + output_dir: Directory where output files will be saved. + technology: Single-cell technology used (e.g., 10xv3, 10xv2, dropseq, etc.). + fastqs: List of paths to FASTQ files. + workflow: The workflow to use (standard, lamanno, nucleus, kite). Default is 'standard'. + h5ad: Export result as h5ad file. + loom: Export result as loom file. + tcc: Generate a TCC (Transcript Compatibility Count) matrix. + mm: Include multi-mapping reads. + filter: Filter the count matrix (bustools filter). + tmp_dir: Path to temporary directory. + keep_tmp: Whether to keep temporary files. + overwrite: Whether to overwrite existing files in the output directory. + threads: Number of threads to use. Default is 8. + """ + # Validation + if not Path(index_path).exists(): + return {"error": f"Index file not found: {index_path}"} + if not Path(t2g_path).exists(): + return {"error": f"T2G file not found: {t2g_path}"} + for f in fastqs: + if not Path(f).exists(): + return {"error": f"FASTQ file not found: {f}"} + + cmd = [ + "kb", "count", + "-i", index_path, + "-g", t2g_path, + "-o", output_dir, + "-x", technology, + "-t", str(threads) + ] + + if workflow != "standard": + cmd.extend(["--workflow", workflow]) + if h5ad: + cmd.append("--h5ad") + if loom: + cmd.append("--loom") + if tcc: + cmd.append("--tcc") + if mm: + cmd.append("--mm") + if filter: + cmd.append("--filter") + if tmp_dir: + cmd.extend(["--tmp", tmp_dir]) + if keep_tmp: + cmd.append("--keep-tmp") + if overwrite: + cmd.append("--overwrite") + + cmd.extend(fastqs) + + try: + # Ensure output directory exists or will be created by kb + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Identify potential output files based on flags + output_files = [str(p) for p in Path(output_dir).rglob("*") if p.is_file()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_dir": output_dir, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_extract( + index_path: str, + output_path: str, + bus_path: str, + tmp_dir: Optional[str] = None, + keep_tmp: bool = False +): + """ + Extract reads that were pseudoaligned to specific genes/transcripts + (or extract all reads that were / were not pseudoaligned). + + Args: + index_path: Path to the kallisto index. + output_path: Path to the output BUS file. + bus_path: Path to the input BUS file. + tmp_dir: Path to temporary directory. + keep_tmp: Whether to keep temporary files. + """ + if not Path(index_path).exists(): + return {"error": f"Index file not found: {index_path}"} + if not Path(bus_path).exists(): + return {"error": f"Input BUS file not found: {bus_path}"} + + cmd = [ + "kb", "extract", + "-i", index_path, + "-o", output_path + ] + + if tmp_dir: + cmd.extend(["--tmp", tmp_dir]) + if keep_tmp: + cmd.append("--keep-tmp") + + cmd.append(bus_path) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/app/kb-python_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/app/kb-python_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..97369ff5ad339568d1f47e8005a12f155946598b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/app/kb-python_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/app/kb-python_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_kb_python' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..56e365874d51c5a442ac56d8855d3c3ad27294df --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kb-python: + build: . + image: mcp-kb-python:latest + container_name: mcp-kb-python + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kb-python + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07df37c2c49abd1de0da3095ac1fd6d1d21ec872 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kb-python + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kb-python/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kma/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kma/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kma/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5cc2d4d814c1452c2c850d0f9ad86514efabe576 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kmc via conda (e.g., from bioconda) +RUN conda install -c bioconda kmc -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kmc_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kmc_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kmc_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/__pycache__/kmc_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/__pycache__/kmc_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..978a03f07db6cb9b377bcd0f4c4b89125830adab Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/__pycache__/kmc_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/kmc_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/kmc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..963b3c3b840403adde98775518ab0a6eca78ff63 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/kmc_server.py @@ -0,0 +1,219 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# @mcp.tool() decorator is not needed in the final code, as per instructions. +# This is a placeholder for the MCP environment. +def tool_decorator(func): + return func + +@tool_decorator +def kmc( + input_path: Path, + output_prefix: Path, + working_directory: Path, + verbose: bool = False, + kmer_length: int = 25, + max_ram_gb: int = 12, + strict_memory: bool = False, + homopolymer_compressed: bool = False, + signature_length: int = 9, + input_format: str = "q", + min_count: int = 2, + max_count: int = 255, + max_count_high: float = 1e9, + no_canonical: bool = False, + ram_only: bool = False, + num_bins: Optional[int] = None, + threads: Optional[int] = None, + fastq_threads: Optional[int] = None, + splitting_threads: Optional[int] = None, + stage2_threads: Optional[int] = None, + json_summary: Optional[Path] = None, + without_output: bool = False, + output_format: str = "kmc", + hide_progress: bool = False, + estimate_only: bool = False, + optimize_output_size: bool = False, +): + """ + Counts k-mers from sequence data using KMC (K-Mer Counter). + + This tool takes a sequence file (or a list of files) and counts the occurrences + of k-mers of a specified length. The results are stored in a KMC database. + + Args: + input_path: Path to a single input file or a file containing a list of + input files (prefixed with '@'). + output_prefix: The path and prefix for the output database files. + KMC will create .kmc_pre and .kmc_suf. + working_directory: Path to a directory for temporary files. + verbose: Show all parameter settings. + kmer_length: K-mer length (k from 1 to 256). + max_ram_gb: Max amount of RAM in GB (from 1 to 1024). + strict_memory: Use strict memory mode (memory limit will not be exceeded). + homopolymer_compressed: Count homopolymer compressed k-mers (experimental). + signature_length: Signature length (5-11). + input_format: Input format: 'a' (FASTA), 'q' (FASTQ), 'm' (multi FASTA), + 'bam' (BAM), or 'kmc' (KMC). + min_count: Exclude k-mers occurring less than this value. + max_count: Maximal value of a counter. + max_count_high: Exclude k-mers occurring more than this value. + no_canonical: Turn off transformation of k-mers into canonical form. + ram_only: Turn on RAM-only mode. + num_bins: Number of bins. + threads: Total number of threads. + fastq_threads: Number of FASTQ reading threads. + splitting_threads: Number of splitting threads. + stage2_threads: Number of threads for the 2nd stage. + json_summary: Path to save the execution summary in JSON format. + without_output: Do not generate output files. + output_format: Output format: 'kmc' or 'kff'. + hide_progress: Hide percentage progress. + estimate_only: Only estimate histogram of k-mers occurrences. + optimize_output_size: Optimize output database size (may increase running time). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_path}") + + if not (1 <= kmer_length <= 256): + raise ValueError("k-mer length must be between 1 and 256.") + + if not (1 <= max_ram_gb <= 1024): + raise ValueError("Max RAM must be between 1 and 1024 GB.") + + if signature_length not in [5, 6, 7, 8, 9, 10, 11]: + raise ValueError("Signature length must be one of: 5, 6, 7, 8, 9, 10, 11.") + + valid_input_formats = ['a', 'q', 'm', 'bam', 'kmc'] + if input_format not in valid_input_formats: + raise ValueError(f"Input format must be one of: {valid_input_formats}") + + valid_output_formats = ['kmc', 'kff'] + if output_format not in valid_output_formats: + raise ValueError(f"Output format must be one of: {valid_output_formats}") + + if min_count < 1: + raise ValueError("min_count must be a positive integer.") + if max_count < 1: + raise ValueError("max_count must be a positive integer.") + if max_count_high < 1: + raise ValueError("max_count_high must be a positive number.") + + if num_bins is not None and num_bins < 1: + raise ValueError("num_bins must be a positive integer.") + if threads is not None and threads < 1: + raise ValueError("threads must be a positive integer.") + if fastq_threads is not None and fastq_threads < 1: + raise ValueError("fastq_threads must be a positive integer.") + if splitting_threads is not None and splitting_threads < 1: + raise ValueError("splitting_threads must be a positive integer.") + if stage2_threads is not None and stage2_threads < 1: + raise ValueError("stage2_threads must be a positive integer.") + + # --- Path Handling --- + working_directory.mkdir(parents=True, exist_ok=True) + output_prefix.parent.mkdir(parents=True, exist_ok=True) + if json_summary: + json_summary.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = ["kmc"] + + # Boolean flags + if verbose: + cmd.append("-v") + if strict_memory: + cmd.append("-sm") + if homopolymer_compressed: + cmd.append("-hc") + if no_canonical: + cmd.append("-b") + if ram_only: + cmd.append("-r") + if without_output: + cmd.append("-w") + if hide_progress: + cmd.append("-hp") + if estimate_only: + cmd.append("-e") + if optimize_output_size: + cmd.append("--opt-out-size") + + # Parameters with values + cmd.append(f"-k{kmer_length}") + cmd.append(f"-m{max_ram_gb}") + cmd.append(f"-p{signature_length}") + cmd.append(f"-f{input_format}") + cmd.append(f"-ci{min_count}") + cmd.append(f"-cs{max_count}") + cmd.append(f"-cx{max_count_high}") + cmd.append(f"-o{output_format}") + + # Optional parameters + if num_bins is not None: + cmd.append(f"-n{num_bins}") + if threads is not None: + cmd.append(f"-t{threads}") + if fastq_threads is not None: + cmd.append(f"-sf{fastq_threads}") + if splitting_threads is not None: + cmd.append(f"-sp{splitting_threads}") + if stage2_threads is not None: + cmd.append(f"-sr{stage2_threads}") + if json_summary is not None: + cmd.append(f"-j{json_summary}") + + # Positional arguments + cmd.extend([str(input_path), str(output_prefix), str(working_directory)]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [], + } + + # --- Structured Result Return --- + output_files = [] + if not without_output and not estimate_only: + # KMC creates two files for its database + db_prefix = output_prefix.with_suffix(f".{output_prefix.name}.kmc_pre") + db_suffix = output_prefix.with_suffix(f".{output_prefix.name}.kmc_suf") + + # A more robust way to handle output naming + final_prefix_path = output_prefix.parent / output_prefix.name + + out_pre = Path(f"{final_prefix_path}.kmc_pre") + out_suf = Path(f"{final_prefix_path}.kmc_suf") + + if out_pre.exists(): + output_files.append(str(out_pre)) + if out_suf.exists(): + output_files.append(str(out_suf)) + + if json_summary and json_summary.exists(): + output_files.append(str(json_summary)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/kmc_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/kmc_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7bba7c2515eddc2b4eb01e9247d4ef672bd1b6cf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/kmc_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/kmc_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_kmc' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..658aff4b79b367241fc6a6af7a63fc11c25e8e5f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kmc: + build: . + image: mcp-kmc:latest + container_name: mcp-kmc + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kmc + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bda0bbaf0996d1c62bdb166aba0ed5f2b99cda9b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kmc + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kmc/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9f0143f267bb44f451955f52413a42f18489fe8f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kraken2 via conda (e.g., from bioconda) +RUN conda install -c bioconda kraken2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kraken2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kraken2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kraken2_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/__pycache__/kraken2_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/__pycache__/kraken2_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4dcb06cbeb0d871efef60b71e73797b8556d12d Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/__pycache__/kraken2_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/__pycache__/kraken2_server.cpython-313.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/__pycache__/kraken2_server.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57b5ba8b7b744e4b6c9b9f163c3e352a2f54d341 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/__pycache__/kraken2_server.cpython-313.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/__pycache__/kraken2_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/__pycache__/kraken2_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5df03858a35466f08fe01dc9c36400086ee0982f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/__pycache__/kraken2_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/kraken2_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/kraken2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..34a55266758deb6290c30cb5975a2c7749b6bf7a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/kraken2_server.py @@ -0,0 +1,460 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Helper function for running subprocesses +def _run_command(cmd: List[str], cwd: Optional[Path] = None) -> Dict[str, Any]: + """ + Executes a shell command and returns its output. + """ + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=cwd + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], # This will be populated by the tool functions + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Command '{cmd[0]}' not found. Is Kraken2 installed and in your PATH?", + "error": "Command not found", + "output_files": [], + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_kraken2' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def kraken2_classify( + database: Path, + input_files: List[Path], + output_file: Optional[Path] = None, + report_file: Optional[Path] = None, + threads: int = 1, + paired: bool = False, + unclassified_out: Optional[Path] = None, + classified_out: Optional[Path] = None, + confidence: float = 0.0, + minimum_hit_groups: int = 2, + quick: bool = False, + use_mpa_style: bool = False, + gzip_compressed: bool = False, + bzip2_compressed: bool = False, + memory_mapping: bool = False, + preload_db: bool = False, + report_zero_counts: bool = False, + report_minimizer_data: bool = False, + skip_classified: bool = False, + skip_unclassified: bool = False, + scientific_name_output: bool = False, + taxid_output: bool = False, + kmer_len: Optional[int] = None, + minimizer_len: Optional[int] = None, + minimizer_spaces: Optional[int] = None, +) -> Dict[str, Any]: + """ + Classifies metagenomic reads using Kraken2. + + Args: + database: Path to the Kraken2 database directory. + input_files: List of input FASTA/FASTQ files. For paired-end reads, provide + R1 files followed by R2 files (e.g., [R1_1, R1_2, ..., R2_1, R2_2, ...]). + output_file: Path for the Kraken2 classification output. If not provided, + output goes to stdout. + report_file: Path for the Kraken2 report file. + threads: Number of threads to use for classification. Must be at least 1. + paired: Set to True if input_files contain paired-end reads. + unclassified_out: Path to write unclassified reads. + classified_out: Path to write classified reads. + confidence: Confidence score threshold (0.0-1.0). + minimum_hit_groups: Minimum number of hit groups required for a classification. Must be at least 1. + quick: Enable quick classification mode. + use_mpa_style: Report output in MPA-style format. + gzip_compressed: Assume input files are gzip compressed. + bzip2_compressed: Assume input files are bzip2 compressed. + memory_mapping: Use memory mapping for database. + preload_db: Preload database into RAM. + report_zero_counts: Include taxa with zero counts in the report. + report_minimizer_data: Include minimizer data in the report. + skip_classified: Do not output classified reads. + skip_unclassified: Do not output unclassified reads. + scientific_name_output: Output scientific names instead of taxids in classification. + taxid_output: Output taxids instead of names in classification. + kmer_len: Override k-mer length from database. Must be positive if provided. + minimizer_len: Override minimizer length from database. Must be positive if provided. + minimizer_spaces: Override minimizer spaces from database. Must be non-negative if provided. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not database.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Database directory '{database}' not found or is not a directory.", + "error": "Invalid database path", + "output_files": [], + } + + if not input_files: + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: No input files provided.", + "error": "Missing input files", + "output_files": [], + } + + for f in input_files: + if not f.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Input file '{f}' not found or is not a file.", + "error": "Invalid input file path", + "output_files": [], + } + + if paired and len(input_files) % 2 != 0: + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: For paired-end reads, an even number of input files is required.", + "error": "Mismatched paired-end files", + "output_files": [], + } + + if threads < 1: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Number of threads must be at least 1, got {threads}.", + "error": "Invalid threads count", + "output_files": [], + } + + if not (0.0 <= confidence <= 1.0): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Confidence score must be between 0.0 and 1.0, got {confidence}.", + "error": "Invalid confidence score", + "output_files": [], + } + + if minimum_hit_groups < 1: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Minimum hit groups must be at least 1, got {minimum_hit_groups}.", + "error": "Invalid minimum hit groups", + "output_files": [], + } + + if kmer_len is not None and kmer_len < 1: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: kmer_len must be positive, got {kmer_len}.", + "error": "Invalid kmer_len", "output_files": [] + } + if minimizer_len is not None and minimizer_len < 1: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: minimizer_len must be positive, got {minimizer_len}.", + "error": "Invalid minimizer_len", "output_files": [] + } + if minimizer_spaces is not None and minimizer_spaces < 0: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: minimizer_spaces cannot be negative, got {minimizer_spaces}.", + "error": "Invalid minimizer_spaces", "output_files": [] + } + + # Prepare command + cmd = ["kraken2", "--db", str(database)] + + if threads > 1: + cmd.extend(["--threads", str(threads)]) + if output_file: + output_file.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["--output", str(output_file)]) + if report_file: + report_file.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["--report", str(report_file)]) + if paired: + cmd.append("--paired") + if unclassified_out: + unclassified_out.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["--unclassified-out", str(unclassified_out)]) + if classified_out: + classified_out.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["--classified-out", str(classified_out)]) + if confidence != 0.0: # Only add if not default + cmd.extend(["--confidence", str(confidence)]) + if minimum_hit_groups != 2: # Only add if not default + cmd.extend(["--minimum-hit-groups", str(minimum_hit_groups)]) + if quick: + cmd.append("--quick") + if use_mpa_style: + cmd.append("--use-mpa-style") + if gzip_compressed: + cmd.append("--gzip-compressed") + if bzip2_compressed: + cmd.append("--bzip2-compressed") + if memory_mapping: + cmd.append("--memory-mapping") + if preload_db: + cmd.append("--preload-db") + if report_zero_counts: + cmd.append("--report-zero-counts") + if report_minimizer_data: + cmd.append("--report-minimizer-data") + if skip_classified: + cmd.append("--skip-classified") + if skip_unclassified: + cmd.append("--skip-unclassified") + if scientific_name_output: + # Some generated manuals include this flag, but standard Kraken2 releases + # do not support it. Use --report plus taxonomy post-processing instead. + pass + if taxid_output: + # Kraken2 output already contains taxids in the classification column. + # Passing a non-portable --taxid-output flag breaks common installations. + pass + if kmer_len is not None: + cmd.extend(["--kmer-len", str(kmer_len)]) + if minimizer_len is not None: + cmd.extend(["--minimizer-len", str(minimizer_len)]) + if minimizer_spaces is not None: + cmd.extend(["--minimizer-spaces", str(minimizer_spaces)]) + + cmd.extend([str(f) for f in input_files]) + + result = _run_command(cmd) + + # Add output files to the result + output_files = [] + if output_file: + output_files.append(str(output_file)) + if report_file: + output_files.append(str(report_file)) + if unclassified_out: + output_files.append(str(unclassified_out)) + if classified_out: + output_files.append(str(classified_out)) + result["output_files"] = output_files + + return result + +@mcp.tool() +def kraken2_build_db( + database: Path, + threads: int = 1, + add_to_library_files: Optional[List[Path]] = None, + build_db: bool = False, + download_taxonomy: bool = False, + download_library: Optional[str] = None, # e.g., 'nt', 'refseq', 'viral', 'archaea', 'bacteria', 'human' + clean: bool = False, + kmer_len: Optional[int] = None, + minimizer_len: Optional[int] = None, + minimizer_spaces: Optional[int] = None, + max_db_size: Optional[str] = None, # e.g., '50G' + protein: bool = False, + fast_build: bool = False, + no_masking: bool = False, + taxid_map: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Builds or updates a Kraken2 database. + + Args: + database: Path to the Kraken2 database directory to be built or updated. + threads: Number of threads to use for database building. Must be at least 1. + add_to_library_files: List of FASTA files to add to the database library. + build_db: Set to True to initiate the database build process after adding files. + download_taxonomy: Set to True to download NCBI taxonomy. + download_library: Specify a library to download (e.g., 'nt', 'refseq', 'viral', 'archaea', 'bacteria', 'human', 'fungi', 'plant', 'protozoa'). + clean: Remove intermediate files after building. + kmer_len: K-mer length for the database. Must be positive if provided. + minimizer_len: Minimizer length for the database. Must be positive if provided. + minimizer_spaces: Number of spaces in minimizers for the database. Must be non-negative if provided. + max_db_size: Maximum database size (e.g., '50G', '100M'). + protein: Build a protein database. + fast_build: Use a faster, less memory-intensive build process. + no_masking: Do not mask low-complexity regions in input sequences. + taxid_map: Path to a custom taxid map file. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not database.parent.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Parent directory of database '{database.parent}' not found.", + "error": "Invalid database path", + "output_files": [], + } + + if threads < 1: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Number of threads must be at least 1, got {threads}.", + "error": "Invalid threads count", + "output_files": [], + } + + if add_to_library_files: + for f in add_to_library_files: + if not f.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Library file '{f}' not found or is not a file.", + "error": "Invalid library file path", + "output_files": [], + } + + if kmer_len is not None and kmer_len < 1: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: kmer_len must be positive, got {kmer_len}.", + "error": "Invalid kmer_len", "output_files": [] + } + if minimizer_len is not None and minimizer_len < 1: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: minimizer_len must be positive, got {minimizer_len}.", + "error": "Invalid minimizer_len", "output_files": [] + } + if minimizer_spaces is not None and minimizer_spaces < 0: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: minimizer_spaces cannot be negative, got {minimizer_spaces}.", + "error": "Invalid minimizer_spaces", "output_files": [] + } + + if taxid_map and not taxid_map.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Custom taxid map file '{taxid_map}' not found or is not a file.", + "error": "Invalid taxid map path", + "output_files": [], + } + + # Prepare command + cmd = ["kraken2-build", "--db", str(database)] + + if threads > 1: + cmd.extend(["--threads", str(threads)]) + if download_taxonomy: + cmd.append("--download-taxonomy") + if download_library: + valid_libraries = ['nt', 'refseq', 'viral', 'archaea', 'bacteria', 'human', 'fungi', 'plant', 'protozoa'] # Common ones + if download_library not in valid_libraries: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: Invalid download_library '{download_library}'. Must be one of {', '.join(valid_libraries)}.", + "error": "Invalid download_library", "output_files": [] + } + cmd.extend(["--download-library", download_library]) + if add_to_library_files: + for f in add_to_library_files: + cmd.extend(["--add-to-library", str(f)]) + if build_db: + cmd.append("--build") + if clean: + cmd.append("--clean") + if kmer_len is not None: + cmd.extend(["--kmer-len", str(kmer_len)]) + if minimizer_len is not None: + cmd.extend(["--minimizer-len", str(minimizer_len)]) + if minimizer_spaces is not None: + cmd.extend(["--minimizer-spaces", str(minimizer_spaces)]) + if max_db_size: + cmd.extend(["--max-db-size", max_db_size]) + if protein: + cmd.append("--protein") + if fast_build: + cmd.append("--fast-build") + if no_masking: + cmd.append("--no-masking") + if taxid_map: + cmd.extend(["--taxid-map", str(taxid_map)]) + + # Ensure at least one action is specified for kraken2-build + if not (download_taxonomy or download_library or add_to_library_files or build_db or clean): + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: No action specified for kraken2-build. Please specify --download-taxonomy, --download-library, --add-to-library, --build, or --clean.", + "error": "No build action specified", + "output_files": [], + } + + result = _run_command(cmd) + + # The database directory itself is the primary output if build was successful + if result.get("returncode", 0) == 0 and (build_db or download_taxonomy or download_library): + result["output_files"].append(str(database)) + + return result + +@mcp.tool() +def kraken2_inspect_db( + database: Path, +) -> Dict[str, Any]: + """ + Inspects a Kraken2 database and prints its contents. + + Args: + database: Path to the Kraken2 database directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not database.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Database directory '{database}' not found or is not a directory.", + "error": "Invalid database path", + "output_files": [], + } + + # Prepare command + cmd = ["kraken2-inspect", "--db", str(database)] + + result = _run_command(cmd) + + # No specific output files are generated by inspect, its output is stdout + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/kraken2_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/kraken2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb299aa6ca1eab2c034b6d51a4e1346dbf96405 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/kraken2_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/kraken2_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_kraken2' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..12678b81c5c5a49282c43e9bc1d47af2b88bbc0c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kraken2: + build: . + image: mcp-kraken2:latest + container_name: mcp-kraken2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kraken2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3885284a988e6cfaff2e0b4165922a3e163706f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kraken2 + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_kraken2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdb/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdb/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdb/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mcl/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mcl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mcl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6548f1499a4590d2054c528e4ec666ea1df68e0a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install megahit via conda (e.g., from bioconda) +RUN conda install -c bioconda megahit -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/megahit_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/megahit_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/megahit_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/__pycache__/megahit_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/__pycache__/megahit_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca5bc65554dfdd099a948d3ff945ea912a101cdf Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/__pycache__/megahit_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/__pycache__/megahit_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/__pycache__/megahit_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f69b00486ad782f6633963ee4f4ab375274b523 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/__pycache__/megahit_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/megahit_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/megahit_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a6dd12871fda44ee7eea9e5469eb8799dcca91b4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/megahit_server.py @@ -0,0 +1,238 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_megahit' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def megahit_assemble( + pe1: Optional[str] = None, + pe2: Optional[str] = None, + pe12: Optional[str] = None, + read: Optional[str] = None, + out_dir: str = "./megahit_out", + out_prefix: Optional[str] = None, + min_count: int = 2, + k_list: Optional[str] = None, + k_min: int = 21, + k_max: int = 141, + k_step: int = 12, + no_mercy: bool = False, + bubble_level: int = 2, + merge_level: str = "20,0.95", + prune_level: int = 2, + prune_depth: int = 2, + disconnect_ratio: float = 0.1, + low_local_ratio: float = 0.2, + max_tip_len: Optional[int] = None, + cleaning_rounds: int = 5, + no_local: bool = False, + kmin_1pass: bool = False, + presets: Optional[str] = None, + memory: float = 0.9, + mem_flag: int = 1, + num_cpu_threads: Optional[int] = None, + no_hw_accel: bool = False, + min_contig_len: int = 200, + keep_tmp_files: bool = False, + tmp_dir: Optional[str] = None, + continue_run: bool = False, + test: bool = False, +): + """ + MEGAHIT: An ultra-fast single-node solution for large and complex metagenomics assembly. + + Args: + pe1: Comma-separated list of fasta/q paired-end #1 files, paired with pe2. + pe2: Comma-separated list of fasta/q paired-end #2 files, paired with pe1. + pe12: Comma-separated list of interleaved fasta/q paired-end files. + read: Comma-separated list of fasta/q single-end files. + out_dir: Output directory. + out_prefix: Output prefix (contig file will be OUT_DIR/OUT_PREFIX.contigs.fa). + min_count: Minimum multiplicity for filtering (k_min+1)-mers. + k_list: Comma-separated list of kmer sizes (all must be odd, 15-255, increment <= 28). + k_min: Minimum kmer size (<= 255), must be odd number. + k_max: Maximum kmer size (<= 255), must be odd number. + k_step: Increment of kmer size of each iteration (<= 28), must be even number. + no_mercy: Do not add mercy kmers. + bubble_level: Intensity of bubble merging (0-2), 0 to disable. + merge_level: Merge complex bubbles of length <= l*kmer_size and similarity >= s (format: l,s). + prune_level: Strength of low depth pruning (0-3). + prune_depth: Remove unitigs with avg kmer depth less than this value. + disconnect_ratio: Disconnect unitigs if depth ratio is less than this. + low_local_ratio: Remove unitigs if depth ratio to neighborhood is less than this. + max_tip_len: Remove tips less than this value (default 2*k). + cleaning_rounds: Number of rounds for graph cleaning. + no_local: Disable local assembly. + kmin_1pass: Use 1pass mode to build SdBG of k_min. + presets: Override parameters (e.g., 'meta-sensitive', 'meta-large'). + memory: Max memory in byte (if 0-1, fraction of total machine memory). + mem_flag: SdBG builder memory mode (0: min, 1: moderate, others: use all). + num_cpu_threads: Number of CPU threads. + no_hw_accel: Run without BMI2 and POPCNT hardware instructions. + min_contig_len: Minimum length of contigs to output. + keep_tmp_files: Keep all temporary files. + tmp_dir: Set temp directory. + continue_run: Continue a MEGAHIT run from its last available check point. + test: Run MEGAHIT on a toy test dataset. + """ + cmd = ["megahit"] + + # Input Validation + if not test and not continue_run: + if not any([pe1, pe12, read]): + return {"error": "Must provide at least one input type (-1/-2, --12, or -r) unless --test or --continue is used."} + if pe1 and not pe2: + return {"error": "pe1 (-1) requires pe2 (-2)."} + if pe2 and not pe1: + return {"error": "pe2 (-2) requires pe1 (-1)."} + + # File existence checks for inputs + def check_files(file_str: Optional[str]): + if file_str: + for f in file_str.split(','): + if not Path(f).exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + try: + check_files(pe1) + check_files(pe2) + check_files(pe12) + check_files(read) + except FileNotFoundError as e: + return {"error": str(e)} + + # Build Command + if pe1: cmd.extend(["-1", pe1]) + if pe2: cmd.extend(["-2", pe2]) + if pe12: cmd.extend(["--12", pe12]) + if read: cmd.extend(["-r", read]) + + cmd.extend(["-o", out_dir]) + if out_prefix: cmd.extend(["--out-prefix", out_prefix]) + + cmd.extend(["--min-count", str(min_count)]) + + if k_list: + cmd.extend(["--k-list", k_list]) + else: + cmd.extend(["--k-min", str(k_min)]) + cmd.extend(["--k-max", str(k_max)]) + cmd.extend(["--k-step", str(k_step)]) + + if no_mercy: cmd.append("--no-mercy") + + if not (0 <= bubble_level <= 2): + return {"error": "bubble_level must be between 0 and 2."} + cmd.extend(["--bubble-level", str(bubble_level)]) + + cmd.extend(["--merge-level", merge_level]) + + if not (0 <= prune_level <= 3): + return {"error": "prune_level must be between 0 and 3."} + cmd.extend(["--prune-level", str(prune_level)]) + + cmd.extend(["--prune-depth", str(prune_depth)]) + cmd.extend(["--disconnect-ratio", str(disconnect_ratio)]) + cmd.extend(["--low-local-ratio", str(low_local_ratio)]) + + if max_tip_len is not None: + cmd.extend(["--max-tip-len", str(max_tip_len)]) + + cmd.extend(["--cleaning-rounds", str(cleaning_rounds)]) + + if no_local: cmd.append("--no-local") + if kmin_1pass: cmd.append("--kmin-1pass") + if presets: cmd.extend(["--presets", presets]) + + cmd.extend(["--memory", str(memory)]) + cmd.extend(["--mem-flag", str(mem_flag)]) + + if num_cpu_threads is not None: + cmd.extend(["--num-cpu-threads", str(num_cpu_threads)]) + + if no_hw_accel: cmd.append("--no-hw-accel") + cmd.extend(["--min-contig-len", str(min_contig_len)]) + + if keep_tmp_files: cmd.append("--keep-tmp-files") + if tmp_dir: cmd.extend(["--tmp-dir", tmp_dir]) + if continue_run: cmd.append("--continue") + if test: cmd.append("--test") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Identify output contig file + prefix = out_prefix if out_prefix else "final" + contig_file = Path(out_dir) / f"{prefix}.contigs.fa" + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(contig_file)] if contig_file.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "MEGAHIT execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode + } + +@mcp.tool() +def megahit_core_contig2fastg( + k_size: int, + contig_fa: str, + output_fastg: Optional[str] = None +): + """ + Convert MEGAHIT intermediate contigs to FASTG format. + + Args: + k_size: Kmer size of the intermediate contig file. + contig_fa: Path to the intermediate contig file (e.g., k119.contig.fa). + output_fastg: Path to save the FASTG output. If None, returns content in stdout. + """ + contig_path = Path(contig_fa) + if not contig_path.exists(): + return {"error": f"Contig file not found: {contig_fa}"} + + cmd = ["megahit_core", "contig2fastg", str(k_size), str(contig_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_fastg: + out_path = Path(output_fastg) + out_path.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "FASTG written to file", + "stderr": result.stderr, + "output_files": [str(out_path)] + } + else: + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "megahit_core contig2fastg failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/megahit_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/megahit_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5a4f49361017705e8202ca2735ef9e132597aa70 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/megahit_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/megahit_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_megahit' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ec644ca19b52b58c93c5ae2294443dcff8b4403b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-megahit: + build: . + image: mcp-megahit:latest + container_name: mcp-megahit + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=megahit + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..565fb2b9b37977c6dd7b759b0200899f36be805e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - megahit + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_megahit/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d755e161b7b6fd2926ac9db2ca95fdc51437c8d9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install metagenome-atlas via conda (e.g., from bioconda) +RUN conda install -c bioconda metagenome-atlas -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/metagenome-atlas_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/metagenome-atlas_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/metagenome-atlas_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/__pycache__/metagenome-atlas_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/__pycache__/metagenome-atlas_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72a16e6c388a9c6c5b87a4fce2b4eb4a6df683b3 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/__pycache__/metagenome-atlas_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/metagenome-atlas_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/metagenome-atlas_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff43ae7ac43bcaa7010038126a320235ee63ff1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/metagenome-atlas_server.py @@ -0,0 +1,240 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() decorator is commented out as per instructions +# but would be present in a real MCP environment. + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_metagenome_atlas' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def atlas_init( + samples: List[Path], + db_dir: Path, + working_dir: Path, + configfile: Optional[Path] = None, + threads: int = 8, + assembler: str = "megahit", + binner: str = "metabat2", + no_conda: bool = False, +) -> dict: + """ + Initializes a new metagenome-atlas project. + + This command sets up the working directory, creates a samples.tsv file from the + input FASTQ files, and generates a default config.yaml. It also downloads + the necessary databases to the specified database directory. + """ + # --- Input Validation --- + if not samples: + raise ValueError("At least one sample FASTQ file must be provided.") + for sample_path in samples: + if not sample_path.is_file(): + raise FileNotFoundError(f"Input sample file not found: {sample_path}") + + if threads < 1: + raise ValueError("The number of threads must be at least 1.") + + allowed_assemblers = ["megahit", "spades"] + if assembler not in allowed_assemblers: + raise ValueError( + f"Invalid assembler '{assembler}'. Must be one of {allowed_assemblers}." + ) + + allowed_binners = ["metabat2", "maxbin2", "concoct", "all"] + if binner not in allowed_binners: + raise ValueError( + f"Invalid binner '{binner}'. Must be one of {allowed_binners}." + ) + + if configfile and not configfile.is_file(): + raise FileNotFoundError(f"Custom config file not found: {configfile}") + + # --- Command Construction --- + cmd = [ + "atlas", + "init", + "--db-dir", + str(db_dir), + "--working-dir", + str(working_dir), + "--threads", + str(threads), + "--assembler", + assembler, + "--binner", + binner, + ] + + if configfile: + cmd.extend(["--configfile", str(configfile)]) + + if no_conda: + cmd.append("--no-conda") + + cmd.extend([str(p) for p in samples]) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + + # Define expected output files + output_files = [ + str(working_dir / "samples.tsv"), + str(working_dir / "config.yaml"), + str(working_dir / "Snakefile"), + ] + + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'atlas' command not found. Make sure metagenome-atlas is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + # --- Return Structured Output --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + + +@mcp.tool() +def atlas_run( + working_dir: Path, + targets: Optional[List[str]] = None, + configfile: Optional[Path] = None, + cores: int = 8, + jobs: Optional[int] = None, + profile: Optional[str] = None, + use_conda: bool = False, + conda_prefix: Optional[Path] = None, + snake_args: Optional[str] = None, +) -> dict: + """ + Executes the metagenome-atlas workflow on an initialized project. + + This command invokes Snakemake to run the pipeline based on the config.yaml + and samples.tsv in the specified working directory. + """ + # --- Input Validation --- + if not working_dir.is_dir(): + raise FileNotFoundError( + f"Working directory not found: {working_dir}. Please run 'atlas_init' first." + ) + if not (working_dir / "config.yaml").is_file(): + raise FileNotFoundError( + f"Project not initialized in '{working_dir}'. 'config.yaml' is missing." + ) + + if cores < 1: + raise ValueError("The number of cores must be at least 1.") + if jobs is not None and jobs < 1: + raise ValueError("The number of jobs must be at least 1 if specified.") + + if configfile and not configfile.is_file(): + raise FileNotFoundError(f"Custom config file not found: {configfile}") + + # --- Command Construction --- + cmd = [ + "atlas", + "run", + "--working-dir", + str(working_dir), + "--cores", + str(cores), + ] + + if configfile: + cmd.extend(["--configfile", str(configfile)]) + if jobs: + cmd.extend(["--jobs", str(jobs)]) + if profile: + cmd.extend(["--profile", profile]) + if use_conda: + cmd.append("--use-conda") + if conda_prefix: + cmd.extend(["--conda-prefix", str(conda_prefix)]) + if snake_args: + cmd.extend(snake_args.split()) + + if targets: + cmd.extend(targets) + else: + # Default target is 'all' if not specified + cmd.append("all") + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + # The 'run' command can take a long time. + # It's executed within the context of the working directory. + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + + # Define representative output directories/files + output_files = [ + str(working_dir / "ASSEMBLY"), + str(working_dir / "BINNING"), + str(working_dir / "QC"), + str(working_dir / "genomes"), + str(working_dir / "annotations"), + str(working_dir / "reports"), + ] + + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'atlas' command not found. Make sure metagenome-atlas is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + # --- Return Structured Output --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/metagenome-atlas_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/metagenome-atlas_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9031059f90e1a15b18b7a5de765ff7cb9e9247f6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/metagenome-atlas_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/metagenome-atlas_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_metagenome_atlas' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..204256fa812e776c98aecae7152e596879b282e6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-metagenome-atlas: + build: . + image: mcp-metagenome-atlas:latest + container_name: mcp-metagenome-atlas + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=metagenome-atlas + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d7cf10169e660b59b7d47c7ec88f222833b2732 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - metagenome-atlas + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_metagenome-atlas/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mlst/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mlst/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mlst/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4522ea091ed04877737a22e77bcdb57c074a11b5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mosdepth via conda (e.g., from bioconda) +RUN conda install -c bioconda mosdepth -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mosdepth_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mosdepth_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mosdepth_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/__pycache__/mosdepth_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/__pycache__/mosdepth_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b7936150bfe4411031af75f612dbc2e460bff05 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/__pycache__/mosdepth_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/mosdepth_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/mosdepth_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3577de905bd7a331a0c6dbc89c6394809675d178 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/mosdepth_server.py @@ -0,0 +1,200 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Optional + +# Set up logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# This is a placeholder for the MCP decorator. +# The actual @mcp.tool decorator will be provided by the MCP environment. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def mosdepth( + prefix: str, + input_files: List[Path], + threads: Optional[int] = None, + chrom: Optional[List[str]] = None, + by: Optional[str] = None, + no_per_base: bool = False, + fasta: Optional[Path] = None, + flag: int = 1796, + include_flag: int = 0, + quantize: Optional[str] = None, + mapq: int = 0, + d4: bool = False, + fast_mode: bool = False, + use_median: bool = False, + no_median: bool = False, + roc: Optional[str] = None, + thresholds: Optional[str] = None, + distribution_file: Optional[Path] = None, + long_reads: bool = False, + specific_regions: Optional[Path] = None, + precision: int = 4, +) -> dict: + """ + Calculates depth from BAM/CRAM files using mosdepth. + + mosdepth is a fast BAM/CRAM depth calculator for WGS, exome, or targeted sequencing. + This tool wraps the `mosdepth` command-line tool, providing access to its full functionality. + """ + # --- Input Validation --- + if not prefix: + raise ValueError("Output prefix must be provided and cannot be empty.") + + if not input_files: + raise ValueError("At least one input BAM or CRAM file must be provided.") + + for file_path in input_files: + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + is_cram = any(str(f).lower().endswith(".cram") for f in input_files) + if is_cram and not fasta: + raise ValueError("A FASTA reference file (--fasta) is required for CRAM inputs.") + + if fasta and not fasta.is_file(): + raise FileNotFoundError(f"FASTA file not found: {fasta}") + + if threads is not None and threads < 0: + raise ValueError(f"Number of threads must be a non-negative integer, but got {threads}.") + + if mapq < 0: + raise ValueError(f"Mapping quality threshold (--mapq) must be non-negative, but got {mapq}.") + + # Check for mutually exclusive arguments + if sum([bool(by), bool(quantize), bool(d4)]) > 1: + raise ValueError("Options --by, --quantize, and --d4 are mutually exclusive.") + + # Check for dependent arguments + if roc and not by: + raise ValueError("--roc requires --by to be specified.") + if thresholds and not roc: + raise ValueError("--thresholds requires --roc to be specified.") + + if by: + try: + # Check if 'by' is a window size (integer) + window_size = int(by) + if window_size <= 0: + raise ValueError + except ValueError: + # If not an integer, assume it's a BED file path + by_path = Path(by) + if not by_path.is_file(): + raise FileNotFoundError(f"BED file specified with --by not found: {by_path}") + + if specific_regions and not specific_regions.is_file(): + raise FileNotFoundError(f"BED file for --specific-regions not found: {specific_regions}") + + # --- Command Construction --- + cmd = ["mosdepth"] + + if threads is not None: + cmd.extend(["-t", str(threads)]) + if chrom: + for c in chrom: + cmd.extend(["-c", c]) + if by: + cmd.extend(["--by", str(by)]) + if no_per_base: + cmd.append("--no-per-base") + if fasta: + cmd.extend(["-f", str(fasta)]) + if flag != 1796: + cmd.extend(["-F", str(flag)]) + if include_flag != 0: + cmd.extend(["-i", str(include_flag)]) + if quantize: + cmd.extend(["--quantize", quantize]) + if mapq != 0: + cmd.extend(["-Q", str(mapq)]) + if d4: + cmd.append("--d4") + if fast_mode: + cmd.append("--fast-mode") + if use_median: + cmd.append("--use-median") + if no_median: + cmd.append("--no-median") + if roc: + cmd.extend(["--roc", roc]) + if thresholds: + cmd.extend(["--thresholds", thresholds]) + if distribution_file: + cmd.extend(["--distribution-file", str(distribution_file)]) + if long_reads: + cmd.append("--long-reads") + if specific_regions: + cmd.extend(["--specific-regions", str(specific_regions)]) + if precision != 4: + cmd.extend(["--precision", str(precision)]) + + # Positional arguments + cmd.append(prefix) + cmd.extend([str(p) for p in input_files]) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + except FileNotFoundError: + logging.error("mosdepth not found. Please ensure it is installed and in your PATH.") + raise + except subprocess.CalledProcessError as e: + logging.error(f"mosdepth execution failed with exit code {e.returncode}.") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + raise e + + # --- Output File Discovery --- + output_files = [] + expected_files = [ + Path(f"{prefix}.mosdepth.global.dist.txt"), + ] + if not no_per_base: + expected_files.extend([ + Path(f"{prefix}.per-base.bed.gz"), + Path(f"{prefix}.per-base.bed.gz.csi"), + ]) + if by: + expected_files.extend([ + Path(f"{prefix}.mosdepth.region.dist.txt"), + Path(f"{prefix}.regions.bed.gz"), + Path(f"{prefix}.regions.bed.gz.csi"), + ]) + if quantize: + expected_files.extend([ + Path(f"{prefix}.quantized.bed.gz"), + Path(f"{prefix}.quantized.bed.gz.csi"), + ]) + if d4: + expected_files.append(Path(f"{prefix}.d4")) + if distribution_file: + expected_files.append(distribution_file) + + for f in expected_files: + if f.exists(): + output_files.append(str(f.resolve())) + else: + logging.warning(f"Expected output file not found: {f}") + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/mosdepth_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/mosdepth_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5888ca90cd81f654265b550a337285fa874bf3bc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/mosdepth_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mosdepth/app/mosdepth_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_mosdepth' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..477da30504feb6d10d11f517b09b2b008b987103 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mosdepth: + build: . + image: mcp-mosdepth:latest + container_name: mcp-mosdepth + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mosdepth + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d7d96fa0eef440c4efae979054b13800fe49fdee --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mosdepth + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mosdepth/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-amrfinderplus/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-amrfinderplus/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-amrfinderplus/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6c574c3c17e3fbaa385c6f6d5c3ac7b792378dcf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ncbi-ngs-sdk via conda (e.g., from bioconda) +RUN conda install -c bioconda ncbi-ngs-sdk -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ncbi-ngs-sdk_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ncbi-ngs-sdk_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ncbi-ngs-sdk_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/__pycache__/ncbi-ngs-sdk_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/__pycache__/ncbi-ngs-sdk_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1b2ae3a667bdea6df89058917cce015d9caf0fe Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/__pycache__/ncbi-ngs-sdk_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/ncbi-ngs-sdk_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/ncbi-ngs-sdk_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d5db7d14f2a59ecd6871438484a29fe449e5121c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/ncbi-ngs-sdk_server.py @@ -0,0 +1,56 @@ +import logging +from typing import List + +# In a real MCP environment, the mcp module would be available. +# For demonstration purposes, a dummy class is defined to mimic the decorator. +class MCP: + def tool(self): + def decorator(f): + return f + return decorator + +mcp = MCP() + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_ncbi_ngs_sdk' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def ngs_sdk_info(): + """ + Provides information about the ncbi-ngs-sdk package. + + The 'ncbi-ngs-sdk' is a Software Development Kit (SDK), not a standalone + command-line tool. It provides libraries and Application Programming Interfaces (APIs) + for C++, Java, and Python to access Next Generation Sequencing (NGS) data from + the NCBI Sequence Read Archive (SRA). + + As it is not an executable with command-line arguments, this function does not + execute any subprocess. It serves as an informational placeholder, confirming the + nature of the package and noting that it has been superseded by and integrated into + the 'sra-tools' suite. For command-line access to SRA data, tools from the + 'sra-tools' package (like fastq-dump, sam-dump) should be used instead. + """ + logging.warning( + "ncbi-ngs-sdk is a library/SDK and not a command-line tool. " + "No command was executed." + ) + + info_message = ( + "The 'ncbi-ngs-sdk' package is a Software Development Kit (SDK) and does not " + "provide a direct command-line executable. It is a collection of libraries " + "used by other tools to access NGS data. The project has been merged into " + "the 'sra-tools' repository. Please use tools from the 'sra-tools' package " + "for command-line operations." + ) + + return { + "command_executed": "N/A (ncbi-ngs-sdk is a library)", + "stdout": info_message, + "stderr": "", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/ncbi-ngs-sdk_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/ncbi-ngs-sdk_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..077bf6efde1287bd0388167b2a768223edb88c95 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/ncbi-ngs-sdk_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ncbi-ngs-sdk/app/ncbi-ngs-sdk_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_ncbi_ngs_sdk' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..246ec5a490393f3cf50c15cc7dcdc0b25073e44d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ncbi-ngs-sdk: + build: . + image: mcp-ncbi-ngs-sdk:latest + container_name: mcp-ncbi-ngs-sdk + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ncbi-ngs-sdk + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bcb01608dfcc0d0778708e7d07ef3304226407be --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ncbi-ngs-sdk + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-ngs-sdk/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bdfe02ef54cda16557e8c479e3aae9117ac55d06 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ngs-tools via conda (e.g., from bioconda) +RUN conda install -c bioconda ngs-tools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ngs-tools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ngs-tools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ngs-tools_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/__pycache__/ngs-tools_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/__pycache__/ngs-tools_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b52bb5d7d8b893a719232e034d7a47515c96e15a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/__pycache__/ngs-tools_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/ngs-tools_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/ngs-tools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f8087038e2e17ad3caaab276c94f8041f82a9f3f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/ngs-tools_server.py @@ -0,0 +1,77 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any, List + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_ngs_tools' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def ngs_tools_run_generic( + version: bool = False, + help_flag: bool = False, +) -> Dict[str, Any]: + """ + Executes the ngs-tools command with generic options. + + WARNING: The provided documentation for ngs-tools does not specify any + command-line subcommands or parameters beyond its general purpose. + This function provides a generic wrapper for the main 'ngs-tools' executable + with common `--version` and `--help` flags. + To create a fully functional MCP tool, detailed command-line documentation + (e.g., from `ngs-tools --help` or specific subcommand help pages) is required. + + Args: + version: If True, print the ngs-tools version and exit. + help_flag: If True, print the ngs-tools help message and exit. + """ + command = ["ngs-tools"] + output_files: List[Path] = [] + + if version: + command.append("--version") + elif help_flag: + command.append("--help") + else: + # If neither version nor help is requested, and no other specific command + # is known from the provided documentation, running 'ngs-tools' alone + # might print general help or an error. This is a best guess given the + # lack of specific CLI documentation. + pass + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ngs-tools command failed with exit code {e.returncode}", + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'ngs-tools' executable not found. Please ensure it is installed and in your PATH.", + "error": "Executable not found", + "output_files": output_files, + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/ngs-tools_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/ngs-tools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b2ed5c02f012c87be0a4b03c9a26947e87c9c5f7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/ngs-tools_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ngs-tools/app/ngs-tools_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_ngs_tools' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..56226e5b077de012ebc964b2d9586550aef01c95 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ngs-tools: + build: . + image: mcp-ngs-tools:latest + container_name: mcp-ngs-tools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ngs-tools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f72ca272141a55aca4bdf6d3553193553aafc828 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ngs-tools + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ngs-tools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63b3c104360048b9b73d38b4f96f7f9760c6f74a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install novoalign via conda (e.g., from bioconda) +RUN conda install -c bioconda novoalign -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/novoalign_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/novoalign_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/novoalign_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/__pycache__/novoalign_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/__pycache__/novoalign_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..766e8251e4d773d6c24b8a0be8c5bd7c6a24896b Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/__pycache__/novoalign_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/novoalign_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/novoalign_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d2111eda5a63f85a8d91f4fe548c50fb5c64f993 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/novoalign_server.py @@ -0,0 +1,264 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Literal + +# MCP decorator is omitted as per instructions, but would be present in a real implementation. +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_novoalign' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def novoalign_index( + index_file: Path, + fasta_files: List[Path], + kmer_length: int = 14, + kmer_step_size: int = 1, +): + """ + Creates a novoalign index from one or more reference FASTA files. + + This is a prerequisite for running the novoalign_align tool. + + Args: + index_file: The path for the output index file. + fasta_files: A list of one or more reference genome FASTA files. + kmer_length: The k-mer length for the index (default: 14). + kmer_step_size: The step size for the k-mer (default: 1). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # --- Input Validation --- + if not fasta_files: + raise ValueError("At least one FASTA file must be provided in fasta_files.") + for f in fasta_files: + if not Path(f).exists(): + raise FileNotFoundError(f"Input FASTA file not found: {f}") + if kmer_length <= 0: + raise ValueError("kmer_length must be a positive integer.") + if kmer_step_size <= 0: + raise ValueError("kmer_step_size must be a positive integer.") + + # --- Command Construction --- + cmd = [ + "novoindex", + "-k", str(kmer_length), + "-s", str(kmer_step_size), + str(index_file), + ] + cmd.extend([str(f) for f in fasta_files]) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"index_file": str(index_file)} + } + except FileNotFoundError: + raise RuntimeError("novoindex command not found. Please ensure the novoalign suite is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"novoindex execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}\n" + "Note: The novoalign suite requires a valid license to run. This error may be due to a missing or expired license." + ) + raise RuntimeError(error_message) from e + +@mcp.tool() +def novoalign_align( + database: Path, + read_files: List[Path], + output_file: Optional[Path] = None, + output_format: Literal["SAM", "BAM", "Native"] = "SAM", + cores: int = 1, + read_group_id: Optional[str] = None, + read_group_library: Optional[str] = None, + read_group_sample: Optional[str] = None, + read_group_platform: Optional[str] = None, + read_group_platform_unit: Optional[str] = None, + read_group_center: Optional[str] = None, + insert_size_mean: Optional[int] = None, + insert_size_stdev: Optional[int] = None, + paired_end_orientation: Literal["FR", "RF", "FF", "RR"] = "FR", + alignment_threshold: Optional[int] = None, + gap_open_penalty: int = 40, + gap_extend_penalty: int = 6, + report_mode: Literal["All", "Random", "None"] = "Random", + report_repeats: Optional[int] = None, + soft_clip: bool = False, + adapter1: Optional[str] = None, + adapter2: Optional[str] = None, + headcrop: int = 0, + tailcrop: int = 0, + quality_trim_threshold: int = 20, + bisulfite_mode: Literal["Off", "F", "R", "Both"] = "Off", + mirna_mode: bool = False, + input_format: Optional[Literal["FA", "FQ", "STDFQ", "ILM1.3", "ILM1.8", "BAM"]] = None, +): + """ + Aligns short reads to a reference genome using novoalign. + + Args: + database: Path to the novoalign index file created by novoalign_index. + read_files: A list of one (single-end) or two (paired-end) read files. + output_file: Path to the output alignment file. If not provided, output is captured. + output_format: The format of the output alignment (SAM, BAM, Native). + cores: Number of CPU cores to use. Multi-threading requires a commercial license. + read_group_id: Read Group ID (ID tag). + read_group_library: Read Group Library (LB tag). + read_group_sample: Read Group Sample (SM tag). + read_group_platform: Read Group Platform (PL tag). + read_group_platform_unit: Read Group Platform Unit (PU tag). + read_group_center: Read Group Center (CN tag). + insert_size_mean: Mean insert size for paired-end reads. Required for PE. + insert_size_stdev: Standard deviation of insert size for paired-end reads. Required for PE. + paired_end_orientation: Orientation of paired-end reads. + alignment_threshold: Alignment score threshold. + gap_open_penalty: Penalty for opening a gap. + gap_extend_penalty: Penalty for extending a gap. + report_mode: Mode for reporting alignments ('All', 'Random', 'None'). + report_repeats: Report repeat alignments up to this many times. + soft_clip: Use soft clipping for alignments. + adapter1: Sequence of the 3' adapter to be trimmed for read 1. + adapter2: Sequence of the 3' adapter to be trimmed for read 2 (if paired-end). + headcrop: Number of bases to crop from the 5' end of reads. + tailcrop: Number of bases to crop from the 3' end of reads. + quality_trim_threshold: Quality score threshold for trimming. + bisulfite_mode: Enable bisulfite alignment mode. + mirna_mode: Enable miRNA alignment mode. + input_format: Specify the format of the input read files. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # --- Input Validation --- + if not database.exists(): + raise FileNotFoundError(f"Database file not found: {database}") + if not read_files: + raise ValueError("At least one read file must be provided.") + for f in read_files: + if not Path(f).exists(): + raise FileNotFoundError(f"Read file not found: {f}") + if len(read_files) > 2: + raise ValueError("A maximum of two read files (for paired-end) is supported.") + + is_paired_end = len(read_files) == 2 + pe_params_provided = [p is not None for p in [insert_size_mean, insert_size_stdev]] + if any(pe_params_provided) and not is_paired_end: + raise ValueError("Insert size parameters can only be used with paired-end reads (2 read files).") + if is_paired_end and not all(pe_params_provided): + raise ValueError("For paired-end reads, both insert_size_mean and insert_size_stdev must be provided.") + + if cores < 1: + raise ValueError("Number of cores must be at least 1.") + if headcrop < 0 or tailcrop < 0 or quality_trim_threshold < 0: + raise ValueError("Trimming and crop values cannot be negative.") + + # --- Command Construction --- + cmd = [ + "novoalign", + "-d", str(database), + "-f", *[str(f) for f in read_files], + "-o", output_format, + "-c", str(cores), + "-g", str(gap_open_penalty), + "-x", str(gap_extend_penalty), + "-r", report_mode, + "-h", str(headcrop), + "-l", str(tailcrop), + "-q", str(quality_trim_threshold), + ] + + if read_group_id: cmd.extend(["--rgid", read_group_id]) + if read_group_library: cmd.extend(["--rglb", read_group_library]) + if read_group_sample: cmd.extend(["--rgsm", read_group_sample]) + if read_group_platform: cmd.extend(["--rgpl", read_group_platform]) + if read_group_platform_unit: cmd.extend(["--rgpu", read_group_platform_unit]) + if read_group_center: cmd.extend(["--rgcn", read_group_center]) + + if is_paired_end and all(pe_params_provided): + cmd.extend(["-i", f"PE{insert_size_mean},{insert_size_stdev},{paired_end_orientation}"]) + + if alignment_threshold is not None: + cmd.extend(["-t", str(alignment_threshold)]) + if report_repeats is not None: + cmd.extend(["-R", str(report_repeats)]) + if soft_clip: + cmd.extend(["-s", "4"]) + if adapter1: + adapter_args = ["-a", adapter1] + if adapter2: + adapter_args.append(adapter2) + cmd.extend(adapter_args) + if bisulfite_mode != "Off": + cmd.extend(["-b", bisulfite_mode]) + if mirna_mode: + cmd.append("-m") + if input_format: + cmd.extend(["-F", input_format]) + + command_executed = " ".join(cmd) + output_files_dict = {} + + # --- Subprocess Execution --- + try: + if output_file: + output_files_dict["alignment_output"] = str(output_file) + with open(output_file, "w") as f_out: + result = subprocess.run( + cmd, + stdout=f_out, + capture_output=True, + text=True, + check=True + ) + stdout_content = f"Output successfully written to {output_file}" + else: + # Use a temporary file for large outputs if no file is specified + with tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=f".{output_format.lower()}") as tmp_out: + result = subprocess.run( + cmd, + stdout=tmp_out, + capture_output=True, + text=True, + check=True + ) + tmp_out.seek(0) + # For simplicity, we don't read the large output back into memory + stdout_content = f"Output written to temporary file: {tmp_out.name}" + output_files_dict["alignment_output"] = tmp_out.name + + return { + "command_executed": command_executed, + "stdout": stdout_content, + "stderr": result.stderr, + "output_files": output_files_dict + } + except FileNotFoundError: + raise RuntimeError("novoalign command not found. Please ensure the novoalign suite is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"novoalign execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}\n" + "Note: The novoalign suite requires a valid license to run. This error may be due to a missing or expired license." + ) + raise RuntimeError(error_message) from e + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/novoalign_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/novoalign_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7a5f583486133c20c4bdb7bd1ef13d3a22d4ca86 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/novoalign_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_novoalign/app/novoalign_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_novoalign' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..13ad5516e1557a4a01f2606b349282e00c5d0059 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-novoalign: + build: . + image: mcp-novoalign:latest + container_name: mcp-novoalign + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=novoalign + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..18056ee95d4f023b9eb1e222f3b28b47c3126f43 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - novoalign + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_novoalign/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..faff7c7e52b3d033c8717c00bf56f0a912804eeb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install pairix via conda (e.g., from bioconda) +RUN conda install -c bioconda pairix -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/pairix_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/pairix_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/pairix_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/__pycache__/pairix_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/__pycache__/pairix_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ef67b977493fe12f117296f2c6064d322de1c9a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/__pycache__/pairix_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/pairix_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/pairix_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a8d2530332f45a88a2a6a2d9cff5cfb6c9e3bbfa --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/pairix_server.py @@ -0,0 +1,385 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# NOTE: The @mcp.tool decorator is a placeholder for the Model Context Protocol (MCP) framework. +# This code is designed to be used within an MCP server environment. +# To run this code standalone, you would need to define or remove the decorator. + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +class mcp: + """A mock mcp class for standalone validation.""" + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_pairix' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def pairix_index( + input_file: Path, + preset: Optional[str] = None, + seq1: Optional[int] = None, + beg1: Optional[int] = None, + end1: Optional[int] = None, + seq2: Optional[int] = None, + beg2: Optional[int] = None, + end2: Optional[int] = None, + comment_char: Optional[str] = None, + delimiter: Optional[str] = None, + force: bool = False, + tabix_mode: bool = False, + uncompressed: bool = False, + auto_offset: bool = False, +): + """ + Creates a .px2 index for a bgzipped pairs file using pairix. + + Args: + input_file: Path to the input pairs file (usually bgzipped). + preset: Preset for column numbers (gff, pairs, sam, vcf, bed, psltbl). + seq1: Sequence name column for the first mate (1-based). + beg1: Start column for the first mate (1-based). + end1: End column for the first mate (1-based). + seq2: Sequence name column for the second mate (1-based). + beg2: Start column for the second mate (1-based). + end2: End column for the second mate (1-based). + comment_char: Skip lines starting with this character. + delimiter: The delimiter character (default is tab). + force: Overwrite the index file if it exists. + tabix_mode: Use tabix mode (no second mate). + uncompressed: Input file is uncompressed. + auto_offset: Automatically detect column numbers for pairs format. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + VALID_PRESETS = {"gff", "pairs", "sam", "vcf", "bed", "psltbl"} + if preset and preset not in VALID_PRESETS: + raise ValueError(f"Invalid preset '{preset}'. Must be one of {VALID_PRESETS}") + + if comment_char and len(comment_char) != 1: + raise ValueError("comment_char must be a single character.") + + if delimiter and len(delimiter) != 1: + raise ValueError("delimiter must be a single character.") + + cmd = ["pairix"] + + if preset: + cmd.extend(["-p", preset]) + if seq1 is not None: + cmd.extend(["-s", str(seq1)]) + if beg1 is not None: + cmd.extend(["-b", str(beg1)]) + if end1 is not None: + cmd.extend(["-e", str(end1)]) + if seq2 is not None: + cmd.extend(["-S", str(seq2)]) + if beg2 is not None: + cmd.extend(["-B", str(beg2)]) + if end2 is not None: + cmd.extend(["-E", str(end2)]) + if comment_char: + cmd.extend(["-c", comment_char]) + if delimiter: + cmd.extend(["-d", delimiter]) + if force: + cmd.append("-f") + if tabix_mode: + cmd.append("-T") + if uncompressed: + cmd.append("-u") + if auto_offset: + cmd.append("-a") + + cmd.append(str(input_file)) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + output_index_file = Path(f"{input_file}.px2") + if not output_index_file.is_file(): + raise FileNotFoundError(f"Index file was not created: {output_index_file}. Stderr: {result.stderr}") + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_index_file)] + } + except FileNotFoundError: + raise RuntimeError("pairix command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"pairix indexing failed with return code {e.returncode}: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Pairix indexing failed.", + "return_code": e.returncode + } + +@mcp.tool() +def pairix_query( + indexed_file: Path, + region1: Optional[str] = None, + region2: Optional[str] = None, + query_file: Optional[Path] = None, + uncompressed: bool = False, +): + """ + Queries a pairix-indexed file for specific genomic regions. + + Args: + indexed_file: Path to the indexed pairs file. + region1: The first query region (e.g., "chr1:100-200"). + region2: The second query region. + query_file: A file containing query regions, one per line. + uncompressed: Input file is uncompressed. + """ + # Input validation + if not indexed_file.is_file(): + raise FileNotFoundError(f"Indexed file not found: {indexed_file}") + + index_file = Path(f"{indexed_file}.px2") + if not index_file.is_file(): + raise FileNotFoundError(f"Index file not found for {indexed_file}. Expected at {index_file}") + + if not region1 and not query_file: + raise ValueError("Either 'region1' or 'query_file' must be provided for querying.") + + if region1 and query_file: + raise ValueError("'region1' and 'query_file' are mutually exclusive.") + + if query_file and not query_file.is_file(): + raise FileNotFoundError(f"Query file not found: {query_file}") + + cmd = ["pairix"] + if uncompressed: + cmd.append("-u") + + cmd.append(str(indexed_file)) + + if query_file: + cmd.extend(["-q", str(query_file)]) + elif region1: + cmd.append(region1) + if region2: + cmd.append(region2) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("pairix command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"pairix query failed with return code {e.returncode}: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Pairix query failed.", + "return_code": e.returncode + } + +@mcp.tool() +def pairix_merge( + input_files: List[Path], + output_file: Path, + threads: int = 1, + print_merge_log: bool = False, +): + """ + Merges multiple bgzipped and pairix-indexed files. + + Args: + input_files: A list of paths to the input files to merge. + output_file: Path to the merged output file. + threads: Number of threads for merging. + print_merge_log: Print a log of merged lines during merging to stderr. + """ + # Input validation + if not input_files: + raise ValueError("At least one input file must be provided for merging.") + + for f in input_files: + if not f.is_file(): + raise FileNotFoundError(f"Input file not found: {f}") + + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["pairix"] + + if print_merge_log: + cmd.append("-M") + + if threads > 1: + cmd.extend(["-t", str(threads)]) + + file_list_str = ",".join(map(str, input_files)) + cmd.extend(["-m", file_list_str]) + + command_executed = " ".join(cmd) + f" > {output_file}" + logging.info(f"Executing command: {command_executed}") + + try: + with open(output_file, "w") as f_out: + result = subprocess.run( + cmd, + stdout=f_out, + stderr=subprocess.PIPE, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": f"Output successfully written to {output_file}", + "stderr": result.stderr, + "output_files": [str(output_file)] + } + except FileNotFoundError: + raise RuntimeError("pairix command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"pairix merge failed with return code {e.returncode}: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr, + "error": "Pairix merge failed.", + "return_code": e.returncode + } + +@mcp.tool() +def pairix_list_chroms( + indexed_file: Path, +): + """ + Lists chromosome names from a pairix index file. + + Args: + indexed_file: Path to the indexed pairs file. + """ + # Input validation + if not indexed_file.is_file(): + raise FileNotFoundError(f"Indexed file not found: {indexed_file}") + + index_file = Path(f"{indexed_file}.px2") + if not index_file.is_file(): + raise FileNotFoundError(f"Index file not found for {indexed_file}. Expected at {index_file}") + + cmd = ["pairix", "-l", str(indexed_file)] + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("pairix command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"pairix list-chroms failed with return code {e.returncode}: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Pairix list-chroms failed.", + "return_code": e.returncode + } + +@mcp.tool() +def pairix_line_count( + indexed_file: Path, +): + """ + Prints the number of pairs in a pairix-indexed file. + + Args: + indexed_file: Path to the indexed pairs file. + """ + # Input validation + if not indexed_file.is_file(): + raise FileNotFoundError(f"Indexed file not found: {indexed_file}") + + index_file = Path(f"{indexed_file}.px2") + if not index_file.is_file(): + raise FileNotFoundError(f"Index file not found for {indexed_file}. Expected at {index_file}") + + cmd = ["pairix", "-n", str(indexed_file)] + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("pairix command not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"pairix line-count failed with return code {e.returncode}: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Pairix line-count failed.", + "return_code": e.returncode + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/pairix_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/pairix_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4286581416660239f20d4f4cd74ea9abe134bc0e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/pairix_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_pairix/app/pairix_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_pairix' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7f0a905a9bda6f5e81efd5c35dd3accced41c2db --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-pairix: + build: . + image: mcp-pairix:latest + container_name: mcp-pairix + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=pairix + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ee5161e1a13a57aff2565e457aa05a89b70ccf2f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - pairix + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pairix/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pandaseq/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pandaseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pandaseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pangolin/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pangolin/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pangolin/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..23d2502717f7eb6e84fdd0174bdbdd605fb972f2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-algorithm-diff via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-algorithm-diff -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-algorithm-diff_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-algorithm-diff_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-algorithm-diff_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/__pycache__/perl-algorithm-diff_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/__pycache__/perl-algorithm-diff_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6454f074969ed8d56046a43c4df205abffb91b7 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/__pycache__/perl-algorithm-diff_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/perl-algorithm-diff_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/perl-algorithm-diff_server.py new file mode 100644 index 0000000000000000000000000000000000000000..81541e06083c9ea94ec0f54004bc4d92613f40da --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/perl-algorithm-diff_server.py @@ -0,0 +1,244 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_algorithm_diff' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_algorithm_diff( + file1: str, + file2: str, +) -> Dict[str, Any]: + """ + Compute 'intelligent' differences between two files using the Perl Algorithm::Diff module. + This tool provides a basic diff output showing additions, deletions, and changes. + + Args: + file1: Path to the first input file. + file2: Path to the second input file. + """ + # Input validation + path1 = Path(file1) + path2 = Path(file2) + + if not path1.is_file(): + return {"error": f"File not found: {file1}"} + if not path2.is_file(): + return {"error": f"File not found: {file2}"} + + # Perl script to use Algorithm::Diff + # Format: [sign, line_index, line_content] + # signs: - (removed from file1), + (added to file2) + perl_script = """ +use Algorithm::Diff qw(diff); +open my $fh1, '<', $ARGV[0] or die "Cannot open $ARGV[0]: $!"; +open my $fh2, '<', $ARGV[1] or die "Cannot open $ARGV[1]: $!"; +chomp(my @seq1 = <$fh1>); +chomp(my @seq2 = <$fh2>); +close $fh1; +close $fh2; + +my $diffs = diff(\\@seq1, \\@seq2); +foreach my $chunk (@$diffs) { + foreach my $line (@$chunk) { + print join("\t", @$line), "\n"; + } + print "----\n"; +} +""" + + cmd = ["perl", "-MAlgorithm::Diff", "-e", perl_script, str(path1), str(path2)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed: {str(e)}" + } + +@mcp.tool() +def perl_algorithm_sdiff( + file1: str, + file2: str, +) -> Dict[str, Any]: + """ + Compute side-by-side differences (sdiff) between two files using Perl Algorithm::Diff. + Returns a list of changes where each line is marked as: + u: unchanged, +: added, -: deleted, c: changed. + + Args: + file1: Path to the first input file. + file2: Path to the second input file. + """ + path1 = Path(file1) + path2 = Path(file2) + + if not path1.is_file(): + return {"error": f"File not found: {file1}"} + if not path2.is_file(): + return {"error": f"File not found: {file2}"} + + # Perl script for sdiff + # Output format: status | left_val | right_val + perl_script = """ +use Algorithm::Diff qw(sdiff); +open my $fh1, '<', $ARGV[0] or die "Cannot open $ARGV[0]: $!"; +open my $fh2, '<', $ARGV[1] or die "Cannot open $ARGV[1]: $!"; +chomp(my @seq1 = <$fh1>); +chomp(my @seq2 = <$fh2>); +close $fh1; +close $fh2; + +my @sdiffs = sdiff(\\@seq1, \\@seq2); +foreach my $row (@sdiffs) { + # $row is [status, left, right] + print join(" | ", map { defined $_ ? $_ : "" } @$row), "\n"; +} +""" + + cmd = ["perl", "-MAlgorithm::Diff", "-e", perl_script, str(path1), str(path2)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed: {str(e)}" + } + +@mcp.tool() +def perl_algorithm_lcs( + file1: str, + file2: str, +) -> Dict[str, Any]: + """ + Find the Longest Common Subsequence (LCS) between two files using Perl Algorithm::Diff. + This returns the lines that are common to both files in the order they appear. + + Args: + file1: Path to the first input file. + file2: Path to the second input file. + """ + path1 = Path(file1) + path2 = Path(file2) + + if not path1.is_file(): + return {"error": f"File not found: {file1}"} + if not path2.is_file(): + return {"error": f"File not found: {file2}"} + + # Perl script for LCS + perl_script = """ +use Algorithm::Diff qw(LCS); +open my $fh1, '<', $ARGV[0] or die "Cannot open $ARGV[0]: $!"; +open my $fh2, '<', $ARGV[1] or die "Cannot open $ARGV[1]: $!"; +chomp(my @seq1 = <$fh1>); +chomp(my @seq2 = <$fh2>); +close $fh1; +close $fh2; + +my @lcs = LCS(\\@seq1, \\@seq2); +foreach my $line (@lcs) { + print $line, "\n"; +} +""" + + cmd = ["perl", "-MAlgorithm::Diff", "-e", perl_script, str(path1), str(path2)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed: {str(e)}" + } + +@mcp.tool() +def perl_algorithm_diff_compact( + file1: str, + file2: str, +) -> Dict[str, Any]: + """ + Compute differences between two files and return a compact representation + of the changes (hunks) using Perl Algorithm::Diff. + + Args: + file1: Path to the first input file. + file2: Path to the second input file. + """ + path1 = Path(file1) + path2 = Path(file2) + + if not path1.is_file(): + return {"error": f"File not found: {file1}"} + if not path2.is_file(): + return {"error": f"File not found: {file2}"} + + # Perl script for compact diff (using the OO interface for more control) + perl_script = """ +use Algorithm::Diff; +open my $fh1, '<', $ARGV[0] or die; +open my $fh2, '<', $ARGV[1] or die; +chomp(my @seq1 = <$fh1>); +chomp(my @seq2 = <$fh2>); +close $fh1; +close $fh2; + +my $diff = Algorithm::Diff->new(\\@seq1, \\@seq2); +while ($diff->Next()) { + next if $diff->Same(); + my $sep = $diff->Items(2) ? "," : ""; + printf "Hunk at lines %d (file1) and %d (file2):\\n", $diff->Get(qw( Min1 Min2 )); + print " - " . join("\\n - ", $diff->Items(1)) . "\\n" if $diff->Items(1); + print " + " . join("\\n + ", $diff->Items(2)) . "\\n" if $diff->Items(2); +} +""" + + cmd = ["perl", "-MAlgorithm::Diff", "-e", perl_script, str(path1), str(path2)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed: {str(e)}" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/perl-algorithm-diff_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/perl-algorithm-diff_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7518ac0afa52aa2e7ddd026e6baccdb4f54b57c2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/perl-algorithm-diff_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-algorithm-diff/app/perl-algorithm-diff_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_algorithm_diff' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cdaac2a82a31184f823e7c46d78ce457516155c3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-algorithm-diff: + build: . + image: mcp-perl-algorithm-diff:latest + container_name: mcp-perl-algorithm-diff + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-algorithm-diff + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8670cf074f4d25da5554c595dd0434d4272df75e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-algorithm-diff + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-algorithm-diff/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5a8d6b140b1580c3d454121ab276103c88ba1271 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-archive-tar via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-archive-tar -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-archive-tar_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-archive-tar_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-archive-tar_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/__pycache__/perl-archive-tar_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/__pycache__/perl-archive-tar_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c1160a8f2f2d203bb5fc64f8bc9d6ada872379f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/__pycache__/perl-archive-tar_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/perl-archive-tar_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/perl-archive-tar_server.py new file mode 100644 index 0000000000000000000000000000000000000000..772ec0ef18b043a2bf262d1e1cba07d25d783904 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/perl-archive-tar_server.py @@ -0,0 +1,387 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# The mcp object is assumed to be provided by the execution environment. +# @mcp.tool() is the required decorator format. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_archive_tar' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def create_archive( + output_archive: Path, + input_files: List[Path], + compression: str = "none", + prefix: Optional[str] = None, + working_directory: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Creates a tar archive from a list of files or directories using Archive::Tar. + + Args: + output_archive: The path to the output tar archive to be created. + input_files: A list of files or directories to add to the archive. + compression: The compression type to use. Valid options: 'none', 'gzip', 'bzip2', 'xz'. + prefix: An optional prefix directory to prepend to all file paths within the archive. + working_directory: The directory from which to run the command. Relative input paths will be resolved from here. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output archive. + """ + # --- Input Validation --- + if not input_files: + raise ValueError("The 'input_files' list cannot be empty.") + + valid_compressions = ["none", "gzip", "bzip2", "xz"] + if compression not in valid_compressions: + raise ValueError(f"Invalid compression type '{compression}'. Must be one of {valid_compressions}.") + + if working_directory: + if not working_directory.is_dir(): + raise FileNotFoundError(f"Working directory '{working_directory}' does not exist or is not a directory.") + # Resolve input files relative to the working directory for existence check + resolved_input_files = [working_directory / f for f in input_files] + else: + resolved_input_files = input_files + + for f in resolved_input_files: + if not f.exists(): + raise FileNotFoundError(f"Input file or directory '{f}' does not exist.") + + # --- Perl Script Generation --- + perl_script_content = f""" + use strict; + use warnings; + use Archive::Tar; + use Getopt::Long; + + # Define constants for compression if not already available + BEGIN {{ + eval {{ require Archive::Tar::Constant; Archive::Tar::Constant->import() }}; + *COMPRESS_GZIP = \\&Archive::Tar::COMPRESS_GZIP unless defined &COMPRESS_GZIP; + *COMPRESS_BZIP = \\&Archive::Tar::COMPRESS_BZIP unless defined &COMPRESS_BZIP; + *COMPRESS_XZ = \\&Archive::Tar::COMPRESS_XZ unless defined &COMPRESS_XZ; + }} + + my $output_file; + my $compression_type = 'none'; + my $prefix = ''; + my @files; + + GetOptions( + 'output=s' => \\$output_file, + 'compression=s' => \\$compression_type, + 'prefix=s' => \\$prefix, + 'file=s@{{,}}' => \\@files, + ) or die "Error in command line arguments\\n"; + + die "Output file not specified\\n" unless $output_file; + die "No input files specified\\n" unless @files; + + my $tar = Archive::Tar->new(); + $tar->add_files(@files); + + my $compress_flag; + if ($compression_type eq 'gzip') {{ + $compress_flag = COMPRESS_GZIP; + }} elsif ($compression_type eq 'bzip2') {{ + $compress_flag = COMPRESS_BZIP; + }} elsif ($compression_type eq 'xz') {{ + $compress_flag = COMPRESS_XZ; + }} else {{ + $compress_flag = 0; # No compression + }} + + if ($prefix) {{ + $tar->write($output_file, $compress_flag, $prefix); + }} else {{ + $tar->write($output_file, $compress_flag); + }} + + if ($tar->error) {{ + die "Failed to write archive: " . $tar->error; + }} + + print "Archive '$output_file' created successfully.\\n"; + """ + + # --- Command Construction and Execution --- + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".pl", delete=False) as script_file: + script_file.write(perl_script_content) + script_path = script_file.name + + cmd = ["perl", script_path] + cmd.extend(["--output", str(output_archive)]) + cmd.extend(["--compression", compression]) + if prefix: + cmd.extend(["--prefix", prefix]) + for f in input_files: # Use original relative paths for the command + cmd.extend(["--file", str(f)]) + + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + cwd=working_directory, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_archive)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl script execution failed.", + "return_code": e.returncode, + } + finally: + if script_path: + Path(script_path).unlink() + + +@mcp.tool() +def extract_archive( + input_archive: Path, + output_directory: Optional[Path] = None, + files_to_extract: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Extracts files from a tar archive using Archive::Tar. + + Args: + input_archive: The path to the input tar archive. + output_directory: The directory to extract files into. Defaults to the current working directory. + files_to_extract: An optional list of specific file paths to extract from the archive. If not provided, all files are extracted. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of extracted file paths. + """ + # --- Input Validation --- + if not input_archive.is_file(): + raise FileNotFoundError(f"Input archive '{input_archive}' does not exist or is not a file.") + + # --- Perl Script Generation --- + perl_script_content = """ + use strict; + use warnings; + use Archive::Tar; + use Getopt::Long; + use File::Spec; + use Cwd; + + my $input_file; + my $output_dir = '.'; + my @files_to_extract; + + GetOptions( + 'input=s' => \\$input_file, + 'output-dir=s' => \\$output_dir, + 'extract-file=s@{{,}}' => \\@files_to_extract, + ) or die "Error in command line arguments\\n"; + + die "Input archive not specified\\n" unless $input_file; + + my $tar = Archive::Tar->new; + unless ($tar->read($input_file, 1)) { # 1 for compressed + die "Failed to read archive: " . $tar->error; + } + + # Change to output directory before extracting + my $original_cwd = cwd(); + mkdir $output_dir unless -d $output_dir; + chdir $output_dir or die "Cannot chdir to $output_dir: $!\\n"; + + my @extracted; + if (@files_to_extract) { + @extracted = $tar->extract(@files_to_extract); + } else { + @extracted = $tar->extract(); + } + + if ($tar->error) { + chdir $original_cwd; + die "Failed during extraction: " . $tar->error; + } + + # Go back to original directory + chdir $original_cwd; + + print "Extracted " . scalar(@extracted) . " files.\\n"; + foreach my $file (@extracted) { + print "$file\\n"; + } + """ + + # --- Command Construction and Execution --- + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".pl", delete=False) as script_file: + script_file.write(perl_script_content) + script_path = script_file.name + + cmd = ["perl", script_path] + cmd.extend(["--input", str(input_archive)]) + + if output_directory: + output_directory.mkdir(parents=True, exist_ok=True) + cmd.extend(["--output-dir", str(output_directory)]) + output_base = output_directory + else: + output_base = Path.cwd() + + if files_to_extract: + for f in files_to_extract: + cmd.extend(["--extract-file", f]) + + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + # Parse stdout to get the list of extracted files + # The perl script prints a summary line first, which we skip. + extracted_files = [str(output_base / f) for f in result.stdout.strip().split('\n')[1:] if f] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": extracted_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl script execution failed.", + "return_code": e.returncode, + } + finally: + if script_path: + Path(script_path).unlink() + + +@mcp.tool() +def list_archive( + input_archive: Path, + properties: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Lists the contents of a tar archive using Archive::Tar. + + Args: + input_archive: The path to the input tar archive. + properties: An optional list of properties to display for each file. If not provided, only file names are listed. + Valid properties: name, size, mtime, mode, uid, gid, linkname, uname, gname, devmajor, devminor, prefix. + + Returns: + A dictionary containing the command executed, stdout (the list of files/properties), and stderr. + """ + # --- Input Validation --- + if not input_archive.is_file(): + raise FileNotFoundError(f"Input archive '{input_archive}' does not exist or is not a file.") + + valid_properties = [ + "name", "size", "mtime", "mode", "uid", "gid", "linkname", + "uname", "gname", "devmajor", "devminor", "prefix" + ] + if properties: + for prop in properties: + if prop not in valid_properties: + raise ValueError(f"Invalid property '{prop}'. Must be one of {valid_properties}.") + + # --- Perl Script Generation --- + perl_script_content = """ + use strict; + use warnings; + use Archive::Tar; + use Getopt::Long; + + my $input_file; + my @properties; + + GetOptions( + 'input=s' => \\$input_file, + 'property=s@{{,}}' => \\@properties, + ) or die "Error in command line arguments\\n"; + + die "Input archive not specified\\n" unless $input_file; + + my $tar = Archive::Tar->new; + unless ($tar->read($input_file, 1)) { # 1 for compressed + die "Failed to read archive: " . $tar->error; + } + + if (@properties) { + my @file_info = $tar->list_files({properties => \\@properties}); + # Print header + print join("\\t", @properties), "\\n"; + foreach my $info (@file_info) { + my @values; + foreach my $prop (@properties) { + push @values, (defined $info->{$prop} ? $info->{$prop} : ''); + } + print join("\\t", @values), "\\n"; + } + } else { + my @files = $tar->list_files(); + foreach my $file (@files) { + print "$file\\n"; + } + } + """ + + # --- Command Construction and Execution --- + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".pl", delete=False) as script_file: + script_file.write(perl_script_content) + script_path = script_file.name + + cmd = ["perl", script_path] + cmd.extend(["--input", str(input_archive)]) + if properties: + for prop in properties: + cmd.extend(["--property", prop]) + + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl script execution failed.", + "return_code": e.returncode, + } + finally: + if script_path: + Path(script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/perl-archive-tar_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/perl-archive-tar_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..32ad41daebe08d6b629a1431ba045b8c8ed5705e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/perl-archive-tar_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-archive-tar/app/perl-archive-tar_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_archive_tar' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..45a8f02de36ef796cac5e788d78bd6e6a0286793 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-archive-tar: + build: . + image: mcp-perl-archive-tar:latest + container_name: mcp-perl-archive-tar + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-archive-tar + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..57f669f9a81e6ff4a93cdf75503f13e67eca538a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-archive-tar + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-archive-tar/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bioperl/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bioperl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bioperl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-class-load-xs/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-class-load-xs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-class-load-xs/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-devel-globaldestruction/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-devel-globaldestruction/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-devel-globaldestruction/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dynaloader/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dynaloader/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dynaloader/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0125d3455f512f75cd7293a240bb35ba1c20914d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-ffi-checklib via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-ffi-checklib -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-ffi-checklib_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-ffi-checklib_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-ffi-checklib_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/__pycache__/perl-ffi-checklib_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/__pycache__/perl-ffi-checklib_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..606844d3b73a17db38bf01da637c7abf565e11ca Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/__pycache__/perl-ffi-checklib_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/perl-ffi-checklib_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/perl-ffi-checklib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fff7136b366091edf1952a04b29a7539587c1a8e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/perl-ffi-checklib_server.py @@ -0,0 +1,573 @@ +import subprocess +import json +import os +from pathlib import Path +from typing import List, Optional, Union, Dict, Any +import tempfile + +# Helper to build Perl arguments string for FFI::CheckLib functions +def _build_perl_args( + lib: Optional[Union[str, List[str]]] = None, + libpath: Optional[Union[str, List[str]]] = None, + systempath: Optional[Union[str, List[str]]] = None, + symbol: Optional[Union[str, List[str]]] = None, + recursive: bool = False, + try_linker_script: bool = False, + alien: Optional[Union[str, List[str]]] = None, +) -> str: + """ + Constructs a Perl hash argument string from Python parameters. + """ + args = [] + + def format_list(items: List[str]) -> str: + """Formats a Python list into a Perl array string.""" + return f"[{', '.join(f'{repr(item)}' for item in items)}]" + + if lib is not None: + if isinstance(lib, list): + args.append(f"lib => {format_list(lib)}") + else: + args.append(f"lib => {repr(lib)}") + + if libpath is not None: + if isinstance(libpath, list): + args.append(f"libpath => {format_list(libpath)}") + else: + args.append(f"libpath => {repr(libpath)}") + + if systempath is not None: + if isinstance(systempath, list): + args.append(f"systempath => {format_list(systempath)}") + else: + args.append(f"systempath => {repr(systempath)}") + + if symbol is not None: + if isinstance(symbol, list): + args.append(f"symbol => {format_list(symbol)}") + else: + args.append(f"symbol => {repr(symbol)}") + + if recursive: + args.append("recursive => 1") + + if try_linker_script: + args.append("try_linker_script => 1") + + if alien is not None: + if isinstance(alien, list): + args.append(f"alien => {format_list(alien)}") + else: + args.append(f"alien => {repr(alien)}") + + return ', '.join(args) + +# Helper to run Perl script and parse JSON output +def _run_perl_ffi_checklib_script( + perl_code: str, + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes a Perl script using FFI::CheckLib and captures its output. + Attempts to parse stdout as JSON. + """ + temp_script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.pl', encoding='utf-8') as temp_script: + temp_script.write(perl_code) + temp_script_path = Path(temp_script.name) + + command = ["perl", str(temp_script_path)] + env = os.environ.copy() + if ffi_checklib_package: + env["FFI_CHECKLIB_PACKAGE"] = ffi_checklib_package + if ffi_checklib_path: + env["FFI_CHECKLIB_PATH"] = ffi_checklib_path + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + env=env + ) + stdout = process.stdout.strip() + stderr = process.stderr.strip() + + parsed_output = None + if stdout: + try: + parsed_output = json.loads(stdout) + except json.JSONDecodeError: + # If stdout is not JSON, return it as raw string + parsed_output = stdout + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output": parsed_output, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Perl script failed with exit code {e.returncode}", + "output_files": [], + } + finally: + if temp_script_path and temp_script_path.exists(): + os.unlink(temp_script_path) + +# Helper for validating FFI_CHECKLIB_PACKAGE +def _validate_ffi_checklib_package(ffi_checklib_package: Optional[str]): + if ffi_checklib_package is not None: + allowed_packages = ["none", "homebrew", "macports"] + packages = [p.strip() for p in ffi_checklib_package.split(',')] + if not all(p in allowed_packages for p in packages): + raise ValueError( + f"Invalid value for ffi_checklib_package. Allowed values: " + f"{', '.join(allowed_packages)}, comma-separated." + ) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_ffi_checklib' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def find_lib( + lib: Union[str, List[str]], + libpath: Optional[Union[str, List[str]]] = None, + systempath: Optional[Union[str, List[str]]] = None, + symbol: Optional[Union[str, List[str]]] = None, + recursive: bool = False, + try_linker_script: bool = False, + alien: Optional[Union[str, List[str]]] = None, + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Finds dynamic libraries available for FFI. + + Returns a list of full paths to dynamic libraries found, or an empty list if none were found. + Note: The 'verify' argument (a Perl code reference) is not supported in this MCP tool. + """ + if not lib: + raise ValueError("The 'lib' parameter cannot be empty.") + _validate_ffi_checklib_package(ffi_checklib_package) + + perl_args_str = _build_perl_args( + lib=lib, + libpath=libpath, + systempath=systempath, + symbol=symbol, + recursive=recursive, + try_linker_script=try_linker_script, + alien=alien, + ) + + perl_code = f""" +use FFI::CheckLib; +use JSON; +my @found_libs = FFI::CheckLib::find_lib({perl_args_str}); +print to_json(\\@found_libs); +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" in result: + return result + + if isinstance(result.get("output"), list): + result["output"] = [Path(item) for item in result["output"] if isinstance(item, str)] + elif isinstance(result.get("output"), str) and result["output"]: + result["output"] = [Path(result["output"])] + else: + result["output"] = [] + + return result + +@mcp.tool() +def assert_lib( + lib: Union[str, List[str]], + libpath: Optional[Union[str, List[str]]] = None, + systempath: Optional[Union[str, List[str]]] = None, + symbol: Optional[Union[str, List[str]]] = None, + recursive: bool = False, + try_linker_script: bool = False, + alien: Optional[Union[str, List[str]]] = None, + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Asserts that a dynamic library is available for FFI. + + Behaves exactly like `find_lib`, but throws an exception (Perl `die`) if no libraries are found. + Returns a list of full paths to dynamic libraries found on success. + Note: The 'verify' argument (a Perl code reference) is not supported in this MCP tool. + """ + if not lib: + raise ValueError("The 'lib' parameter cannot be empty.") + _validate_ffi_checklib_package(ffi_checklib_package) + + perl_args_str = _build_perl_args( + lib=lib, + libpath=libpath, + systempath=systempath, + symbol=symbol, + recursive=recursive, + try_linker_script=try_linker_script, + alien=alien, + ) + + perl_code = f""" +use FFI::CheckLib; +use JSON; +my @found_libs = FFI::CheckLib::assert_lib({perl_args_str}); +print to_json(\\@found_libs); +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" in result: + return result + + if isinstance(result.get("output"), list): + result["output"] = [Path(item) for item in result["output"] if isinstance(item, str)] + elif isinstance(result.get("output"), str) and result["output"]: + result["output"] = [Path(result["output"])] + else: + result["output"] = [] + + return result + +@mcp.tool() +def check_lib_or_exit( + lib: Union[str, List[str]], + libpath: Optional[Union[str, List[str]]] = None, + systempath: Optional[Union[str, List[str]]] = None, + symbol: Optional[Union[str, List[str]]] = None, + recursive: bool = False, + try_linker_script: bool = False, + alien: Optional[Union[str, List[str]]] = None, + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Checks if a dynamic library is available for FFI and exits if not found. + + Intended for use in build scripts. If the library is not found, it will warn + and exit the Perl script with a non-zero status. On success, it returns a confirmation. + Note: The 'verify' argument (a Perl code reference) is not supported in this MCP tool. + """ + if not lib: + raise ValueError("The 'lib' parameter cannot be empty.") + _validate_ffi_checklib_package(ffi_checklib_package) + + perl_args_str = _build_perl_args( + lib=lib, + libpath=libpath, + systempath=systempath, + symbol=symbol, + recursive=recursive, + try_linker_script=try_linker_script, + alien=alien, + ) + + perl_code = f""" +use FFI::CheckLib; +FFI::CheckLib::check_lib_or_exit({perl_args_str}); +print "Library check successful."; +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" not in result: + result["output"] = "Library check successful." + else: + result["output"] = "Library check failed." + + return result + +@mcp.tool() +def find_lib_or_exit( + lib: Union[str, List[str]], + libpath: Optional[Union[str, List[str]]] = None, + systempath: Optional[Union[str, List[str]]] = None, + symbol: Optional[Union[str, List[str]]] = None, + recursive: bool = False, + try_linker_script: bool = False, + alien: Optional[Union[str, List[str]]] = None, + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Finds dynamic libraries and exits with a diagnostic if not found. + + Behaves exactly like `find_lib`, but if the library is not found, it will call + exit with an appropriate diagnostic. Returns a list of full paths to dynamic libraries found on success. + Note: The 'verify' argument (a Perl code reference) is not supported in this MCP tool. + """ + if not lib: + raise ValueError("The 'lib' parameter cannot be empty.") + _validate_ffi_checklib_package(ffi_checklib_package) + + perl_args_str = _build_perl_args( + lib=lib, + libpath=libpath, + systempath=systempath, + symbol=symbol, + recursive=recursive, + try_linker_script=try_linker_script, + alien=alien, + ) + + perl_code = f""" +use FFI::CheckLib; +use JSON; +my @found_libs = FFI::CheckLib::find_lib_or_exit({perl_args_str}); +print to_json(\\@found_libs); +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" in result: + return result + + if isinstance(result.get("output"), list): + result["output"] = [Path(item) for item in result["output"] if isinstance(item, str)] + elif isinstance(result.get("output"), str) and result["output"]: + result["output"] = [Path(result["output"])] + else: + result["output"] = [] + + return result + +@mcp.tool() +def find_lib_or_die( + lib: Union[str, List[str]], + libpath: Optional[Union[str, List[str]]] = None, + systempath: Optional[Union[str, List[str]]] = None, + symbol: Optional[Union[str, List[str]]] = None, + recursive: bool = False, + try_linker_script: bool = False, + alien: Optional[Union[str, List[str]]] = None, + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Finds dynamic libraries and dies with a diagnostic if not found. + + Behaves exactly like `find_lib`, but if the library is not found, it will die + with an appropriate diagnostic. Returns a list of full paths to dynamic libraries found on success. + Note: The 'verify' argument (a Perl code reference) is not supported in this MCP tool. + """ + if not lib: + raise ValueError("The 'lib' parameter cannot be empty.") + _validate_ffi_checklib_package(ffi_checklib_package) + + perl_args_str = _build_perl_args( + lib=lib, + libpath=libpath, + systempath=systempath, + symbol=symbol, + recursive=recursive, + try_linker_script=try_linker_script, + alien=alien, + ) + + perl_code = f""" +use FFI::CheckLib; +use JSON; +my @found_libs = FFI::CheckLib::find_lib_or_die({perl_args_str}); +print to_json(\\@found_libs); +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" in result: + return result + + if isinstance(result.get("output"), list): + result["output"] = [Path(item) for item in result["output"] if isinstance(item, str)] + elif isinstance(result.get("output"), str) and result["output"]: + result["output"] = [Path(result["output"])] + else: + result["output"] = [] + + return result + +@mcp.tool() +def check_lib( + lib: Union[str, List[str]], + libpath: Optional[Union[str, List[str]]] = None, + systempath: Optional[Union[str, List[str]]] = None, + symbol: Optional[Union[str, List[str]]] = None, + recursive: bool = False, + try_linker_script: bool = False, + alien: Optional[Union[str, List[str]]] = None, + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Checks if a dynamic library is available for FFI. + + Returns true (1) if the appropriate libraries are found, or false (0) otherwise. + Note: The 'verify' argument (a Perl code reference) is not supported in this MCP tool. + """ + if not lib: + raise ValueError("The 'lib' parameter cannot be empty.") + _validate_ffi_checklib_package(ffi_checklib_package) + + perl_args_str = _build_perl_args( + lib=lib, + libpath=libpath, + systempath=systempath, + symbol=symbol, + recursive=recursive, + try_linker_script=try_linker_script, + alien=alien, + ) + + perl_code = f""" +use FFI::CheckLib; +use JSON; +my $bool_result = FFI::CheckLib::check_lib({perl_args_str}); +print to_json($bool_result ? \1 : \0); +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" in result: + return result + + output = result.get("output") + result["output"] = bool(output) + + return result + +@mcp.tool() +def which( + name: str, + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Returns the path to the first dynamic library that matches the given name. + """ + if not name: + raise ValueError("The 'name' parameter cannot be empty.") + _validate_ffi_checklib_package(ffi_checklib_package) + + perl_code = f""" +use FFI::CheckLib; +use JSON; +my $path = FFI::CheckLib::which({repr(name)}); +print to_json($path); +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" in result: + return result + + output = result.get("output") + if isinstance(output, str) and output: + result["output"] = Path(output) + else: + result["output"] = None + + return result + +@mcp.tool() +def where( + name: str, + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Returns the paths to all dynamic libraries that match the given name. + """ + if not name: + raise ValueError("The 'name' parameter cannot be empty.") + _validate_ffi_checklib_package(ffi_checklib_package) + + perl_code = f""" +use FFI::CheckLib; +use JSON; +my @paths = FFI::CheckLib::where({repr(name)}); +print to_json(\\@paths); +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" in result: + return result + + if isinstance(result.get("output"), list): + result["output"] = [Path(item) for item in result["output"] if isinstance(item, str)] + else: + result["output"] = [] + + return result + +@mcp.tool() +def has_symbols( + path: Path, + symbol_names: List[str], + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Checks if all specified symbols can be found in the dynamic library located at the given path. + """ + if not path.is_file(): + raise FileNotFoundError(f"Library file not found at: {path}") + if not symbol_names: + raise ValueError("The 'symbol_names' parameter cannot be empty.") + _validate_ffi_checklib_package(ffi_checklib_package) + + symbol_list_str = ', '.join(f"{repr(s)}" for s in symbol_names) + + perl_code = f""" +use FFI::CheckLib; +use JSON; +my $bool_result = FFI::CheckLib::has_symbols({repr(str(path))}, {symbol_list_str}); +print to_json($bool_result ? \1 : \0); +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" in result: + return result + + output = result.get("output") + result["output"] = bool(output) + + return result + +@mcp.tool() +def system_path( + ffi_checklib_package: Optional[str] = None, + ffi_checklib_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Returns the system path as a list of directories where dynamic libraries are searched. + """ + _validate_ffi_checklib_package(ffi_checklib_package) + + perl_code = f""" +use FFI::CheckLib; +use JSON; +my $path_ref = FFI::CheckLib::system_path(); +print to_json($path_ref); +""" + result = _run_perl_ffi_checklib_script(perl_code, ffi_checklib_package, ffi_checklib_path) + + if "error" in result: + return result + + if isinstance(result.get("output"), list): + result["output"] = [Path(item) for item in result["output"] if isinstance(item, str)] + else: + result["output"] = [] + + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/perl-ffi-checklib_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/perl-ffi-checklib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1cd1fc768cad97992d72e52132589ee561c03d6f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/perl-ffi-checklib_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ffi-checklib/app/perl-ffi-checklib_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_ffi_checklib' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..85e6af84643eec569195b50775817ff9453b29f2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-ffi-checklib: + build: . + image: mcp-perl-ffi-checklib:latest + container_name: mcp-perl-ffi-checklib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-ffi-checklib + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..de5049454375ae348ded8fa5140a99475d09f7d4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-ffi-checklib + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ffi-checklib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e85541f17667c010fbbaada30c170c150858da9f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-image-size via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-image-size -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-image-size_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-image-size_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-image-size_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/__pycache__/perl-image-size_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/__pycache__/perl-image-size_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ca07a050117e0005616bc0e9e74f883e6997d30 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/__pycache__/perl-image-size_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/perl-image-size_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/perl-image-size_server.py new file mode 100644 index 0000000000000000000000000000000000000000..61cbcf78d0bd1ad62bef145cbf5680931096ad0f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/perl-image-size_server.py @@ -0,0 +1,122 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, Any, Optional + +# from mcp import mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_image_size' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def image_size( + image_file: Path +) -> Dict[str, Any]: + """ + Determines the width and height of an image file using the Perl Image::Size library. + + This tool acts as a wrapper around the Perl 'Image::Size' module, which does not + provide a direct command-line executable. It dynamically creates and executes a + Perl script to extract the dimensions from the specified image file. + + Args: + image_file: The path to the input image file (e.g., JPG, PNG, GIF, etc.). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the + parsed width and height of the image. + """ + # 1. Input validation + if not image_file.is_file(): + raise FileNotFoundError(f"Input file not found: {image_file}") + + # 2. Perl script content + # This script uses the Image::Size module to get dimensions and prints them + # to stdout in a "width,height" format for easy parsing. + perl_script_content = r""" + use strict; + use warnings; + use Image::Size; + + # Get the image file path from the command line arguments + my $file = shift @ARGV; + + # Basic validation within the script + die "Usage: $0 \n" unless defined $file; + die "File not found or is not a regular file: $file\n" unless -f $file; + + # Get the image size + my ($width, $height) = imgsize($file); + + # Print the result in a machine-readable format if successful + if (defined $width && defined $height) { + print "$width,$height\n"; + } else { + # Print a descriptive error message to stderr if size could not be determined + my $error_msg = Image::Size::errormsg(); + print STDERR "Could not determine size for '$file': $error_msg\n"; + exit 1; + } + """ + + command_to_run = [] + try: + # 3. Create a temporary file for the Perl script + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".pl", encoding='utf-8') as tmp_script: + tmp_script.write(perl_script_content) + tmp_script.flush() # Ensure all content is written to disk + + command_to_run = ['perl', tmp_script.name, str(image_file)] + + # 4. Subprocess execution + process = subprocess.run( + command_to_run, + capture_output=True, + text=True, + check=True + ) + + # 5. Parse the output + stdout_clean = process.stdout.strip() + if not stdout_clean: + raise ValueError("Perl script produced no output to stdout.") + + width_str, height_str = stdout_clean.split(',') + width = int(width_str) + height = int(height_str) + + # 6. Return structured result + return { + "command_executed": " ".join(command_to_run), + "stdout": process.stdout, + "stderr": process.stderr, + "width": width, + "height": height, + "output_files": [] + } + + except FileNotFoundError: + raise RuntimeError("The 'perl' command was not found. Is Perl installed and in your system's PATH?") + except subprocess.CalledProcessError as e: + # This catches errors when the Perl script returns a non-zero exit code + return { + "command_executed": " ".join(command_to_run), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl script execution failed with a non-zero exit code.", + "output_files": [] + } + except (ValueError, IndexError) as e: + # This catches errors if the stdout format is not "width,height" + return { + "command_executed": " ".join(command_to_run), + "stdout": process.stdout if 'process' in locals() else "", + "stderr": process.stderr if 'process' in locals() else "", + "error": f"Failed to parse Perl script output. Expected 'width,height', got '{stdout_clean}'. Details: {e}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/perl-image-size_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/perl-image-size_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b555e5617221049bd13416a0607928fab36cee37 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/perl-image-size_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/perl-image-size_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_image_size' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ea360db949a356123325255905d6a1df2c49c518 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-image-size: + build: . + image: mcp-perl-image-size:latest + container_name: mcp-perl-image-size + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-image-size + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..957f2faa5f1ec2947f7e6cd91f6db1fb23184444 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-image-size + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-image-size/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e21e934802aaef34656fed68839e1e5f53b1ca62 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-importer via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-importer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-importer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-importer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-importer_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/__pycache__/perl-importer_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/__pycache__/perl-importer_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0890be8359f8fbbadc075daa1c7aa1ef08272cdd Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/__pycache__/perl-importer_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/perl-importer_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/perl-importer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51d506a1614733573678fa4cc6fec1435f67de --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/perl-importer_server.py @@ -0,0 +1,245 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_importer' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def install_perl_module( + module_name: str, + notest: bool = True, + force: bool = False, + local_lib: Optional[str] = None, + sudo: bool = False, +): + """ + Installs Perl modules using cpanm (App::cpanminus), a common requirement for + bioinformatics pipelines (e.g., BioPerl, VCFtools). + """ + # Input validation + if not module_name: + return {"error": "Module name must be provided"} + + command = [] + if sudo: + command.append("sudo") + + command.extend(["cpanm", module_name]) + + if notest: + command.append("--notest") + if force: + command.append("--force") + if local_lib: + lib_path = Path(local_lib) + command.extend(["-l", str(lib_path.absolute())]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Installation failed with exit code {e.returncode}" + } + except FileNotFoundError: + return {"error": "cpanm is not installed on the system. Please install App::cpanminus."} + +@mcp.tool() +def execute_perl_script( + script_path: str, + args: Optional[List[str]] = None, + perl5lib: Optional[str] = None, + include_path: Optional[str] = None, + warnings: bool = True, +): + """ + Executes a Perl script with specified arguments and environment variables. + Commonly used for running BioPerl scripts or custom bioinformatics parsers. + """ + script = Path(script_path) + if not script.exists(): + return {"error": f"Script not found at {script_path}"} + + command = ["perl"] + if warnings: + command.append("-w") + if include_path: + command.extend(["-I", include_path]) + + command.append(str(script.absolute())) + + if args: + command.extend(args) + + env = {} + if perl5lib: + env["PERL5LIB"] = perl5lib + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + env=env if env else None + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Perl scripts often output to stdout unless redirected + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Script execution failed with exit code {e.returncode}" + } + +@mcp.tool() +def check_perl_syntax( + script_path: str, + include_path: Optional[str] = None, +): + """ + Performs a syntax check on a Perl script (perl -c). + Useful for validating bioinformatics scripts before long-running pipeline execution. + """ + script = Path(script_path) + if not script.exists(): + return {"error": f"Script not found at {script_path}"} + + command = ["perl", "-c"] + if include_path: + command.extend(["-I", include_path]) + command.append(str(script.absolute())) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "valid": True + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "valid": False, + "error": "Syntax check failed" + } + +@mcp.tool() +def list_installed_perl_modules( + search_term: Optional[str] = None, +): + """ + Lists installed Perl modules or searches for a specific module. + Helps verify if bioinformatics dependencies like Bio::Seq or Bio::DB::Fasta are available. + """ + # Using perldoc -l is a reliable way to find module paths + if search_term: + command = ["perldoc", "-l", search_term] + else: + # Fallback to listing all modules via instmodsh (part of ExtUtils::Installed) + # This is a bit complex in shell, so we use a perl one-liner + command = ["perl", "-MExtUtils::Installed", "-e", "print join('\\n', ExtUtils::Installed->new()->modules())"] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "installed_modules": result.stdout.splitlines(), + "stdout": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stderr": e.stderr, + "error": "Could not retrieve module list. Ensure ExtUtils::Installed is available." + } + +@mcp.tool() +def bioperl_load_gff( + gff_file: str, + database_name: str, + db_type: str = "sqlite", + create: bool = True, + user: Optional[str] = None, + password: Optional[str] = None, +): + """ + Specialized importer tool for BioPerl's bp_seqfeature_load.pl. + Imports GFF3/GTF files into a SeqFeature database (SQLite, MySQL, or PostgreSQL). + """ + gff_path = Path(gff_file) + if not gff_path.exists(): + return {"error": f"GFF file not found: {gff_file}"} + + # Constructing the bp_seqfeature_load.pl command + command = ["bp_seqfeature_load.pl", "-d", database_name, "-f", db_type] + + if create: + command.append("-c") + if user: + command.extend(["-u", user]) + if password: + command.extend(["-p", password]) + + command.append(str(gff_path.absolute())) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "database": database_name, + "status": "Import completed" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"BioPerl GFF import failed: {e.stderr}" + } + except FileNotFoundError: + return {"error": "bp_seqfeature_load.pl not found. Is BioPerl installed?"} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/perl-importer_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/perl-importer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d27dd5811d3d0f49573c3ca075fd3ff03f3cd43f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/perl-importer_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/perl-importer_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_importer' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c7567e20b08ae22c47460f9f6c83554e2dc65c3f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-importer: + build: . + image: mcp-perl-importer:latest + container_name: mcp-perl-importer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-importer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dadb85fc3ebe13a606226fe218ba4cde9de05a44 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-importer + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-importer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..89d3c482c3ba55f7d1334e2163d7c54cea9ad674 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-html via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-html -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-html_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-html_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-html_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/__pycache__/perl-io-html_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/__pycache__/perl-io-html_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95c7c2f0620f1ccc3aa647ef77eb4148cdae1dd7 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/__pycache__/perl-io-html_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/perl-io-html_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/perl-io-html_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2dd196f548530d44f40ce9911791d7e21d4539f0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/perl-io-html_server.py @@ -0,0 +1,173 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_io_html' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def io_html_get_encoding( + file_path: str, +) -> Dict[str, Any]: + """ + Detects the character encoding of an HTML file using the HTML5 sniffing algorithm. + This is equivalent to the IO::HTML::html_file_and_encoding function. + + Args: + file_path: Path to the HTML file to analyze. + """ + path = Path(file_path) + if not path.exists(): + return {"error": f"File not found: {file_path}"} + if not path.is_file(): + return {"error": f"Path is not a file: {file_path}"} + + # Perl script to extract encoding and BOM status + # html_file_and_encoding returns ($filehandle, $encoding, $bom) + perl_cmd = [ + "perl", + "-MIO::HTML", + "-e", + 'my ($fh, $enc, $bom) = IO::HTML::html_file_and_encoding($ARGV[0]); ' + 'print "encoding:$enc\\n"; ' + 'print "bom:" . ($bom ? "true" : "false") . "\\n";', + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "detected_info": result.stdout.strip().split('\n') + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def io_html_read_content( + file_path: str, +) -> Dict[str, Any]: + """ + Opens an HTML file with the correctly detected encoding and returns its content. + This ensures that the HTML is read using the charset specified in the tags or BOM. + + Args: + file_path: Path to the HTML file to read. + """ + path = Path(file_path) + if not path.exists(): + return {"error": f"File not found: {file_path}"} + + # Perl script to open file with IO::HTML and print content to stdout + # We use binmode STDOUT :utf8 to ensure the output is passed correctly to the shell + perl_cmd = [ + "perl", + "-MIO::HTML", + "-e", + 'my $fh = IO::HTML::html_file($ARGV[0]); ' + 'binmode(STDOUT, ":utf8"); ' + 'while(<$fh>){ print $_; }', + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "content": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def io_html_sniff_encoding( + html_content: str, +) -> Dict[str, Any]: + """ + Sniffs the encoding from a string of HTML content. + Useful for detecting encoding of HTML data already in memory or from a stream. + + Args: + html_content: The raw HTML string/bytes to analyze for encoding. + """ + # We pass the content via a temporary file or stdin to avoid shell argument length limits + # Here we use a simple perl one-liner that takes the string as an argument + perl_cmd = [ + "perl", + "-MIO::HTML", + "-e", + 'my $encoding = IO::HTML::sniff_encoding($ARGV[0]); ' + 'print $encoding;', + html_content + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": "perl -MIO::HTML -e '...sniff_encoding...'", + "detected_encoding": result.stdout.strip(), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "perl -MIO::HTML -e '...sniff_encoding...'", + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def io_html_check_compatibility( + file_path: str, +) -> Dict[str, Any]: + """ + Checks if the IO::HTML module is correctly installed and can process the target file. + This is a diagnostic tool for the environment. + + Args: + file_path: Path to a sample HTML file. + """ + path = Path(file_path) + + perl_cmd = [ + "perl", + "-MIO::HTML", + "-e", + 'print "IO::HTML version: $IO::HTML::VERSION\\n"; ' + 'eval { IO::HTML::html_file($ARGV[0]) }; ' + 'if ($@) { print "Error: $@"; exit 1; } else { print "Status: OK\\n"; }', + str(path) if path.exists() else "" + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "error": "Module IO::HTML might not be installed or file is inaccessible.", + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/perl-io-html_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/perl-io-html_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..72c30f79f43b0f5816b98e67d3ab436abb315cbc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/perl-io-html_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/perl-io-html_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_io_html' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e8d588e44df8502d977f5fa6820119ac52ee8318 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-html: + build: . + image: mcp-perl-io-html:latest + container_name: mcp-perl-io-html + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-html + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cac91f069c11d84b42c72b87cfe6d73303945a06 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-html + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-html/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ipc-run/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ipc-run/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-ipc-run/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4cbbe0ed169a2427c11c1fbda20c83f14baf9dce --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-json via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-json -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-json_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-json_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-json_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/__pycache__/perl-json_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/__pycache__/perl-json_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf0ee3b1a1c0e19da7e486fa23121183f5581f41 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/__pycache__/perl-json_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/perl-json_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/perl-json_server.py new file mode 100644 index 0000000000000000000000000000000000000000..37cc314f6499ab8908c9d5abf397a8132b828a7e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/perl-json_server.py @@ -0,0 +1,276 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_json' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_json_encode( + perl_code: str, + ascii: bool = False, + utf8: bool = True, + pretty: bool = False, + canonical: bool = False, + allow_nonref: bool = True, + convert_blessed: bool = False, + space_before: bool = False, + space_after: bool = False, +): + """ + Encodes a Perl data structure into a JSON string using the perl-json module. + + Args: + perl_code: A string containing a Perl data structure (e.g., '{a => 1, b => [2, 3]}'). + ascii: If true, encodes non-ASCII characters as \\uXXXX escapes. + utf8: If true, produces UTF-8 encoded binary string. + pretty: Enables indent, space_before, and space_after for readable output. + canonical: Sorts object keys alphabetically. + allow_nonref: Allows encoding of non-reference scalars (strings, numbers, null). + convert_blessed: Allows encoding of blessed objects (requires TO_JSON method or universal conversion). + space_before: Adds a space before the ':' in key-value pairs. + space_after: Adds a space after the ':' and ',' in JSON. + """ + # Construct the Perl one-liner + # We use JSON->new and chain the methods based on parameters + perl_script = "use JSON; " + perl_script += "my $json = JSON->new;" + if ascii: perl_script += "$json->ascii(1);" + if utf8: perl_script += "$json->utf8(1);" + if pretty: perl_script += "$json->pretty(1);" + if canonical: perl_script += "$json->canonical(1);" + if allow_nonref: perl_script += "$json->allow_nonref(1);" + if convert_blessed: perl_script += "$json->convert_blessed(1);" + if space_before: perl_script += "$json->space_before(1);" + if space_after: perl_script += "$json->space_after(1);" + + # The eval(shift) takes the perl_code from the command line arguments + perl_script += "print $json->encode(eval(shift));" + + try: + result = subprocess.run( + ["perl", "-MJSON", "-e", perl_script, "--", perl_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MJSON -e '...' -- '{perl_code}'", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_json_decode( + json_text: str, + utf8: bool = True, + relaxed: bool = False, + allow_nonref: bool = True, + max_depth: int = 512, +): + """ + Decodes a JSON string into a Perl data structure representation (using Data::Dumper). + + Args: + json_text: The JSON string to decode. + utf8: If true, expects the input to be UTF-8 encoded. + relaxed: Allows shell-style comments and trailing commas in the JSON. + allow_nonref: Allows decoding of non-reference JSON values (scalars). + max_depth: Sets the maximum nesting depth for the JSON structure. + """ + if max_depth < 1: + max_depth = 512 + + perl_script = "use JSON; use Data::Dumper; " + perl_script += "$Data::Dumper::Terse = 1; $Data::Dumper::Indent = 1; " + perl_script += "my $json = JSON->new;" + if utf8: perl_script += "$json->utf8(1);" + if relaxed: perl_script += "$json->relaxed(1);" + if allow_nonref: perl_script += "$json->allow_nonref(1);" + perl_script += f"$json->max_depth({max_depth});" + + perl_script += "print Dumper($json->decode(shift));" + + try: + result = subprocess.run( + ["perl", "-MJSON", "-MData::Dumper", "-e", perl_script, "--", json_text], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MJSON -MData::Dumper -e '...' -- '{json_text}'", + "perl_structure": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_json_reformat_file( + input_file: str, + output_file: Optional[str] = None, + pretty: bool = True, + canonical: bool = True, + ascii: bool = False, + relaxed: bool = False, +): + """ + Reads a JSON file and reformats it (pretty-print or minify). + + Args: + input_file: Path to the input JSON file. + output_file: Path to save the reformatted JSON. If not provided, returns to stdout. + pretty: If true, produces human-readable indented output. + canonical: If true, sorts object keys. + ascii: If true, escapes non-ASCII characters. + relaxed: If true, allows comments and trailing commas in the input file. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + perl_script = "use JSON; use File::Slurp; " + # Note: Using a simple file read if File::Slurp isn't guaranteed, + # but standard perl-json users often have it. We'll use a core-only way for safety. + perl_script = ( + "use JSON; " + "undef $/; " + "my $content = <>; " + "my $json = JSON->new;" + ) + + if pretty: perl_script += "$json->pretty(1);" + if canonical: perl_script += "$json->canonical(1);" + if ascii: perl_script += "$json->ascii(1);" + if relaxed: perl_script += "$json->relaxed(1);" + + perl_script += "print $json->encode($json->decode($content));" + + cmd = ["perl", "-MJSON", "-e", perl_script, input_file] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + output_files = [] + if output_file: + out_path = Path(output_file) + out_path.write_text(result.stdout) + output_files.append(str(out_path)) + return { + "command_executed": " ".join(cmd), + "message": f"Reformatted JSON saved to {output_file}", + "output_files": output_files, + "status": "success" + } + else: + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_json_validate_file( + input_file: str, + relaxed: bool = False, +): + """ + Validates the syntax of a JSON file. + + Args: + input_file: Path to the JSON file to validate. + relaxed: If true, allows comments and trailing commas during validation. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + perl_script = ( + "use JSON; " + "undef $/; " + "my $content = <>; " + "my $json = JSON->new;" + ) + if relaxed: perl_script += "$json->relaxed(1);" + perl_script += "eval { $json->decode($content) }; if ($@) { die $@ } else { print 'Valid JSON' }" + + try: + result = subprocess.run( + ["perl", "-MJSON", "-e", perl_script, input_file], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MJSON -e '...' {input_file}", + "stdout": result.stdout, + "is_valid": True, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "is_valid": False, + "error_message": e.stderr.strip(), + "status": "invalid" + } + +@mcp.tool() +def perl_json_get_backend(): + """ + Identifies which backend module (JSON::XS, JSON::PP, or Cpanel::JSON::XS) is currently being used by the JSON module. + """ + perl_script = "use JSON; my $json = JSON->new; print $json->backend;" + + try: + result = subprocess.run( + ["perl", "-MJSON", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MJSON -e '{perl_script}'", + "backend": result.stdout, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "error": str(e), + "status": "error" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/perl-json_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/perl-json_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a19147395595fb7545254ffcf75fcad2b8351210 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/perl-json_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/perl-json_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_json' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..87a79e338c5c185eba1959ea07f471d116bc10f6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-json: + build: . + image: mcp-perl-json:latest + container_name: mcp-perl-json + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-json + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72ba2caaab2c492444ec46c032118d63bf77c146 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-json + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-json/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-lwp-simple/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-lwp-simple/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-lwp-simple/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e1c93b29d3e5a1566628158daa83817e3f62e05 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-math-bezier via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-math-bezier -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-math-bezier_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-math-bezier_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-math-bezier_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/__pycache__/perl-math-bezier_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/__pycache__/perl-math-bezier_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97972ec01f398a74939718422170f9a96a2ed6b5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/__pycache__/perl-math-bezier_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/perl-math-bezier_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/perl-math-bezier_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ae03a34bd531a4bf5cdafd745a7d7c3f40f0beb0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/perl-math-bezier_server.py @@ -0,0 +1,135 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP decorator is omitted as per instructions, but this is an MCP-ready tool. +# import mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_math_bezier' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_perl_script( + programfile: Optional[Path] = None, + program: Optional[str] = None, + arguments: Optional[List[str]] = None, + include_dirs: Optional[List[Path]] = None, + modules: Optional[List[str]] = None, + check_syntax_only: bool = False, + enable_warnings: bool = False, + disable_warnings: bool = False, + enable_all_warnings: bool = False, + enable_taint_checks: bool = False, + enable_optional_features_for_program: bool = False, +) -> dict: + """ + Executes a Perl script using the Perl interpreter. + + This tool serves as a generic wrapper for the `perl` command-line interpreter. + The `perl-math-bezier` package is a library and does not provide a direct executable. + To use it, you must provide a Perl script or a one-liner that utilizes the library's modules (e.g., via the -M flag or 'use Math::Bezier;' in the script). + + Args: + programfile: Path to the Perl program file to execute. + program: A one-liner string of a Perl program to execute (uses -e or -E). + arguments: A list of arguments to pass to the program file. + include_dirs: A list of directories to add to Perl's @INC search path (uses -I). + modules: A list of Perl modules to load before executing the program (uses -M). + Example: ["Math::Bezier"] + check_syntax_only: If True, checks the syntax of the script without executing it (uses -c). + enable_warnings: If True, enables many useful warnings (uses -w). + disable_warnings: If True, disables all warnings (uses -X). This overrides other warning flags. + enable_all_warnings: If True, enables all warnings (uses -W). This is overridden by disable_warnings. + enable_taint_checks: If True, enables tainting checks for security (uses -T). + enable_optional_features_for_program: If True and `program` is specified, enables all optional features (uses -E instead of -e). + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # --- Input Validation --- + if not programfile and not program: + raise ValueError("Either 'programfile' or 'program' must be provided.") + if programfile and program: + raise ValueError("'programfile' and 'program' are mutually exclusive.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The program file '{programfile}' does not exist.") + + if enable_optional_features_for_program and not program: + raise ValueError("'enable_optional_features_for_program' can only be True when 'program' is specified.") + + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise FileNotFoundError(f"The include directory '{directory}' does not exist.") + + # --- Command Construction --- + cmd = ["perl"] + + # Handle warning flags (priority: -X > -W > -w) + if disable_warnings: + cmd.append("-X") + elif enable_all_warnings: + cmd.append("-W") + elif enable_warnings: + cmd.append("-w") + + if check_syntax_only: + cmd.append("-c") + + if enable_taint_checks: + cmd.append("-T") + + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + + if modules: + for module in modules: + cmd.extend(["-M", module]) + + # Handle program source + if program: + if enable_optional_features_for_program: + cmd.extend(["-E", program]) + else: + cmd.extend(["-e", program]) + elif programfile: + cmd.append(str(programfile)) + + # Add script arguments + if arguments: + cmd.extend(arguments) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # This tool does not explicitly create output files + } + except FileNotFoundError: + raise RuntimeError("Perl executable not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with return code {e.returncode}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/perl-math-bezier_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/perl-math-bezier_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..193c1a624d37d9d26085449470c141e8381e94bc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/perl-math-bezier_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/perl-math-bezier_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_math_bezier' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bcbe4db6c3bb16a4727957bd9bf6c56430ffdb2f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-math-bezier: + build: . + image: mcp-perl-math-bezier:latest + container_name: mcp-perl-math-bezier + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-math-bezier + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7fb857c5b0096c00dc149299eb0d2fc44ae908d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-math-bezier + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-bezier/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ffb5eaac759ff0959075bb715683824bbc7e7dde --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-metabolomics-fragment-annotation via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-metabolomics-fragment-annotation -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY perl-metabolomics-fragment-annotation_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-metabolomics-fragment-annotation_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-metabolomics-fragment-annotation_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/app/__pycache__/perl-metabolomics-fragment-annotation_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/app/__pycache__/perl-metabolomics-fragment-annotation_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d147bdf09629e0d098549d446e0c81dc8691a215 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/app/__pycache__/perl-metabolomics-fragment-annotation_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/app/perl-metabolomics-fragment-annotation_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/app/perl-metabolomics-fragment-annotation_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e55949336b837f6c8f4f9c80f3ee54f8378589ec --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/app/perl-metabolomics-fragment-annotation_server.py @@ -0,0 +1,148 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# The mcp.tool decorator is not defined here, as per the problem description. +# It is assumed to be provided by the MCP framework. +# +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_metabolomics_fragment_annotation' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +# def placeholder(): +# pass + + +@mcp.tool() +def fragment_annotation( + in_file: Path, + out_file: Path, + db_file: Optional[Path] = None, + mode: str = "positive", + precursor_mz: Optional[float] = None, + precursor_adduct: Optional[str] = None, + fragment_tol: float = 0.01, + fragment_tol_unit: str = "Da", + min_intensity: float = 1.0, + max_depth: int = 2, + verbose: bool = False, +) -> dict: + """ + Annotates MS/MS fragment ions from metabolomics data using fragment-annotation.pl. + + This tool takes a peak list file (e.g., MGF, MSP) and annotates the fragments + against a compound database. + + Args: + in_file: Input file containing peak list data (e.g., MGF, MSP). + out_file: Output file for annotated results (e.g., CSV, TSV). + db_file: Database file of known compounds (e.g., SDF, MOL). Highly recommended for annotation. + mode: Ionization mode. Must be 'positive' or 'negative'. + precursor_mz: Precursor m/z value. If not provided, it will be read from the input file. + precursor_adduct: Precursor adduct type (e.g., '[M+H]+', '[M-H]-'). + fragment_tol: Fragment tolerance value. Must be a positive number. + fragment_tol_unit: Fragment tolerance unit. Must be 'Da' or 'ppm'. + min_intensity: Minimum relative intensity for fragments to be considered (0-100). + max_depth: Maximum fragmentation depth to consider. Must be a positive integer. + verbose: Enable verbose logging. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not in_file.is_file(): + raise FileNotFoundError(f"Input file not found: {in_file}") + + if db_file and not db_file.is_file(): + raise FileNotFoundError(f"Database file not found: {db_file}") + + if out_file.parent and not out_file.parent.exists(): + out_file.parent.mkdir(parents=True, exist_ok=True) + + if mode not in ["positive", "negative"]: + raise ValueError(f"Invalid mode '{mode}'. Must be 'positive' or 'negative'.") + + if fragment_tol <= 0: + raise ValueError(f"Fragment tolerance must be positive, but got {fragment_tol}.") + + if fragment_tol_unit not in ["Da", "ppm"]: + raise ValueError(f"Invalid fragment tolerance unit '{fragment_tol_unit}'. Must be 'Da' or 'ppm'.") + + if not (0.0 <= min_intensity <= 100.0): + raise ValueError(f"Minimum intensity must be between 0 and 100, but got {min_intensity}.") + + if max_depth <= 0: + raise ValueError(f"Maximum depth must be a positive integer, but got {max_depth}.") + + # 2. Command Construction + # Assuming the tool is available in the system's PATH as 'fragment-annotation.pl' + cmd = [ + "fragment-annotation.pl", + "--in", str(in_file), + "--out", str(out_file), + "--mode", mode, + "--fragment_tol", str(fragment_tol), + "--fragment_tol_unit", fragment_tol_unit, + "--min_intensity", str(min_intensity), + "--max_depth", str(max_depth), + ] + + if db_file: + cmd.extend(["--db", str(db_file)]) + if precursor_mz is not None: + cmd.extend(["--precursor_mz", str(precursor_mz)]) + if precursor_adduct: + cmd.extend(["--precursor_adduct", precursor_adduct]) + if verbose: + cmd.append("--verbose") + + # 3. Subprocess Execution and Error Handling + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # 4. Structured Result Return (Success) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_file)] + } + except FileNotFoundError: + # This error occurs if 'fragment-annotation.pl' is not in the PATH + raise RuntimeError("The command 'fragment-annotation.pl' was not found. Please ensure the tool is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # This error occurs if the tool returns a non-zero exit code + # The MCP framework will typically handle this exception, but returning a + # structured error provides more context to the user. + error_message = ( + f"Tool execution failed with return code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + # Re-raising is often better for MCP to handle, but if we must return: + # For this problem, we will re-raise to let the MCP framework handle it, + # as this is a more robust pattern. If a dictionary must be returned, + # the following code could be used instead of raising the exception. + # + # return { + # "command_executed": command_executed, + # "stdout": e.stdout, + # "stderr": e.stderr, + # "error": f"Tool execution failed with return code {e.returncode}.", + # "output_files": [] + # } + raise RuntimeError(error_message) from e + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/app/perl-metabolomics-fragment-annotation_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/app/perl-metabolomics-fragment-annotation_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9cfce633eec90492e13797d830b08561422f2bad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/app/perl-metabolomics-fragment-annotation_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_perl-metabolomics-fragment-annotation/app/perl-metabolomics-fragment-annotation_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_metabolomics_fragment_annotation' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b523ed6b72467dcd5874c2cefd94dcd3ef457613 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-metabolomics-fragment-annotation: + build: . + image: mcp-perl-metabolomics-fragment-annotation:latest + container_name: mcp-perl-metabolomics-fragment-annotation + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-metabolomics-fragment-annotation + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ded292d05dc8663928c1e34800953b626c95932f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-metabolomics-fragment-annotation + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-metabolomics-fragment-annotation/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7139289a40a4222e610016961dec2d808edbb423 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-moose via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-moose -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-moose_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-moose_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-moose_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/__pycache__/perl-moose_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/__pycache__/perl-moose_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df2a12c1a766b7590a6af8a3c6c49d8c002e7329 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/__pycache__/perl-moose_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/perl-moose_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/perl-moose_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b3027943ed5f8a9dc3041e1166530b681f742c5d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/perl-moose_server.py @@ -0,0 +1,210 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_moose' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_interpreter( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_dirs: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + enable_switch_parsing: bool = False, + search_path_for_program: bool = False, + taint_warnings: bool = False, + taint_checks: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + extract_from_text: Optional[str] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a script using the Perl interpreter. + + This tool is a wrapper for the `perl` command-line executable. It can run any + Perl script, including those that use modules like Moose. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to pass to the program file. + execute_program: One or more lines of a program passed as a string (-e). + execute_program_extended: Like -e, but enables all optional features (-E). + record_separator: Specify record separator, e.g., '777' for octal (-0). + autosplit: Enable autosplit mode with -n or -p (-a). + unicode_features: Enable listed Unicode features, e.g., 'A' or '8' (-C). + check_syntax_only: Check syntax only; does not execute the program (-c). + debugger: Run program under the specified debugger, e.g., 'Deparse' (-d). + debugging_flags: Set debugging flags, e.g., 'p' or '14' (-D). + no_sitecustomize: Don't run $sitelib/sitecustomize.pl at startup (-f). + split_pattern: Specify the split() pattern for the -a switch (-F). + in_place_edit: Edit files in place. Provide an extension for backups, e.g., '.bak' (-i). + include_dirs: List of directories to add to @INC search path (-I). + line_ending_processing: Enable line ending processing; can specify octal terminator (-l). + modules: List of modules to use/no, e.g., ["-Mstrict", "-mwarnings", "-M-CGI"]. + loop_around_program: Assume a "while (<>) { ... }" loop around the program (-n). + loop_and_print: Like -n, but also prints the line, similar to sed (-p). + enable_switch_parsing: Enable rudimentary parsing for switches after programfile (-s). + search_path_for_program: Look for programfile using the PATH environment variable (-S). + taint_warnings: Enable tainting warnings (-t). + taint_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing the program (-u). + allow_unsafe: Allow unsafe operations (-U). + print_version: Print Perl version, patchlevel, and license (-v). + print_config: Print configuration summary or a single variable, e.g., 'archname' (-V). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + extract_from_text: Ignore text before #!perl line; optionally cd to a directory (-x). + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # --- Input Validation --- + source_provided = any([ + programfile, + execute_program, + execute_program_extended, + print_version, + print_config is not None + ]) + if not source_provided: + raise ValueError( + "No program source provided. You must specify 'programfile', " + "'execute_program', 'execute_program_extended', 'print_version', " + "or 'print_config'." + ) + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if loop_around_program and loop_and_print: + raise ValueError("The flags '-n' (loop_around_program) and '-p' (loop_and_print) are mutually exclusive.") + + warning_flags = [enable_warnings, enable_all_warnings, disable_all_warnings] + if sum(warning_flags) > 1: + raise ValueError("Warning flags '-w' (enable_warnings), '-W' (enable_all_warnings), and '-X' (disable_all_warnings) are mutually exclusive.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: + cmd.append(f"-i{in_place_edit}") + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise NotADirectoryError(f"Include directory does not exist or is not a directory: {directory}") + cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if modules: + for mod in modules: + if not (mod.startswith("-M") or mod.startswith("-m")): + raise ValueError(f"Invalid module string '{mod}'. Must start with '-M' or '-m'.") + cmd.extend(modules) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if enable_switch_parsing: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if taint_warnings: + cmd.append("-t") + if taint_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V:{print_config}" if print_config else "-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if extract_from_text is not None: + cmd.append(f"-x{extract_from_text}") + if disable_all_warnings: + cmd.append("-X") + + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_extended: + for prog_line in execute_program_extended: + cmd.extend(["-E", prog_line]) + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("`perl` command not found. Please ensure Perl is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/perl-moose_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/perl-moose_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e6c7f21cce09f35e25c9fbb51b2769129d93467e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/perl-moose_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/perl-moose_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_moose' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ea5ead0b736ccc6d790844e6bef0d388547d315a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-moose: + build: . + image: mcp-perl-moose:latest + container_name: mcp-perl-moose + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-moose + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1c33b8a778306043ae6cc792b3b0c93f53a5fa74 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-moose + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-moose/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-mozilla-ca/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-mozilla-ca/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-mozilla-ca/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ea1c5d7d00b5ff552e5f01fe3ef90c20341ff063 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-differences via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-differences -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-differences_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-differences_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-differences_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/__pycache__/perl-test-differences_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/__pycache__/perl-test-differences_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78ab64657d944e5d88cd4eddba0e5b6838a93e0a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/__pycache__/perl-test-differences_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/perl-test-differences_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/perl-test-differences_server.py new file mode 100644 index 0000000000000000000000000000000000000000..543bc108831b8cf31b61ba71b7c9bb998d3115f8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/perl-test-differences_server.py @@ -0,0 +1,220 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any +import json + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_test_differences' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_test_differences_text( + got: str, + expected: str, + name: str = "text_comparison", + style: str = "table", + context: int = 3, +) -> Dict[str, Any]: + """ + Compare two strings using Perl's Test::Differences and show the differences. + Useful for identifying exact discrepancies between multi-line strings or command outputs. + + Args: + got: The actual string received. + expected: The expected string. + name: A label for the comparison test. + style: The diff style to use ('table', 'unified', 'context', or 'oldstyle'). + context: Number of lines of context to show around differences (for 'unified' or 'context' styles). + """ + # Validate style + valid_styles = ["table", "unified", "context", "oldstyle"] + if style not in valid_styles: + style = "table" + + # Construct Perl one-liner + # We use Test::More to provide the test harness and Test::Differences for the diff logic + perl_script = ( + "use Test::More; " + "use Test::Differences; " + "plan tests => 1; " + f"eq_or_diff($ARGV[0], $ARGV[1], $ARGV[2], {{ style => '{style}', context => {context} }});" + ) + + cmd = ["perl", "-MTest::More", "-MTest::Differences", "-e", perl_script, "--", got, expected, name] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "test_passed": result.returncode == 0, + "output_files": [] + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": str(e), + "test_passed": False, + "output_files": [] + } + +@mcp.tool() +def perl_test_differences_files( + file_path_1: str, + file_path_2: str, + name: str = "file_comparison", + style: str = "table", + context: int = 3, +) -> Dict[str, Any]: + """ + Compare the contents of two files using Perl's Test::Differences. + Commonly used in bioinformatics to verify that a tool's output matches a reference file. + + Args: + file_path_1: Path to the first file (actual). + file_path_2: Path to the second file (expected). + name: A label for the comparison test. + style: The diff style to use ('table', 'unified', 'context', or 'oldstyle'). + context: Number of lines of context to show around differences. + """ + path1 = Path(file_path_1) + path2 = Path(file_path_2) + + if not path1.exists(): + return {"error": f"File not found: {file_path_1}"} + if not path2.exists(): + return {"error": f"File not found: {file_path_2}"} + + # Read file contents + try: + content1 = path1.read_text() + content2 = path2.read_text() + except Exception as e: + return {"error": f"Failed to read files: {str(e)}"} + + # Validate style + valid_styles = ["table", "unified", "context", "oldstyle"] + if style not in valid_styles: + style = "table" + + perl_script = ( + "use Test::More; " + "use Test::Differences; " + "plan tests => 1; " + f"eq_or_diff($ARGV[0], $ARGV[1], $ARGV[2], {{ style => '{style}', context => {context} }});" + ) + + cmd = ["perl", "-MTest::More", "-MTest::Differences", "-e", perl_script, "--", content1, content2, name] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "test_passed": result.returncode == 0, + "output_files": [] + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": str(e), + "test_passed": False, + "output_files": [] + } + +@mcp.tool() +def perl_test_differences_data( + got_json: str, + expected_json: str, + name: str = "data_structure_comparison", + style: str = "table", +) -> Dict[str, Any]: + """ + Compare two complex data structures (provided as JSON strings) using Perl's Test::Differences. + This tool decodes the JSON and compares the underlying structures (hashes, arrays). + + Args: + got_json: The actual data structure in JSON format. + expected_json: The expected data structure in JSON format. + name: A label for the comparison test. + style: The diff style to use ('table', 'unified', 'context', or 'oldstyle'). + """ + # Validate JSON inputs + try: + json.loads(got_json) + json.loads(expected_json) + except json.JSONDecodeError as e: + return {"error": f"Invalid JSON input: {str(e)}"} + + # Validate style + valid_styles = ["table", "unified", "context", "oldstyle"] + if style not in valid_styles: + style = "table" + + # Perl script that uses JSON::PP (core module) to decode strings into Perl structures + # then compares them using eq_or_diff + perl_script = ( + "use Test::More; " + "use Test::Differences; " + "use JSON::PP; " + "my $json = JSON::PP->new; " + "my $data_got = $json->decode($ARGV[0]); " + "my $data_exp = $json->decode($ARGV[1]); " + "plan tests => 1; " + f"eq_or_diff($data_got, $data_exp, $ARGV[2], {{ style => '{style}' }});" + ) + + cmd = ["perl", "-MTest::More", "-MTest::Differences", "-MJSON::PP", "-e", perl_script, "--", got_json, expected_json, name] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "test_passed": result.returncode == 0, + "output_files": [] + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": str(e), + "test_passed": False, + "output_files": [] + } + +@mcp.tool() +def perl_test_differences_version() -> Dict[str, Any]: + """ + Check the installed version of the Test::Differences Perl module. + """ + perl_script = "use Test::Differences; print $Test::Differences::VERSION;" + cmd = ["perl", "-MTest::Differences", "-e", perl_script] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "version": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Test::Differences module not found or perl execution failed." + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/perl-test-differences_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/perl-test-differences_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4928a9a21f1e1ac7aba64a8a5dd3ddc87bc6d9d8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/perl-test-differences_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/perl-test-differences_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_test_differences' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a8f7f65557547303244bf741ebf9da6d0df06435 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-differences + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-differences/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-text-diff/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-text-diff/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-text-diff/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d04cdb80a58c5fbdf1dd66eb56b0344c58c6645c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-time-hires via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-time-hires -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-time-hires_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-time-hires_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-time-hires_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/__pycache__/perl-time-hires_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/__pycache__/perl-time-hires_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db96699e7f1635f91989232846f5c73acd609fc5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/__pycache__/perl-time-hires_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/perl-time-hires_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/perl-time-hires_server.py new file mode 100644 index 0000000000000000000000000000000000000000..aa71a68f695ec92c9ebb16cad90afa9099b60339 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/perl-time-hires_server.py @@ -0,0 +1,401 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_time_hires' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def usleep(microseconds: int): + """ + Sleeps for the number of microseconds (millionths of a second) specified. + Returns the number of microseconds actually slept. + """ + if microseconds < 0: + return {"error": "microseconds must be a non-negative integer"} + + cmd = ["perl", "-MTime::HiRes=usleep", "-e", "print usleep($ARGV[0])", str(microseconds)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "microseconds_slept": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def nanosleep(nanoseconds: int): + """ + Sleeps for the number of nanoseconds (1e9ths of a second) specified. + Returns the number of nanoseconds actually slept (accurate only to microseconds). + """ + if nanoseconds < 0: + return {"error": "nanoseconds must be a non-negative integer"} + + cmd = ["perl", "-MTime::HiRes=nanosleep", "-e", "print nanosleep($ARGV[0])", str(nanoseconds)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "nanoseconds_slept": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def ualarm(microseconds: int, interval_microseconds: int = 0): + """ + Issues a ualarm call. The interval_microseconds is optional (defaults to 0). + Returns the remaining time in the alarm in microseconds. + """ + if microseconds < 0 or interval_microseconds < 0: + return {"error": "Parameters must be non-negative integers"} + + cmd = ["perl", "-MTime::HiRes=ualarm", "-e", "print ualarm($ARGV[0], $ARGV[1])", str(microseconds), str(interval_microseconds)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "remaining_microseconds": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def gettimeofday(): + """ + Returns the seconds and microseconds since the epoch as a comma-separated string. + """ + cmd = ["perl", "-MTime::HiRes=gettimeofday", "-e", "print join(',', gettimeofday())"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "time_data": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def tv_interval(sec1: int, usec1: int, sec2: Optional[int] = None, usec2: Optional[int] = None): + """ + Returns the floating seconds between two times (sec1, usec1) and (sec2, usec2). + If the second time is omitted, the current time is used. + """ + if sec2 is not None and usec2 is not None: + perl_code = f"print tv_interval([{sec1}, {usec1}], [{sec2}, {usec2}])" + else: + perl_code = f"print tv_interval([{sec1}, {usec1}])" + + cmd = ["perl", "-MTime::HiRes=tv_interval", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "interval_seconds": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_time(): + """ + Returns floating seconds since the epoch with microsecond resolution. + """ + cmd = ["perl", "-MTime::HiRes=time", "-e", "printf('%.6f', time())"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "current_time": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_sleep(seconds: float): + """ + Sleeps for the specified amount of floating point seconds. + Returns the number of seconds actually slept. + """ + if seconds < 0: + return {"error": "seconds must be a non-negative float"} + + cmd = ["perl", "-MTime::HiRes=sleep", "-e", "print sleep($ARGV[0])", str(seconds)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "seconds_slept": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_alarm(seconds: float, interval: float = 0.0): + """ + Sets an alarm for the specified floating point seconds. + Returns the remaining time in the alarm in seconds. + """ + if seconds < 0 or interval < 0: + return {"error": "Parameters must be non-negative floats"} + + cmd = ["perl", "-MTime::HiRes=alarm", "-e", "print alarm($ARGV[0], $ARGV[1])", str(seconds), str(interval)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "remaining_seconds": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_stat(file_path: str): + """ + Performs a high-resolution stat on a file. + Returns a comma-separated list of stat fields (dev, ino, mode, nlink, uid, gid, rdev, size, atime, mtime, ctime, blksize, blocks). + """ + path = Path(file_path) + if not path.exists(): + return {"error": f"File not found: {file_path}"} + + cmd = ["perl", "-MTime::HiRes=stat", "-e", "print join(',', stat($ARGV[0]))", str(file_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "stat_fields": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_lstat(file_path: str): + """ + Performs a high-resolution lstat on a symbolic link or file. + Returns a comma-separated list of stat fields. + """ + path = Path(file_path) + if not path.exists() and not path.is_symlink(): + return {"error": f"File or link not found: {file_path}"} + + cmd = ["perl", "-MTime::HiRes=lstat", "-e", "print join(',', lstat($ARGV[0]))", str(file_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "lstat_fields": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_utime(atime: float, mtime: float, files: List[str]): + """ + Sets high-resolution access and modification times for a list of files. + Returns the number of files successfully updated. + """ + for f in files: + if not Path(f).exists(): + return {"error": f"File not found: {f}"} + + cmd = ["perl", "-MTime::HiRes=utime", "-e", "$a=shift; $m=shift; print utime($a, $m, @ARGV)", str(atime), str(mtime)] + files + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "files_updated": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def clock_gettime(clock_id: str = "CLOCK_REALTIME"): + """ + Returns the current time of the specified clock (e.g., CLOCK_REALTIME, CLOCK_MONOTONIC). + """ + cmd = ["perl", "-MTime::HiRes=:all", "-e", "print clock_gettime(eval($ARGV[0]))", clock_id] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "clock_time": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def clock_getres(clock_id: str = "CLOCK_REALTIME"): + """ + Returns the resolution of the specified clock. + """ + cmd = ["perl", "-MTime::HiRes=:all", "-e", "print clock_getres(eval($ARGV[0]))", clock_id] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "clock_resolution": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def clock_nanosleep(nanoseconds: int, clock_id: str = "CLOCK_REALTIME", flags: int = 0): + """ + Sleeps for the specified nanoseconds using the specified clock. + Flags can be TIMER_ABSTIME (1) or 0. + """ + if nanoseconds < 0: + return {"error": "nanoseconds must be non-negative"} + + cmd = ["perl", "-MTime::HiRes=:all", "-e", "print clock_nanosleep(eval($ARGV[1]), $ARGV[0], $ARGV[2])", str(nanoseconds), clock_id, str(flags)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "nanoseconds_slept": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_clock(): + """ + Returns the process time (user + system) in seconds with high resolution. + """ + cmd = ["perl", "-MTime::HiRes=clock", "-e", "print clock()"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "process_time": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/perl-time-hires_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/perl-time-hires_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a99af756450da9232d8bd8863d791389d15132b4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/perl-time-hires_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/perl-time-hires_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_time_hires' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..99e2b434733b7c74e3d8984e4fc7f075151f30d3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-time-hires: + build: . + image: mcp-perl-time-hires:latest + container_name: mcp-perl-time-hires + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-time-hires + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..32c6d05fb886e826b264e96e0ac8aa3a9751a744 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-time-hires + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-time-hires/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-timedate/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-timedate/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-timedate/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0a7aca7ccbcc120265bc3debc46dd9557889966b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-libxml via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-libxml -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-libxml_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-libxml_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-libxml_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/__pycache__/perl-xml-libxml_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/__pycache__/perl-xml-libxml_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cddbaa3e32989cb76f3e57c810c5beb655a80c7b Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/__pycache__/perl-xml-libxml_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/perl-xml-libxml_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/perl-xml-libxml_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9c44e426b5383ad8da5800b4d6d0a34ad81f7a77 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/perl-xml-libxml_server.py @@ -0,0 +1,276 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_xml_libxml' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_xml_libxml_validate( + xml_path: str, + schema_path: Optional[str] = None, + schema_type: str = "xsd", +): + """ + Validates an XML file using perl-xml-libxml. Can check for well-formedness or + validate against an XSD or DTD. + + Args: + xml_path: Path to the XML file to validate. + schema_path: Optional path to a schema file (XSD or DTD). + schema_type: Type of schema provided ('xsd' or 'dtd'). Defaults to 'xsd'. + """ + xml_file = Path(xml_path) + if not xml_file.exists(): + return {"error": f"XML file not found: {xml_path}"} + + # Construct Perl one-liner for validation + perl_script = [ + "use XML::LibXML;", + "my $xml = shift;", + "my $schema_file = shift;", + "my $type = shift;", + "my $parser = XML::LibXML->new();", + "eval {", + " if ($schema_file) {", + " if ($type eq 'xsd') {", + " my $schema = XML::LibXML::Schema->new(location => $schema_file);", + " my $doc = $parser->parse_file($xml);", + " $schema->validate($doc);", + " } elsif ($type eq 'dtd') {", + " $parser->validation(1);", + " $parser->parse_file($xml);", + " }", + " } else {", + " $parser->parse_file($xml);", + " }", + "};", + "if ($@) { die \"Validation failed: $@\"; } else { print \"Validation successful\\n\"; }", + ] + + cmd = ["perl", "-MXML::LibXML", "-e", "".join(perl_script), str(xml_file)] + if schema_path: + s_path = Path(schema_path) + if not s_path.exists(): + return {"error": f"Schema file not found: {schema_path}"} + cmd.append(str(s_path)) + cmd.append(schema_type) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Validation failed" + } + +@mcp.tool() +def perl_xml_libxml_xpath( + xml_path: str, + expression: str, + output_format: str = "string", +): + """ + Extracts data from an XML file using an XPath expression via XML::LibXML. + + Args: + xml_path: Path to the XML file. + expression: XPath expression to evaluate. + output_format: How to return results ('string' for text content, 'xml' for raw XML nodes). + """ + xml_file = Path(xml_path) + if not xml_file.exists(): + return {"error": f"XML file not found: {xml_path}"} + + # Construct Perl one-liner for XPath + perl_script = [ + "use XML::LibXML;", + "my $xml = shift;", + "my $xpath = shift;", + "my $fmt = shift;", + "my $dom = XML::LibXML->load_xml(location => $xml);", + "for my $node ($dom->findnodes($xpath)) {", + " if ($fmt eq 'xml') { print $node->toString(), \"\\n\"; }", + " else { print $node->textContent(), \"\\n\"; }", + "}" + ] + + cmd = ["perl", "-MXML::LibXML", "-e", "".join(perl_script), str(xml_file), expression, output_format] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "results": result.stdout.splitlines() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "XPath query failed" + } + +@mcp.tool() +def perl_xml_libxml_format( + xml_path: str, + indent: int = 1, + no_blanks: bool = True, +): + """ + Pretty-prints/formats an XML file using XML::LibXML. + + Args: + xml_path: Path to the XML file to format. + indent: Indentation level (0, 1, or 2). Defaults to 1. + no_blanks: If True, removes existing whitespace before re-formatting. Defaults to True. + """ + xml_file = Path(xml_path) + if not xml_file.exists(): + return {"error": f"XML file not found: {xml_path}"} + + if indent < 0 or indent > 2: + return {"error": "Indent must be 0, 1, or 2"} + + blanks_flag = 1 if no_blanks else 0 + + perl_script = [ + "use XML::LibXML;", + "my $xml = shift;", + "my $ind = shift;", + "my $nb = shift;", + "my $dom = XML::LibXML->load_xml(location => $xml, no_blanks => $nb);", + "print $dom->toString($ind);" + ] + + cmd = ["perl", "-MXML::LibXML", "-e", "".join(perl_script), str(xml_file), str(indent), str(blanks_flag)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "formatted_xml": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Formatting failed" + } + +@mcp.tool() +def perl_xml_libxml_execute( + script_path: Optional[str] = None, + one_liner: Optional[str] = None, + input_files: Optional[List[str]] = None, + warnings: bool = True, + taint_check: bool = False, + include_dirs: Optional[List[str]] = None, + autosplit: bool = False, + loop_n: bool = False, + loop_p: bool = False, +): + """ + General purpose Perl execution tool with XML::LibXML pre-loaded. + Allows running custom scripts or one-liners that utilize the library. + + Args: + script_path: Path to a .pl script to execute. + one_liner: A string containing Perl code to execute (equivalent to -e). + input_files: List of files to pass as arguments to the script. + warnings: Enable many useful warnings (-w). Defaults to True. + taint_check: Enable tainting checks (-T). Defaults to False. + include_dirs: List of directories to add to @INC (-I). + autosplit: Enable autosplit mode (-a) with -n or -p. + loop_n: Assume "while (<>) { ... }" loop around program (-n). + loop_p: Assume loop like -n but print line also (-p). + """ + cmd = ["perl", "-MXML::LibXML"] + + if warnings: + cmd.append("-w") + if taint_check: + cmd.append("-T") + if autosplit: + cmd.append("-a") + if loop_n: + cmd.append("-n") + if loop_p: + cmd.append("-p") + + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", d]) + + if one_liner: + cmd.extend(["-e", one_liner]) + elif script_path: + s_path = Path(script_path) + if not s_path.exists(): + return {"error": f"Script not found: {script_path}"} + cmd.append(str(s_path)) + else: + return {"error": "Either script_path or one_liner must be provided."} + + if input_files: + for f in input_files: + f_path = Path(f) + if f_path.exists(): + cmd.append(str(f_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "exit_code": e.returncode, + "error": "Perl execution failed" + } + +@mcp.tool() +def perl_xml_libxml_info(): + """ + Returns version information for the perl-xml-libxml installation and the underlying libxml2 library. + """ + perl_script = "use XML::LibXML; printf('XML::LibXML Version: %s\\nLibXML2 Version: %s\\n', $XML::LibXML::VERSION, XML::LibXML::LIBXML_DOTTED_VERSION);" + cmd = ["perl", "-e", perl_script] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve version info" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/perl-xml-libxml_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/perl-xml-libxml_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e906dd69089785738240768209784bd5bad60d44 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/perl-xml-libxml_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/perl-xml-libxml_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_xml_libxml' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1414450d5cab98c47adcf029be3d8009ab5161cb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-libxml: + build: . + image: mcp-perl-xml-libxml:latest + container_name: mcp-perl-xml-libxml + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-libxml + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f9a178635543090a48cafd5b83741825cb5031f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-libxml + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-libxml/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2d10f06824700eb4504b231de66270b64d60fcad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-sax-base via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-sax-base -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-sax-base_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-sax-base_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-sax-base_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/__pycache__/perl-xml-sax-base_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/__pycache__/perl-xml-sax-base_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22d7273fd5c1d7192d3c65af67e94fa36bc8f518 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/__pycache__/perl-xml-sax-base_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/perl-xml-sax-base_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/perl-xml-sax-base_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b79bf77e4b4bc69096b03651fdb114091af894e7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/perl-xml-sax-base_server.py @@ -0,0 +1,236 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_xml_sax_base' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_xml_sax_base_run( + program_file: Optional[str] = None, + one_liner: Optional[str] = None, + arguments: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + syntax_check: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + one_liner_all_features: Optional[str] = None, + no_site_customize: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + include_dirs: Optional[List[str]] = None, + line_ending_processing: Optional[str] = None, + modules: Optional[List[str]] = None, + loop_n: bool = False, + loop_p: bool = False, + switch_parsing: bool = False, + path_search: bool = False, + taint_warnings: bool = False, + taint_checks: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + print_version: bool = False, + config_summary: Optional[str] = None, + warnings: bool = False, + all_warnings: bool = False, + extract_directory: Optional[str] = None, + disable_all_warnings: bool = False, +): + """ + Executes the Perl interpreter with the XML::SAX::Base environment. + This tool provides access to the Perl CLI switches as defined in the perl-xml-sax-base package environment. + + Args: + program_file: Path to the Perl script to execute. + one_liner: One line of program (several -e's allowed, but here as a single string). + arguments: Arguments passed to the programfile. + record_separator: Specify record separator (-0). + autosplit: Autosplit mode with -n or -p (-a). + unicode_features: Enables the listed Unicode features (-C). + syntax_check: Check syntax only (-c). + debugger: Run program under debugger (-d). + debug_flags: Set debugging flags (-D). + one_liner_all_features: Like -e, but enables all optional features (-E). + no_site_customize: Don't do $sitelib/sitecustomize.pl at startup (-f). + split_pattern: split() pattern for -a switch (-F). + inplace_extension: Edit <> files in place, makes backup if extension supplied (-i). + include_dirs: Specify @INC/#include directory (-I). + line_ending_processing: Enable line ending processing, specifies line terminator (-l). + modules: Execute "use module..." before executing program (-M). + loop_n: Assume "while (<>) { ... }" loop around program (-n). + loop_p: Assume loop like -n but print line also (-p). + switch_parsing: Enable rudimentary parsing for switches after programfile (-s). + path_search: Look for programfile using PATH environment variable (-S). + taint_warnings: Enable tainting warnings (-t). + taint_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing program (-u). + unsafe_operations: Allow unsafe operations (-U). + print_version: Print version, patchlevel and license (-v). + config_summary: Print configuration summary or a single Config.pm variable (-V). + warnings: Enable many useful warnings (-w). + all_warnings: Enable all warnings (-W). + extract_directory: Ignore text before #!perl line, optionally cd to directory (-x). + disable_all_warnings: Disable all warnings (-X). + """ + cmd = ["perl"] + + # Handle switches + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if syntax_check: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d{debugger}") + if debug_flags is not None: + cmd.append(f"-D{debug_flags}") + if one_liner is not None: + cmd.extend(["-e", one_liner]) + if one_liner_all_features is not None: + cmd.extend(["-E", one_liner_all_features]) + if no_site_customize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if modules: + for m in modules: + cmd.append(f"-M{m}") + if loop_n: + cmd.append("-n") + if loop_p: + cmd.append("-p") + if switch_parsing: + cmd.append("-s") + if path_search: + cmd.append("-S") + if taint_warnings: + cmd.append("-t") + if taint_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if config_summary is not None: + cmd.append(f"-V:{config_summary}" if config_summary else "-V") + if warnings: + cmd.append("-w") + if all_warnings: + cmd.append("-W") + if extract_directory is not None: + cmd.append(f"-x{extract_directory}") + if disable_all_warnings: + cmd.append("-X") + + # Handle program file and arguments + if program_file: + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"Program file not found: {program_file}"} + cmd.append(str(prog_path)) + + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_xml_sax_base_check_version(): + """ + Checks the installed version of the XML::SAX::Base Perl module. + This is useful to verify that the library is correctly installed in the environment. + """ + cmd = ["perl", "-MXML::SAX::Base", "-e", "print $XML::SAX::Base::VERSION"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "module": "XML::SAX::Base", + "version": result.stdout.strip(), + "command_executed": " ".join(cmd), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "error": "XML::SAX::Base module not found or failed to load.", + "stderr": e.stderr, + "command_executed": " ".join(cmd), + "status": "error" + } + +@mcp.tool() +def perl_xml_sax_base_validate_xml_structure( + xml_file: str, +): + """ + Uses XML::SAX::Base to perform a basic parse of an XML file to check for well-formedness. + Note: XML::SAX::Base is a base class; this tool uses it to verify the SAX parsing chain. + + Args: + xml_file: Path to the XML file to validate. + """ + xml_path = Path(xml_file) + if not xml_path.exists(): + return {"error": f"XML file not found: {xml_file}"} + + # Perl one-liner to attempt parsing using the SAX Base logic + # It uses XML::SAX::ParserFactory to find an available parser that inherits from Base + perl_code = ( + "use XML::SAX::ParserFactory; " + "my $handler = XML::SAX::Base->new(); " + "my $parser = XML::SAX::ParserFactory->parser(Handler => $handler); " + "eval { $parser->parse_uri($ARGV[0]) }; " + "if ($@) { die $@; }" + ) + + cmd = ["perl", "-e", perl_code, str(xml_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "message": f"XML file {xml_file} is well-formed according to SAX parser.", + "stdout": result.stdout, + "command_executed": " ".join(cmd), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "error": f"Validation failed for {xml_file}", + "stderr": e.stderr, + "command_executed": " ".join(cmd), + "status": "error" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/perl-xml-sax-base_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/perl-xml-sax-base_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..824de42c5ac29cfb1990c1706bd4902a19c3145c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/perl-xml-sax-base_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/perl-xml-sax-base_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_xml_sax_base' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1a9a1e4ddd94a241df31aeca32c89f9a39b8d36a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-sax-base: + build: . + image: mcp-perl-xml-sax-base:latest + container_name: mcp-perl-xml-sax-base + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-sax-base + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d358461587267c837158b1577f9423c6a24b72df --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-sax-base + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-base/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..af11c407f831c1d4f28c005e9b2da80c95315e90 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install phyml via conda (e.g., from bioconda) +RUN conda install -c bioconda phyml -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/phyml_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/phyml_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/phyml_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/__pycache__/phyml_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/__pycache__/phyml_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15915c68cd79ed70772600770af2e9c067109312 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/__pycache__/phyml_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/phyml_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/phyml_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2cdc8f7a47a6c3051f7a42945dd26f7ea7c8ef76 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/phyml_server.py @@ -0,0 +1,441 @@ +import subprocess +from pathlib import Path +from typing import Optional, Union, Literal, List + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_phyml' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def phyml( + input_file: Path, + data_type: Literal['nt', 'aa', 'generic'] = 'nt', + sequential: bool = False, + num_data_sets: Optional[int] = None, + use_pars_start_tree: bool = False, + bootstrap: int = -5, + tbe: bool = False, + model: Optional[str] = None, + aa_rate_file: Optional[Path] = None, + char_frequencies: Optional[Union[Literal['e', 'm', 'o'], str]] = None, + ts_tv_ratio: Optional[Union[float, Literal['e']]] = None, + prop_invar: Optional[Union[float, Literal['e']]] = None, + num_subst_categories: int = 4, + freerates: bool = False, + gamma_shape_parameter: Optional[Union[float, Literal['e']]] = None, + tree_search_move: Optional[Literal['NNI', 'SPR', 'BEST']] = None, + input_tree_file: Optional[Path] = None, + optimization_params: Optional[Literal['tlr', 'tl', 'lr', 'l', 'r', 'n']] = None, + rand_start: bool = False, + num_rand_starts: Optional[int] = None, + random_seed: Optional[int] = None, + print_site_lnl: bool = False, + print_trace: bool = False, + run_id: Optional[str] = None, + quiet: bool = False, + no_memory_check: bool = False, + leave_duplicates: bool = False, + alias_subpatt: bool = False, + boot_progress_display: int = 20, +) -> dict: + """ + Phylogenetic estimation using Maximum Likelihood with PhyML. + + PhyML estimates maximum likelihood phylogenies from alignments of nucleotide + or amino acid sequences. It supports a large number of substitution models + and various options for searching tree topologies. + + Args: + input_file: The name of the nucleotide or amino-acid sequence file in PHYLIP format. + data_type: Data type: 'nt' for nucleotide (default), 'aa' for amino-acid, or 'generic'. + sequential: Changes interleaved format (default) to sequential format. + num_data_sets: Number of data sets to analyze. Must be a positive integer. + use_pars_start_tree: Use a minimum parsimony starting tree. This option is taken into account when the '-u' option + is absent and when tree topology modifications are to be done. + bootstrap: Bootstrap replicates or likelihood ratio test type. + > 0: number of bootstrap replicates. + = 0: neither approximate likelihood ratio test nor bootstrap values are computed. + = -1: approximate likelihood ratio test returning aLRT statistics. + = -2: approximate likelihood ratio test returning Chi2-based parametric branch supports. + = -4: SH-like branch supports alone. + = -5: (default) approximate Bayes branch supports. + tbe: Computes TBE instead of FBP (standard) bootstrap support. Has no effect with bootstrap <= 0. + model: Substitution model name. + Nucleotide models: HKY85 (default) | JC69 | K80 | F81 | F84 | TN93 | GTR | custom. + Amino-acid models: LG (default) | WAG | JTT | MtREV | Dayhoff | DCMut | RtREV | CpREV | VT | AB | Blosum62 | MtMam | MtArt | HIVw | HIVb | custom. + For 'custom' nucleotide, a string of six digits identifies the model (e.g., '012345' for GTR). + aa_rate_file: Name of the file that provides the amino acid substitution rate matrix in PAML format. + Compulsory to use this option when analysing amino acid sequences with the `custom' model. + char_frequencies: Character frequencies. + 'e': determined by counting the number of amino-acids or nucleotides from the sequence alignment. + 'm': optimized by ML (nucleotide) or estimated from model (amino-acid). + 'o': optimized by ML. + 'fA,fC,fG,fT': comma-separated nucleotide frequencies (e.g., '0.25,0.25,0.25,0.25'). + Only valid for nucleotide-based models. No blank spaces between values. + ts_tv_ratio: Transition/transversion ratio. DNA sequences only. + Can be a fixed positive value (ex:4.0) or 'e' to get the maximum likelihood estimate. + prop_invar: Proportion of invariable sites. + Can be a fixed value in the [0,1] range or 'e' to get the maximum likelihood estimate. + num_subst_categories: Number of relative substitution rate categories. Default: 4. Must be a positive integer. + freerates: FreeRate model of substitution rate variation across sites. + gamma_shape_parameter: Distribution of the gamma distribution shape parameter. + Can be a fixed positive value or 'e' to get the maximum likelihood estimate. + tree_search_move: Tree topology search operation. 'NNI' (default, fast) or 'SPR' (slower) or 'BEST' (best of NNI and SPR). (Deprecated option). + input_tree_file: Starting tree filename. The tree must be in Newick format. + optimization_params: This option focuses on specific parameter optimisation. + 'tlr': tree topology (t), branch length (l) and rate parameters (r) are optimised. + 'tl': tree topology and branch length are optimised. + 'lr': branch length and rate parameters are optimised. + 'l': branch length are optimised. + 'r': rate parameters are optimised. + 'n': no parameter is optimised. + rand_start: Sets the initial tree to random. Only valid if SPR searches are to be performed. + num_rand_starts: Number of initial random trees to be used. Only valid if SPR searches are to be performed. Must be positive. + random_seed: Seed used to initiate the random number generator. Must be an integer. + print_site_lnl: Print the likelihood for each site in file *_phyml_lk.txt. + print_trace: Print each phylogeny explored during the tree search process in file *_phyml_trace.txt. + run_id: Append the string ID_string at the end of each PhyML output file. + quiet: No interactive question (for running in batch mode) and quiet output. + no_memory_check: No interactive question for memory usage (for running in batch mode). Normal output otherwise. + leave_duplicates: PhyML removes duplicate sequences by default. Use this option to leave them in. + alias_subpatt: Site aliasing is generalized at the subtree level. Sometimes lead to faster calculations. + boot_progress_display: Frequency at which the bootstrap progress bar will be updated. Default: 20. Must be an integer. + """ + command = ["phyml"] + output_files_list: List[Path] = [] + + # Input validation + if not input_file.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Input file '{input_file}' not found.", + "output_files": [], + } + command.extend(["-i", str(input_file)]) + + # Data type + command.extend(["-d", data_type]) + + # Sequential format + if sequential: + command.append("-q") + + # Number of data sets + if num_data_sets is not None: + if not isinstance(num_data_sets, int) or num_data_sets <= 0: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: num_data_sets must be a positive integer, got {num_data_sets}.", + "output_files": [], + } + command.extend(["-n", str(num_data_sets)]) + + # Parsimony starting tree + if use_pars_start_tree: + command.append("-p") + + # Bootstrap + # Default is -5, so always include it unless 0 is explicitly passed + if bootstrap != -5: + command.extend(["-b", str(bootstrap)]) + + # TBE + if tbe: + if bootstrap <= 0: + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: --tbe option requires bootstrap value > 0.", + "output_files": [], + } + command.append("--tbe") + + # Model + if model: + command.extend(["-m", model]) + + # AA rate file + if aa_rate_file: + if not aa_rate_file.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Amino acid rate file '{aa_rate_file}' not found.", + "output_files": [], + } + command.extend(["--aa_rate_file", str(aa_rate_file)]) + elif data_type == 'aa' and model == 'custom': + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: --aa_rate_file is compulsory for amino acid sequences with the 'custom' model.", + "output_files": [], + } + + # Character frequencies + if char_frequencies: + if isinstance(char_frequencies, str): + if char_frequencies not in ['e', 'm', 'o']: + # Check for fA,fC,fG,fT format + freqs = char_frequencies.split(',') + if len(freqs) != 4: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Invalid character frequencies format. Expected 'e', 'm', 'o' or 'fA,fC,fG,fT', got '{char_frequencies}'.", + "output_files": [], + } + try: + float_freqs = [float(f) for f in freqs] + if not all(0 <= f <= 1 for f in float_freqs): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Nucleotide frequencies must be between 0 and 1, got '{char_frequencies}'.", + "output_files": [], + } + if abs(sum(float_freqs) - 1.0) > 1e-6: # Allow for floating point inaccuracies + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Nucleotide frequencies must sum to 1.0, got '{char_frequencies}'.", + "output_files": [], + } + if data_type != 'nt': + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Nucleotide frequencies (fA,fC,fG,fT) are only valid for nucleotide-based models, but data_type is '{data_type}'.", + "output_files": [], + } + except ValueError: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Invalid nucleotide frequencies format. Expected 'fA,fC,fG,fT' with floats, got '{char_frequencies}'.", + "output_files": [], + } + command.extend(["-f", char_frequencies]) + + # Transition/transversion ratio + if ts_tv_ratio is not None: + if data_type != 'nt': + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: Transition/transversion ratio (-t) is only valid for nucleotide sequences.", + "output_files": [], + } + if isinstance(ts_tv_ratio, float) and ts_tv_ratio <= 0: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Transition/transversion ratio must be a positive value or 'e', got {ts_tv_ratio}.", + "output_files": [], + } + command.extend(["-t", str(ts_tv_ratio)]) + + # Proportion of invariable sites + if prop_invar is not None: + if isinstance(prop_invar, float) and not (0 <= prop_invar <= 1): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Proportion of invariable sites must be in [0,1] range or 'e', got {prop_invar}.", + "output_files": [], + } + command.extend(["-v", str(prop_invar)]) + + # Number of substitution categories + if num_subst_categories <= 0: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Number of substitution rate categories must be a positive integer, got {num_subst_categories}.", + "output_files": [], + } + if num_subst_categories != 4: # Only add if not default + command.extend(["-c", str(num_subst_categories)]) + + # FreeRate model + if freerates: + command.append("--freerates") + + # Gamma shape parameter + if gamma_shape_parameter is not None: + if isinstance(gamma_shape_parameter, float) and gamma_shape_parameter <= 0: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Gamma shape parameter must be a positive value or 'e', got {gamma_shape_parameter}.", + "output_files": [], + } + command.extend(["-a", str(gamma_shape_parameter)]) + + # Tree search move + if tree_search_move: + command.extend(["-s", tree_search_move]) + + # Input tree file + if input_tree_file: + if not input_tree_file.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Input tree file '{input_tree_file}' not found.", + "output_files": [], + } + command.extend(["-u", str(input_tree_file)]) + + # Optimization parameters + if optimization_params: + command.extend(["-o", optimization_params]) + + # Random start and number of random starts validation + if rand_start or num_rand_starts is not None: + if tree_search_move != 'SPR': + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: --rand_start and --n_rand_starts options are only valid if SPR searches are performed (i.e., -s SPR).", + "output_files": [], + } + if rand_start: + command.append("--rand_start") + if num_rand_starts is not None: + if not isinstance(num_rand_starts, int) or num_rand_starts <= 0: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: num_rand_starts must be a positive integer, got {num_rand_starts}.", + "output_files": [], + } + command.extend(["--n_rand_starts", str(num_rand_starts)]) + + # Random seed + if random_seed is not None: + if not isinstance(random_seed, int): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: random_seed must be an integer, got {random_seed}.", + "output_files": [], + } + command.extend(["--r_seed", str(random_seed)]) + + # Print site likelihood + if print_site_lnl: + command.append("--print_site_lnl") + + # Print trace + if print_trace: + command.append("--print_trace") + + # Run ID + if run_id: + command.extend(["--run_id", run_id]) + + # Quiet + if quiet: + command.append("--quiet") + + # No memory check + if no_memory_check: + command.append("--no_memory_check") + + # Leave duplicates + if leave_duplicates: + command.append("--leave_duplicates") + + # Alias subpatt + if alias_subpatt: + command.append("--alias_subpatt") + + # Boot progress display + if boot_progress_display <= 0: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: boot_progress_display must be a positive integer, got {boot_progress_display}.", + "output_files": [], + } + if boot_progress_display != 20: # Only add if not default + command.extend(["--boot_progress_display", str(boot_progress_display)]) + + # Determine expected output files + # PhyML typically outputs files in the same directory as the input file + # with a prefix derived from the input file name. + input_file_stem = input_file.name + + # PhyML output files usually have the format: + # _phyml_stats.txt + # _phyml_tree.txt + # If --run_id is used: __phyml_stats.txt + # If --print_site_lnl: _phyml_lk.txt (or with run_id) + # If --print_trace: _phyml_trace.txt (or with run_id) + + # Construct the base output filename prefix + if run_id: + base_output_name = f"{input_file_stem}_{run_id}_phyml" + else: + base_output_name = f"{input_file_stem}_phyml" + + # Add common output files + output_files_list.append(input_file.parent / f"{base_output_name}_stats.txt") + output_files_list.append(input_file.parent / f"{base_output_name}_tree.txt") + + # Add conditional output files + if print_site_lnl: + output_files_list.append(input_file.parent / f"{base_output_name}_lk.txt") + if print_trace: + output_files_list.append(input_file.parent / f"{base_output_name}_trace.txt") + + # Execute the command + process = None + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + + # Filter for actual existing output files + existing_output_files = [str(f) for f in output_files_list if f.exists()] + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": existing_output_files, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: phyml command not found. Please ensure it is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except Exception as e: + # Catch any other unexpected errors + return { + "command_executed": " ".join(command), + "stdout": process.stdout if process and hasattr(process, 'stdout') else "", + "stderr": f"An unexpected error occurred: {e}", + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/phyml_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/phyml_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5263d59d82217bf0f967f8545b21e8c6e81dbb80 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/phyml_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_phyml/app/phyml_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_phyml' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e09c5a0bed14848bd60eb42a8a02bbe16798cf8f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-phyml: + build: . + image: mcp-phyml:latest + container_name: mcp-phyml + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=phyml + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9d0147de3d813f75111821405ff471c39a997f2d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - phyml + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_phyml/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_picard-slim/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_picard-slim/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_picard-slim/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pplacer/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pplacer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pplacer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..630ef28416d77b7cea456a6e589239c36ccd5e01 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install prank via conda (e.g., from bioconda) +RUN conda install -c bioconda prank -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/prank_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/prank_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/prank_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/__pycache__/prank_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/__pycache__/prank_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41ab112345b14b04415d10b1e6c9a25c82f234be Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/__pycache__/prank_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/prank_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/prank_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a818fc4a008d856b760fe93d534e76de2e2366c9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/prank_server.py @@ -0,0 +1,252 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_prank' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def prank_align( + sequence_file: str, + tree_file: Optional[str] = None, + output_file: str = "output", + output_format: str = "fasta", + showxml: bool = False, + showtree: bool = False, + showanc: bool = False, + showevents: bool = False, + showall: bool = False, + support: bool = False, + njtree: bool = False, + treeonly: bool = False, + quiet: bool = False, + force_insertions_skipped: bool = False, + gaprate: Optional[float] = None, + gapext: Optional[float] = None, + codon: bool = False, + dna: bool = False, + protein: bool = False, + termgap: bool = False, + nomissing: bool = False, + keep: bool = False, + iterate: Optional[int] = None, + once: bool = False, + prunetree: bool = False, + prunedata: bool = False, + uselogs: bool = False, + translate: bool = False, + mttranslate: bool = False, +) -> Dict[str, Any]: + """ + Perform multiple sequence alignment using PRANK (Probabilistic Alignment Kit). + PRANK is a probabilistic multiple alignment program for DNA, codon and amino-acid sequences. + + Args: + sequence_file: Input sequence file in FASTA format. + tree_file: Optional guide tree file. If not provided, PRANK generates an approximate NJ tree. + output_file: Name of the output file (default: 'output'). + output_format: Output format ('fasta', 'phylipi', 'phylips', 'paml', 'nexus'). + showxml: Output xml-files. + showtree: Output dnd-files. + showanc: Output ancestral sequences. + showevents: Output evolutionary events. + showall: Output all of the above (xml, tree, anc, events). + support: Compute posterior support. + njtree: Estimate tree from input alignment (and realign). + treeonly: Estimate tree only. + quiet: Run in quiet mode. + force_insertions_skipped: If True, force insertions to be always skipped (+F). If False, use default (-F). + gaprate: Gap opening rate (default: dna 0.025 / prot 0.005). + gapext: Gap extension probability (default: dna 0.75 / prot 0.5). + codon: For coding DNA: use empirical codon model. + dna: Force use of DNA model (no autodetection). + protein: Force use of protein model (no autodetection). + termgap: Penalise terminal gaps normally. + nomissing: No missing data, use -F for terminal gaps. + keep: Keep alignment 'as is' (e.g., for ancestor inference). + iterate: Number of rounds of re-alignment iteration. + once: Run only once (same as iterate=1). + prunetree: Prune guide tree branches with no sequence data. + prunedata: Prune sequence data with no guide tree leaves. + uselogs: Slower but should work for a greater number of sequences. + translate: Translate to protein. + mttranslate: Translate to protein using mitochondrial table. + """ + # Input validation + seq_path = Path(sequence_file) + if not seq_path.exists(): + return {"error": f"Sequence file not found: {sequence_file}"} + + cmd = ["prank", f"-d={sequence_file}"] + + # Tree file + if tree_file: + tree_path = Path(tree_file) + if not tree_path.exists(): + return {"error": f"Tree file not found: {tree_file}"} + cmd.append(f"-t={tree_file}") + + # Output parameters + cmd.append(f"-o={output_file}") + + valid_formats = ['fasta', 'phylipi', 'phylips', 'paml', 'nexus'] + if output_format not in valid_formats: + return {"error": f"Invalid output format. Must be one of: {valid_formats}"} + cmd.append(f"-f={output_format}") + + # Boolean flags + if showxml: cmd.append("-showxml") + if showtree: cmd.append("-showtree") + if showanc: cmd.append("-showanc") + if showevents: cmd.append("-showevents") + if showall: cmd.append("-showall") + if support: cmd.append("-support") + if njtree: cmd.append("-njtree") + if treeonly: cmd.append("-treeonly") + if quiet: cmd.append("-quiet") + + # Model parameters + if force_insertions_skipped: + cmd.append("+F") + else: + cmd.append("-F") + + if gaprate is not None: + if gaprate < 0: + return {"error": "gaprate must be a positive float"} + cmd.append(f"-gaprate={gaprate}") + + if gapext is not None: + if not (0 <= gapext <= 1): + return {"error": "gapext must be between 0 and 1"} + cmd.append(f"-gapext={gapext}") + + if codon: cmd.append("-codon") + if dna: cmd.append("-DNA") + if protein: cmd.append("-protein") + if termgap: cmd.append("-termgap") + if nomissing: cmd.append("-nomissing") + + # Other parameters + if keep: cmd.append("-keep") + if once: + cmd.append("-once") + elif iterate is not None: + if iterate < 1: + return {"error": "iterate must be at least 1"} + cmd.append(f"-iterate={iterate}") + + if prunetree: cmd.append("-prunetree") + if prunedata: cmd.append("-prunedata") + if uselogs: cmd.append("-uselogs") + if translate: cmd.append("-translate") + if mttranslate: cmd.append("-mttranslate") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": list(Path(".").glob(f"{output_file}*")) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def prank_convert( + sequence_file: str, + output_file: str = "output", + output_format: str = "fasta", +) -> Dict[str, Any]: + """ + Convert a sequence alignment file to another format using PRANK. + + Args: + sequence_file: Input alignment file. + output_file: Name of the output file (default: 'output'). + output_format: Target format ('fasta', 'phylipi', 'phylips', 'paml', 'nexus'). + """ + seq_path = Path(sequence_file) + if not seq_path.exists(): + return {"error": f"Sequence file not found: {sequence_file}"} + + valid_formats = ['fasta', 'phylipi', 'phylips', 'paml', 'nexus'] + if output_format not in valid_formats: + return {"error": f"Invalid output format. Must be one of: {valid_formats}"} + + cmd = [ + "prank", + f"-d={sequence_file}", + "-convert", + f"-o={output_file}", + f"-f={output_format}" + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": list(Path(".").glob(f"{output_file}*")) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def prank_version() -> Dict[str, Any]: + """ + Check the version of PRANK installed. + """ + cmd = ["prank", "-version"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def prank_help_extended() -> Dict[str, Any]: + """ + Show extended help options for PRANK. + """ + cmd = ["prank", "-help"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + # PRANK sometimes returns non-zero for help + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/prank_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/prank_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1cec608e4613c17ee2f36b52e2c526113251f5a1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/prank_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_prank/app/prank_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_prank' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dd4a8f1013dd900e05c85d3a81bc6e84efd787a7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-prank: + build: . + image: mcp-prank:latest + container_name: mcp-prank + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=prank + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2bec34259c205309a89a791ca9b830103fba3d00 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - prank + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_prank/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5aed52ffb2fd45384fe91f5b0c566261207dd108 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install proteinortho via conda (e.g., from bioconda) +RUN conda install -c bioconda proteinortho -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/proteinortho_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/proteinortho_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/proteinortho_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/__pycache__/proteinortho_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/__pycache__/proteinortho_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..905e0860b830bf54acc375401490a4abc84bd0b4 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/__pycache__/proteinortho_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/proteinortho_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/proteinortho_server.py new file mode 100644 index 0000000000000000000000000000000000000000..efd8a19e61ac9e0c660206454c53fdbe69a3d62f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/proteinortho_server.py @@ -0,0 +1,291 @@ +from typing import List, Optional, Union +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_proteinortho' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def proteinortho( + fasta_files: List[str], + project: str = "myproject", + cpus: int = 1, + p: str = "diamond", + e: float = 1e-05, + cov: int = 50, + identity: int = 25, + sim: float = 0.95, + singles: bool = False, + selfblast: bool = False, + clean: bool = True, + step: int = 0, + force: bool = False, + keep: bool = False, + check_dependencies: bool = False, +): + """ + Proteinortho is a tool to detect orthologous genes within different species. + It handles the full pipeline from sequence comparison (BLAST/Diamond) to clustering. + + Args: + fasta_files: List of FASTA files (proteins or DNA) to compare. + project: Prefix for all output files. + cpus: Number of processors to use. + p: Search engine to use (diamond, blastp, blastn, blastp+, blastn+, mmseqs, lastp). + e: E-value threshold for the search engine. + cov: Minimum coverage of the best alignment in % (default: 50). + identity: Minimum identity of the best alignment in % (default: 25). + sim: Minimum bit-score similarity (0..1) (default: 0.95). + singles: Report genes without orthologs (singletons). + selfblast: Perform self-comparisons within species. + clean: Remove temporary files after completion. + step: Start at a specific step (1: blast, 2: clustering, 3: orthology). 0 runs all. + force: Force recalculation even if results exist. + keep: Keep all temporary files. + check_dependencies: Check if all required dependencies are installed. + """ + # Input validation + if not fasta_files: + return {"error": "At least one FASTA file must be provided."} + + valid_fasta = [] + for f in fasta_files: + path = Path(f) + if not path.exists(): + return {"error": f"Input file not found: {f}"} + valid_fasta.append(str(path.absolute())) + + # Build command + cmd = ["proteinortho"] + cmd.append(f"-project={project}") + cmd.append(f"-cpus={cpus}") + cmd.append(f"-p={p}") + cmd.append(f"-e={e}") + cmd.append(f"-cov={cov}") + cmd.append(f"-identity={identity}") + cmd.append(f"-sim={sim}") + + if singles: cmd.append("-singles") + if selfblast: cmd.append("-selfblast") + if clean: cmd.append("-clean") + if force: cmd.append("-force") + if keep: cmd.append("-keep") + if check_dependencies: cmd.append("-check") + if step > 0: cmd.append(f"-step={step}") + + cmd.extend(valid_fasta) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Identify expected output files + output_extensions = [".proteinortho", ".proteinortho-graph", ".blast-graph", ".summary"] + found_outputs = [] + for ext in output_extensions: + out_path = Path(f"{project}{ext}") + if out_path.exists(): + found_outputs.append(str(out_path.absolute())) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": found_outputs + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def proteinortho_grab_proteins( + ortho_file: str, + fasta_files: List[str], + group_ids: Optional[List[str]] = None, + species_names: Optional[List[str]] = None, + out_prefix: str = "grabbed_proteins", +): + """ + Extract protein sequences from orthology groups identified by proteinortho. + + Args: + ortho_file: The .proteinortho output file from a proteinortho run. + fasta_files: The original FASTA files used in the proteinortho run. + group_ids: Specific group IDs to extract (e.g., ['0', '1']). + species_names: Specific species names to extract. + out_prefix: Prefix for the output FASTA files. + """ + ortho_path = Path(ortho_file) + if not ortho_path.exists(): + return {"error": f"Orthology file not found: {ortho_file}"} + + valid_fasta = [] + for f in fasta_files: + path = Path(f) + if not path.exists(): + return {"error": f"FASTA file not found: {f}"} + valid_fasta.append(str(path.absolute())) + + # proteinortho_grab_proteins.pl [options] group_ids file.proteinortho file1.fa ... + cmd = ["proteinortho_grab_proteins.pl"] + + if species_names: + cmd.append(f"-species={','.join(species_names)}") + + cmd.append(f"-to={out_prefix}") + + # If no group IDs provided, the tool usually expects a '-' or specific IDs + if group_ids: + cmd.append(",".join(group_ids)) + else: + cmd.append("-") # Extract all + + cmd.append(str(ortho_path.absolute())) + cmd.extend(valid_fasta) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "info": f"Sequences extracted with prefix: {out_prefix}" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def proteinortho_summary( + ortho_file: str, +): + """ + Generate a summary of a proteinortho run. + + Args: + ortho_file: The .proteinortho output file. + """ + ortho_path = Path(ortho_file) + if not ortho_path.exists(): + return {"error": f"Orthology file not found: {ortho_file}"} + + cmd = ["proteinortho_summary.pl", str(ortho_path.absolute())] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def proteinortho_clustering( + blast_graph_file: str, + cpus: int = 1, + connectivity: float = 0.1, + sim: float = 0.95, + e_value: float = 1e-05, + verbose: bool = False, +): + """ + The standalone clustering engine of proteinortho. + Useful if you already have a .blast-graph file and want to re-cluster with different parameters. + + Args: + blast_graph_file: The .blast-graph file containing pairwise similarities. + cpus: Number of processors to use. + connectivity: Minimum connectivity (0..1) (default: 0.1). + sim: Minimum bit-score similarity (0..1) (default: 0.95). + e_value: E-value threshold. + verbose: Enable verbose output. + """ + graph_path = Path(blast_graph_file) + if not graph_path.exists(): + return {"error": f"Blast graph file not found: {blast_graph_file}"} + + cmd = ["proteinortho_clustering"] + cmd.append(f"-cpus={cpus}") + cmd.append(f"-p={connectivity}") + cmd.append(f"-m={sim}") + cmd.append(f"-e={e_value}") + if verbose: cmd.append("-v") + + cmd.append(str(graph_path.absolute())) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "info": "Clustering completed. Check stdout for group definitions." + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def proteinortho_format( + blast_files: List[str], + cpus: int = 1, + verbose: bool = False, +): + """ + Formats raw BLAST/Diamond output files into the proteinortho graph format. + + Args: + blast_files: List of raw output files from the search engine. + cpus: Number of processors to use. + verbose: Enable verbose output. + """ + valid_files = [] + for f in blast_files: + path = Path(f) + if not path.exists(): + return {"error": f"Blast file not found: {f}"} + valid_files.append(str(path.absolute())) + + cmd = ["proteinortho_format"] + cmd.append(f"-cpus={cpus}") + if verbose: cmd.append("-v") + cmd.extend(valid_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "info": "Formatting completed. Output is usually directed to stdout or a graph file." + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/proteinortho_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/proteinortho_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9d83853cfeb9b5e09fd8815961bf74aeaab88d28 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/proteinortho_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_proteinortho/app/proteinortho_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_proteinortho' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b62e1071ff9d7f5d78acd65780c528790824ad8e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-proteinortho: + build: . + image: mcp-proteinortho:latest + container_name: mcp-proteinortho + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=proteinortho + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..55b0be18f2ee33c88b15e417d08c1de3f7377708 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - proteinortho + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteinortho/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e5dc111981e016c932c1bfce12fd56d6940ed089 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install py2bit via conda (e.g., from bioconda) +RUN conda install -c bioconda py2bit -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/py2bit_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/py2bit_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/py2bit_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/__pycache__/py2bit_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/__pycache__/py2bit_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d733aa9d65e882c201ec06f2eaaf4b76525807bd Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/__pycache__/py2bit_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/py2bit_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/py2bit_server.py new file mode 100644 index 0000000000000000000000000000000000000000..87c2cd05b6667872117029ff80819d7c2148ef56 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/py2bit_server.py @@ -0,0 +1,232 @@ +import subprocess +import json +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_py2bit' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def py2bit_get_info( + input_2bit: str, +) -> Dict[str, Any]: + """ + Retrieve general information about a 2bit file, including file size, + number of chromosomes, total sequence length, and masked lengths. + + Args: + input_2bit: Path to the .2bit file. + """ + input_path = Path(input_2bit) + if not input_path.exists(): + return {"error": f"Input file {input_2bit} does not exist."} + + # We use a python one-liner to access the library as it is a Python extension + # Note: storeMasked=True is used to ensure soft-masked length is reported if available + py_cmd = ( + f"import py2bit, json; " + f"tb = py2bit.open('{str(input_path)}', True); " + f"print(json.dumps(tb.info()))" + ) + + cmd = ["python", "-c", py_cmd] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "info": json.loads(result.stdout.strip()), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr or str(e), + "stdout": e.stdout + } + +@mcp.tool() +def py2bit_get_chroms( + input_2bit: str, + chromosome: Optional[str] = None, +) -> Dict[str, Any]: + """ + Access the list of chromosomes and their lengths from a 2bit file. + + Args: + input_2bit: Path to the .2bit file. + chromosome: Optional specific chromosome name to get the length for. + If omitted, returns a dictionary of all chromosomes and lengths. + """ + input_path = Path(input_2bit) + if not input_path.exists(): + return {"error": f"Input file {input_2bit} does not exist."} + + chrom_arg = f"'{chromosome}'" if chromosome else "" + py_cmd = ( + f"import py2bit, json; " + f"tb = py2bit.open('{str(input_path)}'); " + f"print(json.dumps(tb.chroms({chrom_arg})))" + ) + + cmd = ["python", "-c", py_cmd] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "chromosomes": json.loads(result.stdout.strip()), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr or str(e) + } + +@mcp.tool() +def py2bit_get_sequence( + input_2bit: str, + chromosome: str, + start: int = 0, + end: int = 0, + store_masked: bool = False, +) -> Dict[str, Any]: + """ + Fetch the sequence of a full or partial chromosome from a 2bit file. + Uses 0-based half-open coordinates. + + Args: + input_2bit: Path to the .2bit file. + chromosome: Name of the chromosome/contig. + start: 0-based start position (default 0). + end: 0-based end position (default 0, which fetches until the end of the chromosome). + store_masked: If True, includes soft-masking information (lower case bases). + """ + input_path = Path(input_2bit) + if not input_path.exists(): + return {"error": f"Input file {input_2bit} does not exist."} + + # Handle default end=0 to mean full chromosome in the python script + end_val = end if end > 0 else "None" + py_cmd = ( + f"import py2bit; " + f"tb = py2bit.open('{str(input_path)}', {store_masked}); " + f"print(tb.sequence('{chromosome}', {start}, {end_val}))" + ) + + cmd = ["python", "-c", py_cmd] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "sequence": result.stdout.strip(), + "length": len(result.stdout.strip()), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr or str(e) + } + +@mcp.tool() +def py2bit_get_bases( + input_2bit: str, + chromosome: str, + start: int = 0, + end: int = 0, + as_fraction: bool = True, +) -> Dict[str, Any]: + """ + Compute the composition of bases (A, C, T, G) in a chromosome or specific region. + + Args: + input_2bit: Path to the .2bit file. + chromosome: Name of the chromosome/contig. + start: 0-based start position (default 0). + end: 0-based end position (default 0, which fetches until the end of the chromosome). + as_fraction: If True (default), returns fractions (0.0-1.0). If False, returns integer counts. + """ + input_path = Path(input_2bit) + if not input_path.exists(): + return {"error": f"Input file {input_2bit} does not exist."} + + end_val = end if end > 0 else "None" + py_cmd = ( + f"import py2bit, json; " + f"tb = py2bit.open('{str(input_path)}'); " + f"print(json.dumps(tb.bases('{chromosome}', {start}, {end_val}, {as_fraction})))" + ) + + cmd = ["python", "-c", py_cmd] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "base_stats": json.loads(result.stdout.strip()), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr or str(e) + } + +@mcp.tool() +def py2bit_get_masked_blocks( + input_2bit: str, + chromosome: str, + mask_type: str = "hard", + start: int = 0, + end: int = 0, +) -> Dict[str, Any]: + """ + Fetch masked blocks (hard-masked NNNN or soft-masked lowercase) for a chromosome or region. + + Args: + input_2bit: Path to the .2bit file. + chromosome: Name of the chromosome/contig. + mask_type: Type of masking to query: 'hard' (default) or 'soft'. + start: 0-based start position for overlap query (default 0). + end: 0-based end position for overlap query (default 0, returns all blocks). + """ + input_path = Path(input_2bit) + if not input_path.exists(): + return {"error": f"Input file {input_2bit} does not exist."} + + if mask_type not in ["hard", "soft"]: + return {"error": "mask_type must be either 'hard' or 'soft'."} + + method = "hardMaskedBlocks" if mask_type == "hard" else "softMaskedBlocks" + end_val = end if end > 0 else "None" + + # softMaskedBlocks requires storeMasked=True during open + py_cmd = ( + f"import py2bit, json; " + f"tb = py2bit.open('{str(input_path)}', True); " + f"print(json.dumps(tb.{method}('{chromosome}', {start}, {end_val})))" + ) + + cmd = ["python", "-c", py_cmd] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "mask_type": mask_type, + "blocks": json.loads(result.stdout.strip()), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr or str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/py2bit_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/py2bit_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..688813cd2e2b6a7125e5300b9e43b0f0396ad697 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/py2bit_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_py2bit/app/py2bit_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_py2bit' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..39a9a46e92cb0a139fc04a8d84a31ded94953a23 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-py2bit: + build: . + image: mcp-py2bit:latest + container_name: mcp-py2bit + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=py2bit + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b972826e7fc22d637f61eb4f9916f6d4aead5a07 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - py2bit + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_py2bit/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..80b76ccbf2a98077416e7790faa3f27d530fc3c0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install pyhmmer via conda (e.g., from bioconda) +RUN conda install -c bioconda pyhmmer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/pyhmmer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/pyhmmer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/pyhmmer_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/__pycache__/pyhmmer_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/__pycache__/pyhmmer_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5fe7adae7834e6ef08c620e349f9934ed0733a4 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/__pycache__/pyhmmer_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/pyhmmer_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/pyhmmer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bbcad3e3b3f5529ac4faadeab688367f0808fed4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/pyhmmer_server.py @@ -0,0 +1,771 @@ +import pyhmmer +from pathlib import Path +import tempfile +from typing import Optional, List, Dict, Any, Iterable, Literal + +# --- Helper functions for writing pyhmmer results to files --- + +def _write_hits_to_tblout(hits_iterable: Iterable[pyhmmer.plan7.TopHits], output_path: Path): + """ + Writes an iterable of pyhmmer.plan7.TopHits objects to a simplified tabular + output file, similar to HMMER's --tblout format. + """ + with open(output_path, "w") as f: + f.write("# target name\ttarget accession\tquery name\tquery accession\tE-value\tscore\tbias\t# of domains\n") + for hits in hits_iterable: + query_name = hits.query.name.decode() if hits.query.name else "N/A" + query_acc = hits.query.accession.decode() if hits.query.accession else "N/A" + for hit in hits: + target_name = hit.name.decode() if hit.name else "N/A" + target_acc = hit.accession.decode() if hit.accession else "N/A" + f.write( + f"{target_name}\t{target_acc}\t" + f"{query_name}\t{query_acc}\t" + f"{hit.evalue:.2e}\t{hit.score:.1f}\t{hit.bias:.1f}\t" + f"{len(hit.domains)}\n" + ) + +def _write_hits_to_domtblout(hits_iterable: Iterable[pyhmmer.plan7.TopHits], output_path: Path): + """ + Writes an iterable of pyhmmer.plan7.TopHits objects to a simplified domain + tabular output file, similar to HMMER's --domtblout format. + """ + with open(output_path, "w") as f: + f.write("# target name\ttarget accession\tquery name\tquery accession\t" + "domain E-value\tdomain score\tdomain bias\t" + "hmm_from\thmm_to\tali_from\tali_to\tenv_from\tenv_to\n") + for hits in hits_iterable: + query_name = hits.query.name.decode() if hits.query.name else "N/A" + query_acc = hits.query.accession.decode() if hits.query.accession else "N/A" + for hit in hits: + target_name = hit.name.decode() if hit.name else "N/A" + target_acc = hit.accession.decode() if hit.accession else "N/A" + for domain in hit.domains: + f.write( + f"{target_name}\t{target_acc}\t" + f"{query_name}\t{query_acc}\t" + f"{domain.evalue:.2e}\t{domain.score:.1f}\t{domain.bias:.1f}\t" + f"{domain.hmm_from}\t{domain.hmm_to}\t" + f"{domain.ali_from}\t{domain.ali_to}\t" + f"{domain.env_from}\t{domain.env_to}\n" + ) + +def _write_alignment_to_file(alignment: pyhmmer.easel.Alignment, output_path: Path, output_format: str): + """ + Writes a pyhmmer.easel.Alignment object to a file in the specified format. + """ + # pyhmmer.easel.Alignment.write expects a file-like object opened in binary mode ('wb') + with open(output_path, "wb") as f: + alignment.write(f, format=output_format) + +# --- MCP Tool Definitions --- + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_pyhmmer' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def hmmsearch( + hmm_file: Path, + sequence_file: Path, + cpus: int = 1, + e_value_cutoff: Optional[float] = None, + dom_e_value_cutoff: Optional[float] = None, + bit_score_cutoff: Optional[float] = None, + max_target_seqs: Optional[int] = None, + cut_ga: bool = False, + cut_nc: bool = False, + cut_tc: bool = False, + bias_filter: bool = False, + output_tblout: Optional[Path] = None, + output_domtblout: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Searches a sequence database against one or more profile HMMs using pyhmmer.hmmsearch. + + This function wraps the pyhmmer.hmmsearch API, which provides Python bindings + to HMMER3's hmmsearch functionality. It searches protein sequences against + a database of profile HMMs. + + Args: + hmm_file: Path to the HMM database file (e.g., in HMMER3 text format). + sequence_file: Path to the target sequence database file (e.g., FASTA format). + cpus: Number of CPU threads to use for parallel processing. Must be a positive integer. + e_value_cutoff: E-value threshold for reporting hits. Hits with E-value > this are not reported. + dom_e_value_cutoff: E-value threshold for reporting domains. Domains with E-value > this are not reported. + bit_score_cutoff: Bit score threshold for reporting hits. Hits with score < this are not reported. + max_target_seqs: Maximum number of target sequences to report per query HMM. + cut_ga: Use the HMM's trusted gathering cutoff (GA) to set score thresholds. + cut_nc: Use the HMM's noise cutoff (NC) to set score thresholds. + cut_tc: Use the HMM's trusted cutoff (TC) to set score thresholds. + bias_filter: Turn on the bias filter (default is off). + output_tblout: Optional path to write the tabular summary of hits. If not provided, a temporary file will be created. + output_domtblout: Optional path to write the tabular summary of domain hits. If not provided, a temporary file will be created. + + Returns: + A dictionary containing: + - "command_executed": A string representing the pyhmmer API call. + - "stdout": Standard output (empty for pyhmmer API calls unless explicitly captured). + - "stderr": Standard error (empty for pyhmmer API calls unless explicitly captured). + - "output_files": A list of paths to generated output files (e.g., tabular hit files). + """ + # Input validation + if not hmm_file.is_file(): + raise FileNotFoundError(f"HMM file not found: {hmm_file}") + if not sequence_file.is_file(): + raise FileNotFoundError(f"Sequence file not found: {sequence_file}") + if cpus < 1: + raise ValueError("Number of CPUs must be a positive integer.") + if e_value_cutoff is not None and e_value_cutoff <= 0: + raise ValueError("E-value cutoff must be positive.") + if dom_e_value_cutoff is not None and dom_e_value_cutoff <= 0: + raise ValueError("Domain E-value cutoff must be positive.") + if bit_score_cutoff is not None and bit_score_cutoff < 0: + raise ValueError("Bit score cutoff must be non-negative.") + if max_target_seqs is not None and max_target_seqs < 1: + raise ValueError("Max target sequences must be a positive integer.") + + # Prepare output files + temp_output_tblout = False + if output_tblout is None: + output_tblout = Path(tempfile.NamedTemporaryFile(delete=False, suffix=".tblout").name) + temp_output_tblout = True + + temp_output_domtblout = False + if output_domtblout is None: + output_domtblout = Path(tempfile.NamedTemporaryFile(delete=False, suffix=".domtblout").name) + temp_output_domtblout = True + + output_files: List[Path] = [] + stdout_buffer = [] + stderr_buffer = [] + + try: + # Load HMMs and sequences + with pyhmmer.plan7.HMMFile(hmm_file) as hmms_reader: + hmms = list(hmms_reader) # Load all HMMs into memory + + with pyhmmer.easel.SequenceFile(sequence_file, digital=True) as seqs_reader: + sequences = seqs_reader.read_block() # Load sequences into memory + + # Construct pyhmmer.hmmsearch arguments + search_kwargs = { + "cpus": cpus, + "cut_ga": cut_ga, + "cut_nc": cut_nc, + "cut_tc": cut_tc, + "bias_filter": bias_filter, + } + if e_value_cutoff is not None: + search_kwargs["E"] = e_value_cutoff + if dom_e_value_cutoff is not None: + search_kwargs["domE"] = dom_e_value_cutoff + if bit_score_cutoff is not None: + search_kwargs["T"] = bit_score_cutoff + if max_target_seqs is not None: + search_kwargs["max_target_seqs"] = max_target_seqs + + # Execute hmmsearch and collect results (pyhmmer.hmmsearch returns a generator) + all_hits = list(pyhmmer.hmmsearch(hmms, sequences, **search_kwargs)) + + # Write results to output files + _write_hits_to_tblout(all_hits, output_tblout) + output_files.append(output_tblout) + + _write_hits_to_domtblout(all_hits, output_domtblout) + output_files.append(output_domtblout) + + except Exception as e: + stderr_buffer.append(f"Error during pyhmmer.hmmsearch execution: {e}") + # Clean up temporary files if an error occurred + if temp_output_tblout and output_tblout.exists(): + output_tblout.unlink() + if temp_output_domtblout and output_domtblout.exists(): + output_domtblout.unlink() + return { + "command_executed": f"pyhmmer.hmmsearch(hmms={hmm_file.name}, sequences={sequence_file.name}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": [], + } + + return { + "command_executed": f"pyhmmer.hmmsearch(hmms={hmm_file.name}, sequences={sequence_file.name}, cpus={cpus}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": output_files, + } + +@mcp.tool() +def hmmscan( + sequence_file: Path, + hmm_file: Path, + cpus: int = 1, + e_value_cutoff: Optional[float] = None, + dom_e_value_cutoff: Optional[float] = None, + bit_score_cutoff: Optional[float] = None, + max_target_seqs: Optional[int] = None, + cut_ga: bool = False, + cut_nc: bool = False, + cut_tc: bool = False, + bias_filter: bool = False, + output_tblout: Optional[Path] = None, + output_domtblout: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Searches a sequence (or sequences) against a profile HMM database using pyhmmer.hmmscan. + + This function wraps the pyhmmer.hmmscan API, which provides Python bindings + to HMMER3's hmmscan functionality. It searches protein sequences against + a database of profile HMMs. + + Args: + sequence_file: Path to the query sequence file (e.g., FASTA format). + hmm_file: Path to the HMM database file (e.g., in HMMER3 text format). + cpus: Number of CPU threads to use for parallel processing. Must be a positive integer. + e_value_cutoff: E-value threshold for reporting hits. Hits with E-value > this are not reported. + dom_e_value_cutoff: E-value threshold for reporting domains. Domains with E-value > this are not reported. + bit_score_cutoff: Bit score threshold for reporting hits. Hits with score < this are not reported. + max_target_seqs: Maximum number of target sequences to report per query sequence. + cut_ga: Use the HMM's trusted gathering cutoff (GA) to set score thresholds. + cut_nc: Use the HMM's noise cutoff (NC) to set score thresholds. + cut_tc: Use the HMM's trusted cutoff (TC) to set score thresholds. + bias_filter: Turn on the bias filter (default is off). + output_tblout: Optional path to write the tabular summary of hits. If not provided, a temporary file will be created. + output_domtblout: Optional path to write the tabular summary of domain hits. If not provided, a temporary file will be created. + + Returns: + A dictionary containing: + - "command_executed": A string representing the pyhmmer API call. + - "stdout": Standard output (empty for pyhmmer API calls unless explicitly captured). + - "stderr": Standard error (empty for pyhmmer API calls unless explicitly captured). + - "output_files": A list of paths to generated output files (e.g., tabular hit files). + """ + # Input validation + if not hmm_file.is_file(): + raise FileNotFoundError(f"HMM file not found: {hmm_file}") + if not sequence_file.is_file(): + raise FileNotFoundError(f"Sequence file not found: {sequence_file}") + if cpus < 1: + raise ValueError("Number of CPUs must be a positive integer.") + if e_value_cutoff is not None and e_value_cutoff <= 0: + raise ValueError("E-value cutoff must be positive.") + if dom_e_value_cutoff is not None and dom_e_value_cutoff <= 0: + raise ValueError("Domain E-value cutoff must be positive.") + if bit_score_cutoff is not None and bit_score_cutoff < 0: + raise ValueError("Bit score cutoff must be non-negative.") + if max_target_seqs is not None and max_target_seqs < 1: + raise ValueError("Max target sequences must be a positive integer.") + + # Prepare output files + temp_output_tblout = False + if output_tblout is None: + output_tblout = Path(tempfile.NamedTemporaryFile(delete=False, suffix=".tblout").name) + temp_output_tblout = True + + temp_output_domtblout = False + if output_domtblout is None: + output_domtblout = Path(tempfile.NamedTemporaryFile(delete=False, suffix=".domtblout").name) + temp_output_domtblout = True + + output_files: List[Path] = [] + stdout_buffer = [] + stderr_buffer = [] + + try: + # Load HMMs and sequences + with pyhmmer.plan7.HMMFile(hmm_file) as hmms_reader: + hmms = list(hmms_reader) # Load all HMMs into memory + + with pyhmmer.easel.SequenceFile(sequence_file, digital=True) as seqs_reader: + sequences = seqs_reader.read_block() # Load sequences into memory + + # Construct pyhmmer.hmmscan arguments + search_kwargs = { + "cpus": cpus, + "cut_ga": cut_ga, + "cut_nc": cut_nc, + "cut_tc": cut_tc, + "bias_filter": bias_filter, + } + if e_value_cutoff is not None: + search_kwargs["E"] = e_value_cutoff + if dom_e_value_cutoff is not None: + search_kwargs["domE"] = dom_e_value_cutoff + if bit_score_cutoff is not None: + search_kwargs["T"] = bit_score_cutoff + if max_target_seqs is not None: + search_kwargs["max_target_seqs"] = max_target_seqs + + # Execute hmmscan and collect results (pyhmmer.hmmscan returns a generator) + all_hits = list(pyhmmer.hmmscan(sequences, hmms, **search_kwargs)) + + # Write results to output files + _write_hits_to_tblout(all_hits, output_tblout) + output_files.append(output_tblout) + + _write_hits_to_domtblout(all_hits, output_domtblout) + output_files.append(output_domtblout) + + except Exception as e: + stderr_buffer.append(f"Error during pyhmmer.hmmscan execution: {e}") + # Clean up temporary files if an error occurred + if temp_output_tblout and output_tblout.exists(): + output_tblout.unlink() + if temp_output_domtblout and output_domtblout.exists(): + output_domtblout.unlink() + return { + "command_executed": f"pyhmmer.hmmscan(sequences={sequence_file.name}, hmms={hmm_file.name}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": [], + } + + return { + "command_executed": f"pyhmmer.hmmscan(sequences={sequence_file.name}, hmms={hmm_file.name}, cpus={cpus}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": output_files, + } + +@mcp.tool() +def nhmmer( + hmm_file: Path, + sequence_file: Path, + cpus: int = 1, + e_value_cutoff: Optional[float] = None, + dom_e_value_cutoff: Optional[float] = None, + bit_score_cutoff: Optional[float] = None, + max_target_seqs: Optional[int] = None, + bias_filter: bool = False, + output_tblout: Optional[Path] = None, + output_domtblout: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Searches a DNA/RNA sequence database against one or more profile HMMs using pyhmmer.nhmmer. + + This function wraps the pyhmmer.nhmmer API, which provides Python bindings + to HMMER3's nhmmer functionality. It searches nucleic acid sequences against + a database of profile HMMs. + + Args: + hmm_file: Path to the HMM database file (e.g., in HMMER3 text format). This HMM should be nucleic. + sequence_file: Path to the target nucleic acid sequence database file (e.g., FASTA format). + cpus: Number of CPU threads to use for parallel processing. Must be a positive integer. + e_value_cutoff: E-value threshold for reporting hits. Hits with E-value > this are not reported. + dom_e_value_cutoff: E-value threshold for reporting domains. Domains with E-value > this are not reported. + bit_score_cutoff: Bit score threshold for reporting hits. Hits with score < this are not reported. + max_target_seqs: Maximum number of target sequences to report per query HMM. + bias_filter: Turn on the bias filter (default is off). + output_tblout: Optional path to write the tabular summary of hits. If not provided, a temporary file will be created. + output_domtblout: Optional path to write the tabular summary of domain hits. If not provided, a temporary file will be created. + + Returns: + A dictionary containing: + - "command_executed": A string representing the pyhmmer API call. + - "stdout": Standard output (empty for pyhmmer API calls unless explicitly captured). + - "stderr": Standard error (empty for pyhmmer API calls unless explicitly captured). + - "output_files": A list of paths to generated output files (e.g., tabular hit files). + """ + # Input validation + if not hmm_file.is_file(): + raise FileNotFoundError(f"HMM file not found: {hmm_file}") + if not sequence_file.is_file(): + raise FileNotFoundError(f"Sequence file not found: {sequence_file}") + if cpus < 1: + raise ValueError("Number of CPUs must be a positive integer.") + if e_value_cutoff is not None and e_value_cutoff <= 0: + raise ValueError("E-value cutoff must be positive.") + if dom_e_value_cutoff is not None and dom_e_value_cutoff <= 0: + raise ValueError("Domain E-value cutoff must be positive.") + if bit_score_cutoff is not None and bit_score_cutoff < 0: + raise ValueError("Bit score cutoff must be non-negative.") + if max_target_seqs is not None and max_target_seqs < 1: + raise ValueError("Max target sequences must be a positive integer.") + + # Prepare output files + temp_output_tblout = False + if output_tblout is None: + output_tblout = Path(tempfile.NamedTemporaryFile(delete=False, suffix=".tblout").name) + temp_output_tblout = True + + temp_output_domtblout = False + if output_domtblout is None: + output_domtblout = Path(tempfile.NamedTemporaryFile(delete=False, suffix=".domtblout").name) + temp_output_domtblout = True + + output_files: List[Path] = [] + stdout_buffer = [] + stderr_buffer = [] + + try: + # Load HMMs (nhmmer expects nucleic alphabet HMMs) + with pyhmmer.plan7.HMMFile(hmm_file) as hmms_reader: + hmms = list(hmms_reader) + + # For nhmmer, sequences should be nucleic. Explicitly use DNA alphabet. + # pyhmmer.easel.Alphabet.dna() can be used for both DNA and RNA, + # as HMMER's nhmmer typically handles both. + nucleic_alphabet = pyhmmer.easel.Alphabet.dna() + with pyhmmer.easel.SequenceFile(sequence_file, digital=True, alphabet=nucleic_alphabet) as seqs_reader: + sequences = seqs_reader.read_block() + + # Construct pyhmmer.nhmmer arguments + search_kwargs = { + "cpus": cpus, + "bias_filter": bias_filter, + } + if e_value_cutoff is not None: + search_kwargs["E"] = e_value_cutoff + if dom_e_value_cutoff is not None: + search_kwargs["domE"] = dom_e_value_cutoff + if bit_score_cutoff is not None: + search_kwargs["T"] = bit_score_cutoff + if max_target_seqs is not None: + search_kwargs["max_target_seqs"] = max_target_seqs + + # Execute nhmmer and collect results (pyhmmer.nhmmer returns a generator) + all_hits = list(pyhmmer.nhmmer(hmms, sequences, **search_kwargs)) + + # Write results to output files + _write_hits_to_tblout(all_hits, output_tblout) + output_files.append(output_tblout) + + _write_hits_to_domtblout(all_hits, output_domtblout) + output_files.append(output_domtblout) + + except Exception as e: + stderr_buffer.append(f"Error during pyhmmer.nhmmer execution: {e}") + # Clean up temporary files if an error occurred + if temp_output_tblout and output_tblout.exists(): + output_tblout.unlink() + if temp_output_domtblout and output_domtblout.exists(): + output_domtblout.unlink() + return { + "command_executed": f"pyhmmer.nhmmer(hmms={hmm_file.name}, sequences={sequence_file.name}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": [], + } + + return { + "command_executed": f"pyhmmer.nhmmer(hmms={hmm_file.name}, sequences={sequence_file.name}, cpus={cpus}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": output_files, + } + +@mcp.tool() +def phmmer( + query_sequence_file: Path, + target_sequence_file: Path, + cpus: int = 1, + e_value_cutoff: Optional[float] = None, + bit_score_cutoff: Optional[float] = None, + max_target_seqs: Optional[int] = None, + bias_filter: bool = False, + output_tblout: Optional[Path] = None, + output_domtblout: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Searches a protein sequence against a protein sequence database using pyhmmer.phmmer. + + This function wraps the pyhmmer.phmmer API, which provides Python bindings + to HMMER3's phmmer functionality. It performs sequence-vs-sequence searches + using HMMER's acceleration heuristics. + + Args: + query_sequence_file: Path to the query protein sequence file (e.g., FASTA format). + target_sequence_file: Path to the target protein sequence database file (e.g., FASTA format). + cpus: Number of CPU threads to use for parallel processing. Must be a positive integer. + e_value_cutoff: E-value threshold for reporting hits. Hits with E-value > this are not reported. + bit_score_cutoff: Bit score threshold for reporting hits. Hits with score < this are not reported. + max_target_seqs: Maximum number of target sequences to report per query sequence. + bias_filter: Turn on the bias filter (default is off). + output_tblout: Optional path to write the tabular summary of hits. If not provided, a temporary file will be created. + output_domtblout: Optional path to write the tabular summary of domain hits. If not provided, a temporary file will be created. + + Returns: + A dictionary containing: + - "command_executed": A string representing the pyhmmer API call. + - "stdout": Standard output (empty for pyhmmer API calls unless explicitly captured). + - "stderr": Standard error (empty for pyhmmer API calls unless explicitly captured). + - "output_files": A list of paths to generated output files (e.g., tabular hit files). + """ + # Input validation + if not query_sequence_file.is_file(): + raise FileNotFoundError(f"Query sequence file not found: {query_sequence_file}") + if not target_sequence_file.is_file(): + raise FileNotFoundError(f"Target sequence file not found: {target_sequence_file}") + if cpus < 1: + raise ValueError("Number of CPUs must be a positive integer.") + if e_value_cutoff is not None and e_value_cutoff <= 0: + raise ValueError("E-value cutoff must be positive.") + if bit_score_cutoff is not None and bit_score_cutoff < 0: + raise ValueError("Bit score cutoff must be non-negative.") + if max_target_seqs is not None and max_target_seqs < 1: + raise ValueError("Max target sequences must be a positive integer.") + + # Prepare output files + temp_output_tblout = False + if output_tblout is None: + output_tblout = Path(tempfile.NamedTemporaryFile(delete=False, suffix=".tblout").name) + temp_output_tblout = True + + temp_output_domtblout = False + if output_domtblout is None: + output_domtblout = Path(tempfile.NamedTemporaryFile(delete=False, suffix=".domtblout").name) + temp_output_domtblout = True + + output_files: List[Path] = [] + stdout_buffer = [] + stderr_buffer = [] + + try: + # Load query and target sequences (phmmer expects protein alphabet) + protein_alphabet = pyhmmer.easel.Alphabet.amino() + with pyhmmer.easel.SequenceFile(query_sequence_file, digital=True, alphabet=protein_alphabet) as query_seqs_reader: + query_sequences = query_seqs_reader.read_block() + + with pyhmmer.easel.SequenceFile(target_sequence_file, digital=True, alphabet=protein_alphabet) as target_seqs_reader: + target_sequences = target_seqs_reader.read_block() + + # Construct pyhmmer.phmmer arguments + search_kwargs = { + "cpus": cpus, + "bias_filter": bias_filter, + } + if e_value_cutoff is not None: + search_kwargs["E"] = e_value_cutoff + if bit_score_cutoff is not None: + search_kwargs["T"] = bit_score_cutoff + if max_target_seqs is not None: + search_kwargs["max_target_seqs"] = max_target_seqs + + # Execute phmmer and collect results (pyhmmer.phmmer returns a generator) + all_hits = list(pyhmmer.phmmer(query_sequences, target_sequences, **search_kwargs)) + + # Write results to output files + _write_hits_to_tblout(all_hits, output_tblout) + output_files.append(output_tblout) + + _write_hits_to_domtblout(all_hits, output_domtblout) + output_files.append(output_domtblout) + + except Exception as e: + stderr_buffer.append(f"Error during pyhmmer.phmmer execution: {e}") + # Clean up temporary files if an error occurred + if temp_output_tblout and output_tblout.exists(): + output_tblout.unlink() + if temp_output_domtblout and output_domtblout.exists(): + output_domtblout.unlink() + return { + "command_executed": f"pyhmmer.phmmer(query_sequences={query_sequence_file.name}, target_sequences={target_sequence_file.name}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": [], + } + + return { + "command_executed": f"pyhmmer.phmmer(query_sequences={query_sequence_file.name}, target_sequences={target_sequence_file.name}, cpus={cpus}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": output_files, + } + +@mcp.tool() +def hmmbuild( + alignment_file: Path, + output_hmm_file: Path, + alphabet_type: Literal["amino", "dna", "rna"], + name: Optional[str] = None, + accession: Optional[str] = None, + hand_model: bool = True, # Corresponds to HMMER's default 'hand' model construction + symfrac: float = 0.5, + fragsc: float = 0.0, + fast: bool = False, +) -> Dict[str, Any]: + """ + Builds a profile HMM from a multiple sequence alignment using pyhmmer.hmmbuild. + + This function wraps the pyhmmer.hmmbuild API, which provides Python bindings + to HMMER3's hmmbuild functionality. + + Args: + alignment_file: Path to the multiple sequence alignment file (e.g., Stockholm, FASTA, Clustal). + output_hmm_file: Path to write the output HMM file. + alphabet_type: The type of alphabet for the sequences in the alignment ("amino", "dna", or "rna"). + name: Optional name for the HMM. + accession: Optional accession for the HMM. + hand_model: If True, use the 'hand' model construction algorithm (default). If False, use 'wbl' (WBL model). + Note: pyhmmer.hmmbuild takes `builder` argument, which defaults to `pyhmmer.plan7.HMM.hand()`. + For simplicity, this parameter exposes a boolean for the common 'hand' vs 'wbl' choice. + symfrac: Minimum fraction of residues required to be non-gap in a column for it to be considered a match state. + (0.0 to 1.0, default 0.5). + fragsc: Fragment score. (default 0.0). + fast: Use a faster, less accurate algorithm for model construction. + + Returns: + A dictionary containing: + - "command_executed": A string representing the pyhmmer API call. + - "stdout": Standard output (empty for pyhmmer API calls unless explicitly captured). + - "stderr": Standard error (empty for pyhmmer API calls unless explicitly captured). + - "output_files": A list of paths to generated output files (e.g., the HMM file). + """ + # Input validation + if not alignment_file.is_file(): + raise FileNotFoundError(f"Alignment file not found: {alignment_file}") + if not (0.0 <= symfrac <= 1.0): + raise ValueError("symfrac must be between 0.0 and 1.0.") + + output_files: List[Path] = [] + stdout_buffer = [] + stderr_buffer = [] + + try: + # Determine alphabet + if alphabet_type == "amino": + alphabet = pyhmmer.easel.Alphabet.amino() + elif alphabet_type == "dna": + alphabet = pyhmmer.easel.Alphabet.dna() + elif alphabet_type == "rna": + alphabet = pyhmmer.easel.Alphabet.rna() + else: + raise ValueError(f"Invalid alphabet type: {alphabet_type}") + + # Load alignment + with pyhmmer.easel.AlignmentFile(alignment_file, alphabet=alphabet) as alignment_reader: + alignment = alignment_reader.read() + + # Construct HMM builder + builder = pyhmmer.plan7.HMM.hand() if hand_model else pyhmmer.plan7.HMM.wbl() + + # Construct pyhmmer.hmmbuild arguments + build_kwargs = { + "builder": builder, + "symfrac": symfrac, + "fragsc": fragsc, + "fast": fast, + } + if name: + build_kwargs["name"] = name.encode() # pyhmmer expects bytes + if accession: + build_kwargs["accession"] = accession.encode() # pyhmmer expects bytes + + # Execute hmmbuild + hmm = pyhmmer.hmmbuild(alignment, **build_kwargs) + + # Write HMM to file + with open(output_hmm_file, "wb") as f: + hmm.write(f) + output_files.append(output_hmm_file) + + except Exception as e: + stderr_buffer.append(f"Error during pyhmmer.hmmbuild execution: {e}") + if output_hmm_file.exists(): + output_hmm_file.unlink() + return { + "command_executed": f"pyhmmer.hmmbuild(alignment={alignment_file.name}, alphabet_type='{alphabet_type}', ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": [], + } + + return { + "command_executed": f"pyhmmer.hmmbuild(alignment={alignment_file.name}, alphabet_type='{alphabet_type}', name='{name or 'N/A'}', ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": output_files, + } + +@mcp.tool() +def hmmalign( + hmm_file: Path, + sequence_file: Path, + output_alignment_file: Path, + alphabet_type: Literal["amino", "dna", "rna"], + output_format: Literal["stockholm", "fasta", "clustal", "a2m"] = "stockholm", + cpus: int = 1, +) -> Dict[str, Any]: + """ + Aligns sequences to a profile HMM using pyhmmer.hmmalign. + + This function wraps the pyhmmer.hmmalign API, which provides Python bindings + to HMMER3's hmmalign functionality. + + Args: + hmm_file: Path to the profile HMM file. + sequence_file: Path to the sequences to align (e.g., FASTA format). + output_alignment_file: Path to write the output multiple sequence alignment file. + alphabet_type: The type of alphabet for the sequences and HMM ("amino", "dna", or "rna"). + output_format: Format for the output alignment ("stockholm", "fasta", "clustal", or "a2m"). + cpus: Number of CPU threads to use for parallel processing. Must be a positive integer. + + Returns: + A dictionary containing: + - "command_executed": A string representing the pyhmmer API call. + - "stdout": Standard output (empty for pyhmmer API calls unless explicitly captured). + - "stderr": Standard error (empty for pyhmmer API calls unless explicitly captured). + - "output_files": A list of paths to generated output files (e.g., the alignment file). + """ + # Input validation + if not hmm_file.is_file(): + raise FileNotFoundError(f"HMM file not found: {hmm_file}") + if not sequence_file.is_file(): + raise FileNotFoundError(f"Sequence file not found: {sequence_file}") + if cpus < 1: + raise ValueError("Number of CPUs must be a positive integer.") + if output_format not in ["stockholm", "fasta", "clustal", "a2m"]: + raise ValueError(f"Invalid output format: {output_format}. Must be one of 'stockholm', 'fasta', 'clustal', 'a2m'.") + + output_files: List[Path] = [] + stdout_buffer = [] + stderr_buffer = [] + + try: + # Determine alphabet + if alphabet_type == "amino": + alphabet = pyhmmer.easel.Alphabet.amino() + elif alphabet_type == "dna": + alphabet = pyhmmer.easel.Alphabet.dna() + elif alphabet_type == "rna": + alphabet = pyhmmer.easel.Alphabet.rna() + else: + raise ValueError(f"Invalid alphabet type: {alphabet_type}") + + # Load HMM (hmmalign expects a single HMM) + with pyhmmer.plan7.HMMFile(hmm_file) as hmm_reader: + hmm = hmm_reader.read() + + # Load sequences + with pyhmmer.easel.SequenceFile(sequence_file, digital=True, alphabet=alphabet) as seqs_reader: + sequences = seqs_reader.read_block() + + # Execute hmmalign + alignment = pyhmmer.hmmalign(hmm, sequences, cpus=cpus) + + # Write alignment to file + _write_alignment_to_file(alignment, output_alignment_file, output_format) + output_files.append(output_alignment_file) + + except Exception as e: + stderr_buffer.append(f"Error during pyhmmer.hmmalign execution: {e}") + if output_alignment_file.exists(): + output_alignment_file.unlink() + return { + "command_executed": f"pyhmmer.hmmalign(hmm={hmm_file.name}, sequences={sequence_file.name}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": [], + } + + return { + "command_executed": f"pyhmmer.hmmalign(hmm={hmm_file.name}, sequences={sequence_file.name}, cpus={cpus}, ...)", + "stdout": "\n".join(stdout_buffer), + "stderr": "\n".join(stderr_buffer), + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/pyhmmer_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/pyhmmer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb58775a8c2131d7b1acaeaccb232f1fcb57011 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/pyhmmer_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_pyhmmer/app/pyhmmer_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_pyhmmer' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f380eeefe98e7ee5cedaa02ab7925e0042d17a28 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/app/requirements.txt @@ -0,0 +1 @@ +pyhmmer==0.12.0 diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a5c383474f9b7ae4ddef5a395114f2e691db2980 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-pyhmmer: + build: . + image: mcp-pyhmmer:latest + container_name: mcp-pyhmmer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=pyhmmer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f9aca9bdb48120a18fc8569c01d892235212bed2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - pyhmmer + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d1de2c99250251e1750b7ddd161435e73286276a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyhmmer/requirements.txt @@ -0,0 +1,3 @@ +pyhmmer==0.12.0 +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyrovelocity/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyrovelocity/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyrovelocity/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..84ec1f58046acf94bace5189a02b902333c0eec2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install qcatch via conda (e.g., from bioconda) +RUN conda install -c bioconda qcatch -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/qcatch_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/qcatch_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/qcatch_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/__pycache__/qcatch_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/__pycache__/qcatch_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c32a51adac27c896b3d81a6101a48e2bdc3978a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/__pycache__/qcatch_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/qcatch_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/qcatch_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb78f89791f5de952ba9e71a0be60770c603a3b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/qcatch_server.py @@ -0,0 +1,153 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_qcatch' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def qcatch( + input_path: str, + output_path: str, + chemistry: Optional[str] = None, + save_filtered_h5ad: bool = False, + gene_id2name_file: Optional[str] = None, + valid_cell_list: Optional[str] = None, + n_partitions: Optional[int] = None, + remove_doublets: bool = False, + visualize_doublets: bool = False, + skip_umap_tsne: bool = False, + export_summary_table: bool = False, + verbose: bool = False, +) -> Dict[str, Any]: + """ + QCatch: Automated quality control of single-cell quantifications from alevin-fry and simpleaf. + + Generates an interactive HTML report and optionally filtered H5AD files. + + Args: + input_path: Path to the input directory containing quantification output files or to the H5AD file itself. + output_path: Path to the output directory where results and reports will be saved. + chemistry: Specifies the chemistry used (e.g., '10X_3p_v2', '10X_3p_v3', '10X_3p_v4', '10X_5p_v3', '10X_3p_LT', '10X_HT'). + save_filtered_h5ad: If enabled, saves a separate .h5ad file containing only the final retained cells. + gene_id2name_file: Path to a TSV file (no header) mapping gene IDs to gene names (columns: gene_id, gene_name). + valid_cell_list: Path to a TSV file (no header) containing a user-specified list of valid cell barcodes. + n_partitions: Number of partitions (max barcodes for ambient estimation). Overrides chemistry-based settings. + remove_doublets: Perform doublet detection using Scrublet and remove detected doublets. + visualize_doublets: Generates additional UMAP/t-SNE plots showing doublets (requires remove_doublets=True). + skip_umap_tsne: Skips generation of UMAP and t-SNE plots to reduce runtime. + export_summary_table: Exports summary metrics as a separate CSV file. + verbose: Enable verbose logging with debug-level messages. + """ + # Input validation + input_p = Path(input_path) + if not input_p.exists(): + return {"error": f"Input path '{input_path}' does not exist."} + + output_p = Path(output_path) + output_p.mkdir(parents=True, exist_ok=True) + + # Logic validation + if visualize_doublets and not remove_doublets: + return {"error": "The 'visualize_doublets' option requires 'remove_doublets' to be enabled."} + + supported_chemistries = ['10X_3p_v2', '10X_3p_v3', '10X_3p_v4', '10X_5p_v3', '10X_3p_LT', '10X_HT'] + if chemistry and chemistry not in supported_chemistries: + return {"error": f"Unsupported chemistry '{chemistry}'. Supported: {supported_chemistries}"} + + # Build command + cmd = ["qcatch", "--input", str(input_p), "--output", str(output_p)] + + if chemistry: + cmd.extend(["--chemistry", chemistry]) + + if save_filtered_h5ad: + cmd.append("--save_filtered_h5ad") + + if gene_id2name_file: + g_path = Path(gene_id2name_file) + if not g_path.exists(): + return {"error": f"Gene mapping file '{gene_id2name_file}' not found."} + cmd.extend(["--gene_id2name_file", str(g_path)]) + + if valid_cell_list: + l_path = Path(valid_cell_list) + if not l_path.exists(): + return {"error": f"Valid cell list file '{valid_cell_list}' not found."} + cmd.extend(["--valid_cell_list", str(l_path)]) + + if n_partitions is not None: + if n_partitions <= 0: + return {"error": "n_partitions must be a positive integer."} + cmd.extend(["--n_partitions", str(n_partitions)]) + + if remove_doublets: + cmd.append("--remove_doublets") + + if visualize_doublets: + cmd.append("--visualize_doublets") + + if skip_umap_tsne: + cmd.append("--skip_umap_tsne") + + if export_summary_table: + cmd.append("--export_summary_table") + + if verbose: + cmd.append("--verbose") + + try: + # Execute the tool + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Identify output files + output_files = [str(f) for f in output_p.iterdir() if f.is_file()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"QCatch failed with exit code {e.returncode}", + "status": "error" + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "status": "error" + } + +@mcp.tool() +def qcatch_version() -> Dict[str, Any]: + """ + Display the installed version of QCatch. + """ + try: + result = subprocess.run(["qcatch", "--version"], capture_output=True, text=True, check=True) + return { + "command_executed": "qcatch --version", + "stdout": result.stdout.strip(), + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "qcatch --version", + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Failed to retrieve version. Exit code {e.returncode}", + "status": "error" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/qcatch_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/qcatch_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c0464052d096c11efc3fb74c8ae3954bd9b0d26a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/qcatch_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_qcatch/app/qcatch_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_qcatch' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6503674171a9be45e4363e70ead705e876ec2605 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-qcatch: + build: . + image: mcp-qcatch:latest + container_name: mcp-qcatch + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=qcatch + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..383351de9db63634963e3f491b5b184d0a884f0b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - qcatch + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_qcatch/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b24e20969686bf6653c61f2079f112bb8dc9cba7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-basejump via conda (e.g., from bioconda) +RUN conda install -c bioconda r-basejump -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/r-basejump_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-basejump_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-basejump_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/__pycache__/r-basejump_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/__pycache__/r-basejump_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3227fdf9248f2b32608fe25c720d6e10ca5e089a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/__pycache__/r-basejump_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/r-basejump_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/r-basejump_server.py new file mode 100644 index 0000000000000000000000000000000000000000..05d88012c24a95308f68fcf5cfc8bf7791fdf1e6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/r-basejump_server.py @@ -0,0 +1,126 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_r_basejump' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_r_script( + r_script_path: Path, + r_arguments: Optional[List[str]] = None, + output_dir: Optional[Path] = None, + r_executable: str = "Rscript", +) -> Dict[str, Any]: + """ + Executes a user-provided R script, enabling interaction with R packages like 'r-basejump'. + + The 'r-basejump' tool is an R package, meaning its functionalities are typically + accessed by calling R functions within an R environment or an R script. The + provided documentation does not specify any direct command-line subcommands + or executables for 'r-basejump'. + + This MCP tool provides a generic interface to run any R script. Users can write + an R script that imports and uses functions from 'r-basejump' (assuming the + package is installed in the R environment accessible by `r_executable`). + + Args: + r_script_path: Path to the R script file to be executed. This script should + contain the R code, including calls to 'r-basejump' functions + if desired. + r_arguments: Optional list of string arguments to pass to the R script. + These arguments will be accessible within the R script via + `commandArgs(trailingOnly = TRUE)`. + output_dir: Optional directory where the R script should write its output files. + If not provided, a temporary directory will be created and used + as the working directory for the R script execution. Any files + created in this directory will be reported. The R script itself + must be designed to write its outputs to the current working directory + or a path relative to it. + r_executable: The R interpreter executable to use (e.g., 'Rscript', 'R'). + Defaults to 'Rscript', which is commonly used for non-interactive + R script execution. + + Returns: + A dictionary containing the command executed, standard output, standard error, + and a list of any output files generated in the specified (or temporary) + output directory. + + Raises: + ValueError: If the provided R script file does not exist. + """ + # Input validation + if not r_script_path.is_file(): + raise ValueError(f"R script file not found: {r_script_path}") + + # Prepare the output directory + temp_dir_obj: Optional[tempfile.TemporaryDirectory] = None + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + final_output_dir = output_dir + else: + temp_dir_obj = tempfile.TemporaryDirectory() + final_output_dir = Path(temp_dir_obj.name) + + command = [r_executable, str(r_script_path)] + if r_arguments: + command.extend(r_arguments) + + stdout_data = "" + stderr_data = "" + output_files: List[str] = [] + error_message: Optional[str] = None + + try: + # Execute the R script, setting the working directory to the output directory + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=final_output_dir, + env={"R_LIBS_USER": str(final_output_dir)} # Suggest R to look for libs here, though typically R_LIBS is set by env + ) + stdout_data = process.stdout + stderr_data = process.stderr + + # Collect any files created in the output directory + for f in final_output_dir.iterdir(): + if f.is_file(): + output_files.append(str(f)) + + except FileNotFoundError: + stderr_data = ( + f"Error: R executable '{r_executable}' not found. " + "Please ensure R is installed and accessible in your system's PATH." + ) + error_message = "R_EXECUTABLE_NOT_FOUND" + except subprocess.CalledProcessError as e: + stdout_data = e.stdout + stderr_data = e.stderr + error_message = f"R script execution failed with exit code {e.returncode}" + except Exception as e: + stderr_data = f"An unexpected error occurred: {e}" + error_message = "UNEXPECTED_ERROR" + finally: + # Clean up the temporary directory if it was created and no error occurred + # that prevented file collection (or if files were moved out). + # If an error occurred, the temporary directory might be useful for debugging. + if temp_dir_obj and not error_message: + temp_dir_obj.cleanup() + + result: Dict[str, Any] = { + "command_executed": " ".join(command), + "stdout": stdout_data, + "stderr": stderr_data, + "output_files": output_files, + } + if error_message: + result["error"] = error_message + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/r-basejump_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/r-basejump_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..761af976ff4db6ca573bebae03b7073f292d9a78 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/r-basejump_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_r-basejump/app/r-basejump_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_basejump' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d35b83975720342c87d2d330c76e63e7ede29f01 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-basejump: + build: . + image: mcp-r-basejump:latest + container_name: mcp-r-basejump + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-basejump + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..80ae3f187cbb2f4cc5f594dae259d0e33e2e96ff --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-basejump + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-basejump/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1e6058c7194b4d1ae80eba7c56f67638ea04448b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-flanders via conda (e.g., from bioconda) +RUN conda install -c bioconda r-flanders -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/r-flanders_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-flanders_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-flanders_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/__pycache__/r-flanders_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/__pycache__/r-flanders_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f58432a6dc35278c0c13e5c20e04c281ca2716f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/__pycache__/r-flanders_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/r-flanders_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/r-flanders_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18416b02c1217fde92f4d9b8eb298f34bfb33b85 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/r-flanders_server.py @@ -0,0 +1,281 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Helper function to run R scripts +def _run_r_script(r_script_content: str, output_files: Optional[List[Path]] = None) -> Dict[str, Any]: + """ + Executes an R script and captures its output. + + Args: + r_script_content: The R script code as a string. + output_files: An optional list of expected output file paths to check for existence. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + + final_output_files = [] + if output_files: + for f in output_files: + if f.exists(): + final_output_files.append(str(f)) + else: + # If an expected output file is missing, it indicates a potential issue + # but we don't want to fail the entire tool if R didn't explicitly error. + # This could be logged or handled based on specific tool requirements. + pass + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [], + } + finally: + # Clean up the temporary R script + if temp_r_script_path.exists(): + temp_r_script_path.unlink() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_r_flanders' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def finemap2anndata( + finemap_files: List[Path], + phenotype_ids: List[str], + study_ids: List[str], + output_anndata_path: Path, +) -> Dict[str, Any]: + """ + Converts a set of finemapping .rds files into a single AnnData object with credible set metadata. + + This function takes multiple finemapping output .rds files, along with corresponding + phenotype and study IDs, and merges them into a unified AnnData object. The resulting + AnnData object can then be used for downstream colocalization analysis. + + Args: + finemap_files: A list of paths to finemapping .rds files. Each file should be an + output from a finemapping pipeline (e.g., nf-flanders). + phenotype_ids: A list of phenotype identifiers, where each element corresponds + to a file in `finemap_files`. The length of this list must match + `finemap_files`. + study_ids: A list of study identifiers, where each element corresponds to a file + in `finemap_files`. The length of this list must match `finemap_files`. + output_anndata_path: The desired path to write the resulting AnnData object + in H5AD format (.h5ad extension is required). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of + generated output files. + + Raises: + ValueError: If input validation fails (e.g., empty file list, mismatched lengths, + incorrect file extensions, or non-existent files). + """ + # Input validation + if not finemap_files: + raise ValueError("finemap_files cannot be empty.") + for f in finemap_files: + if not f.is_file(): + raise ValueError(f"Finemap file '{f}' does not exist.") + if f.suffix != ".rds": + raise ValueError(f"Finemap file '{f}' must have a .rds extension.") + + if not (len(finemap_files) == len(phenotype_ids) == len(study_ids)): + raise ValueError( + "finemap_files, phenotype_ids, and study_ids must have the same length. " + f"Lengths: {len(finemap_files)}, {len(phenotype_ids)}, {len(study_ids)}" + ) + if output_anndata_path.suffix != ".h5ad": + raise ValueError(f"output_anndata_path '{output_anndata_path}' must have a .h5ad extension.") + + # Prepare R vectors from Python lists + r_finemap_files = 'c(' + ', '.join([f'"{str(f)}"' for f in finemap_files]) + ')' + r_phenotype_ids = 'c(' + ', '.join([f'"{pid}"' for pid in phenotype_ids]) + ')' + r_study_ids = 'c(' + ', '.join([f'"{sid}"' for sid in study_ids]) + ')' + + r_script = f""" + library(flanders) + library(data.table) # Dependency for flanders, often used for data manipulation + library(dplyr) # Dependency for flanders, often used for data manipulation + library(anndata) # Required for writing AnnData objects to h5ad + + finemap_files <- {r_finemap_files} + phenotype_id <- {r_phenotype_ids} + study_id <- {r_study_ids} + + # Ensure the output directory exists + output_dir <- dirname("{str(output_anndata_path)}") + if (!dir.exists(output_dir)) {{ + dir.create(output_dir, recursive = TRUE) + }} + + ad <- finemap2anndata( + finemap_files = finemap_files, + phenotype_id = phenotype_id, + study_id = study_id + ) + + # Write the AnnData object to disk + ad$write_h5ad("{str(output_anndata_path)}") + """ + + return _run_r_script(r_script, output_files=[output_anndata_path]) + + +@mcp.tool() +def anndata2coloc_input( + input_anndata_path: Path, + output_coloc_input_path: Path, +) -> Dict[str, Any]: + """ + Generates a data frame specifying pairs of credible sets for colocalization tests. + + This function takes an existing AnnData object (typically generated by `finemap2anndata`) + and processes it to create an input table suitable for colocalization testing. This + table defines the pairs of credible sets that will be tested for colocalization. + + Args: + input_anndata_path: Path to an existing AnnData object (.h5ad) containing + credible set metadata. + output_coloc_input_path: The desired path to write the resulting colocalization + input table in CSV format (.csv extension is required). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of + generated output files. + + Raises: + ValueError: If input validation fails (e.g., non-existent input file, + incorrect file extensions). + """ + # Input validation + if not input_anndata_path.is_file(): + raise ValueError(f"Input AnnData file '{input_anndata_path}' does not exist.") + if input_anndata_path.suffix != ".h5ad": + raise ValueError(f"input_anndata_path '{input_anndata_path}' must be an .h5ad file.") + if output_coloc_input_path.suffix != ".csv": + raise ValueError(f"output_coloc_input_path '{output_coloc_input_path}' must have a .csv extension.") + + r_script = f""" + library(zellkonverter) + library(SingleCellExperiment) + library(scRNAseq) # Often loaded in contexts using zellkonverter/SingleCellExperiment + library(flanders) + library(data.table) # Required for fwrite + + # Ensure the output directory exists + output_dir <- dirname("{str(output_coloc_input_path)}") + if (!dir.exists(output_dir)) {{ + dir.create(output_dir, recursive = TRUE) + }} + + sce <- readH5AD("{str(input_anndata_path)}", reader = "R") + coloc_input <- anndata2coloc_input(sce) + fwrite(coloc_input, file = "{str(output_coloc_input_path)}") + """ + + return _run_r_script(r_script, output_files=[output_coloc_input_path]) + + +@mcp.tool() +def anndata2coloc( + input_anndata_path: Path, + input_coloc_input_path: Path, + output_coloc_results_path: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs colocalization tests using the provided AnnData object and trait-pair table. + + This function executes pairwise colocalization tests based on an AnnData object + (containing finemapping results) and a pre-generated colocalization input table. + The results can either be printed to standard output or saved to a specified CSV file. + + Args: + input_anndata_path: Path to an existing AnnData object (.h5ad) containing + credible set metadata. + input_coloc_input_path: Path to the colocalization input table (.csv) + generated by `anndata2coloc_input`. This table specifies + which credible set pairs to test. + output_coloc_results_path: Optional path to write the colocalization results + table in CSV format (.csv extension is required if provided). + If not provided, the results will be printed to stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of + generated output files. + + Raises: + ValueError: If input validation fails (e.g., non-existent input files, + incorrect file extensions). + """ + # Input validation + if not input_anndata_path.is_file(): + raise ValueError(f"Input AnnData file '{input_anndata_path}' does not exist.") + if input_anndata_path.suffix != ".h5ad": + raise ValueError(f"input_anndata_path '{input_anndata_path}' must be an .h5ad file.") + + if not input_coloc_input_path.is_file(): + raise ValueError(f"Input colocalization input file '{input_coloc_input_path}' does not exist.") + if input_coloc_input_path.suffix != ".csv": + raise ValueError(f"input_coloc_input_path '{input_coloc_input_path}' must be a .csv file.") + + if output_coloc_results_path and output_coloc_results_path.suffix != ".csv": + raise ValueError(f"output_coloc_results_path '{output_coloc_results_path}' must have a .csv extension if provided.") + + r_script_lines = [ + "library(zellkonverter)", + "library(SingleCellExperiment)", + "library(scRNAseq)", # Often loaded in contexts using zellkonverter/SingleCellExperiment + "library(flanders)", + "library(data.table)", # Required for fread and fwrite + "", + f'sce <- readH5AD("{str(input_anndata_path)}", reader = "R")', + f'coloc_input <- fread("{str(input_coloc_input_path)}")', + "coloc_results <- anndata2coloc(sce, coloc_input)", + ] + + output_files_to_check = [] + if output_coloc_results_path: + # Ensure the output directory exists + r_script_lines.append(f'output_dir <- dirname("{str(output_coloc_results_path)}")') + r_script_lines.append('if (!dir.exists(output_dir)) { dir.create(output_dir, recursive = TRUE) }') + r_script_lines.append(f'fwrite(coloc_results, file = "{str(output_coloc_results_path)}")') + output_files_to_check.append(output_coloc_results_path) + else: + r_script_lines.append("print(coloc_results)") + + r_script = "\n".join(r_script_lines) + + return _run_r_script(r_script, output_files=output_files_to_check) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/r-flanders_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/r-flanders_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3073fbda100bcb6d192b478eeca790b0446aaf34 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/r-flanders_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_r-flanders/app/r-flanders_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_flanders' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a175064158b5acf2bdc30af56b54ae776471343d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-flanders: + build: . + image: mcp-r-flanders:latest + container_name: mcp-r-flanders + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-flanders + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b27db9c59039267ea0618da7f321cde3f19d266 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-flanders + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-flanders/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6978c0fced048acb8a49efa97ed9ff1a8f0858e3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-mams via conda (e.g., from bioconda) +RUN conda install -c bioconda r-mams -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/r-mams_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-mams_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-mams_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/__pycache__/r-mams_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/__pycache__/r-mams_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82ead6904f87ecd51d4a9b1fa9ea7322fbd9eeb7 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/__pycache__/r-mams_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/r-mams_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/r-mams_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f2d9932e3217b0a5276e2f788a5a7294f65b7919 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/r-mams_server.py @@ -0,0 +1,144 @@ +import subprocess +from pathlib import Path +from typing import Optional, List +import os + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def r_mams( + input_file: Path, + output_dir: Path, + param_file: Optional[Path] = None, + ppm: float = 5.0, + rt_tol: float = 30.0, + min_peak_height: float = 1000.0, + min_peak_width: float = 5.0, + max_peak_width: float = 60.0, + sn_thresh: float = 10.0, + prefilter_intensity: float = 100.0, + noise_intensity: float = 100.0, + threads: int = 1, + verbose: bool = False, +) -> dict: + """ + Executes the r-mams tool for metabolomics data processing. + + This tool performs peak picking and feature detection on mass spectrometry data. + It requires an input file with at least 'mz' and 'rt' columns and generates + output files in the specified directory. + + Args: + input_file: Path to the input file. A tab-separated file with at least 'mz' and 'rt' columns. + output_dir: Path to the output directory where results will be stored. + param_file: Optional path to a JSON file with MAMS parameters. + ppm: Mass tolerance in parts-per-million (ppm). Must be positive. + rt_tol: Retention time tolerance in seconds. Must be non-negative. + min_peak_height: Minimum peak height. Must be non-negative. + min_peak_width: Minimum peak width in seconds. Must be positive. + max_peak_width: Maximum peak width in seconds. Must be greater than min_peak_width. + sn_thresh: Signal-to-noise ratio threshold. Must be non-negative. + prefilter_intensity: Prefilter intensity threshold. Must be non-negative. + noise_intensity: Noise intensity threshold. Must be non-negative. + threads: Number of threads to use for processing. Must be at least 1. + verbose: Enable verbose output. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if param_file and not param_file.is_file(): + raise FileNotFoundError(f"Parameter file not found: {param_file}") + + if ppm <= 0: + raise ValueError("ppm must be a positive number.") + if rt_tol < 0: + raise ValueError("rt_tol cannot be negative.") + if min_peak_height < 0: + raise ValueError("min_peak_height cannot be negative.") + if min_peak_width <= 0: + raise ValueError("min_peak_width must be a positive number.") + if max_peak_width <= min_peak_width: + raise ValueError("max_peak_width must be greater than min_peak_width.") + if sn_thresh < 0: + raise ValueError("sn_thresh cannot be negative.") + if prefilter_intensity < 0: + raise ValueError("prefilter_intensity cannot be negative.") + if noise_intensity < 0: + raise ValueError("noise_intensity cannot be negative.") + if threads < 1: + raise ValueError("threads must be at least 1.") + + # --- File Path Handling --- + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Could not create output directory {output_dir}: {e}") + + # --- Command Construction --- + cmd = [ + "r-mams", + "--input_file", str(input_file), + "--output_dir", str(output_dir), + "--ppm", str(ppm), + "--rt_tol", str(rt_tol), + "--min_peak_height", str(min_peak_height), + "--min_peak_width", str(min_peak_width), + "--max_peak_width", str(max_peak_width), + "--sn_thresh", str(sn_thresh), + "--prefilter_intensity", str(prefilter_intensity), + "--noise_intensity", str(noise_intensity), + "--threads", str(threads), + ] + + if param_file: + cmd.extend(["--param_file", str(param_file)]) + + if verbose: + cmd.append("--verbose") + + command_executed = " ".join(cmd) + + # --- Subprocess Execution & Error Handling --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + raise RuntimeError("r-mams executable not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + # In case of an error, return a structured error message + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"r-mams failed with exit code {e.returncode}", + "output_files": [] + } + + # --- Structured Result Return --- + try: + output_files = [str(f) for f in output_dir.glob("**/*") if f.is_file()] + except Exception as e: + output_files = [] + stderr += f"\nWarning: Could not list output files in {output_dir}. Error: {e}" + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/r-mams_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/r-mams_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..03a5227f97bae3b87a948c872c0af6bb3ff97232 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/r-mams_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_r-mams/app/r-mams_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_mams' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0215d12b56a637868ef49a1c1e760504cdb80050 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-mams: + build: . + image: mcp-r-mams:latest + container_name: mcp-r-mams + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-mams + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ee49bff10b0e03fc56f62fe58b6c7f5f1d0b89a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-mams + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-mams/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3c1f7338c4e8de5ce0eb67cbeb826d86db0d78db --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-redeemr via conda (e.g., from bioconda) +RUN conda install -c bioconda r-redeemr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/r-redeemr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-redeemr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-redeemr_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/__pycache__/r-redeemr_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/__pycache__/r-redeemr_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e18075aa64ce2b90d73138db255bf5deef42812e Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/__pycache__/r-redeemr_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/r-redeemr_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/r-redeemr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..14bbf735219bc9ad10f1bd1fd8b1415623344fe1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/r-redeemr_server.py @@ -0,0 +1,145 @@ +import subprocess +import tempfile +import shlex +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Assuming mcp is available in the environment as per the instructions. +# from mcp import tool as mcp.tool + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_r_redeemr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def redeemr( + genome: Path, + species: str, + output_dir: Optional[Path] = None, + nproc: int = 1, + repeatmasker_dir: Optional[Path] = None, + repeatmodeler_dir: Optional[Path] = None, + trf_dir: Optional[Path] = None, + rmblast_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Runs the redeemr pipeline for REpeats DE-novo Estimation and Masking in R. + + This tool serves as a wrapper for the `redeemr::redeem()` R function, which + automates the process of de-novo repeat identification and masking using + RepeatModeler and RepeatMasker. + + Args: + genome: Path to the input genome file in FASTA format. + species: The species name to be used by RepeatMasker (e.g., "homo_sapiens"). + output_dir: Directory to save the output files. If not provided, a temporary directory will be created. + nproc: Number of processors to use for the analysis. + repeatmasker_dir: Optional path to the RepeatMasker installation directory. + repeatmodeler_dir: Optional path to the RepeatModeler installation directory. + trf_dir: Optional path to the Tandem Repeats Finder (TRF) installation directory. + rmblast_dir: Optional path to the RMBlast (a modified version of NCBI BLAST) installation directory. + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and paths to the output directory and files. + """ + # 1. Input Validation + if not genome.is_file(): + raise FileNotFoundError(f"Input genome file not found at: {genome}") + if not species.strip(): + raise ValueError("Species name cannot be empty.") + if nproc <= 0: + raise ValueError(f"Number of processors (nproc) must be a positive integer, but got {nproc}.") + + for optional_path in [repeatmasker_dir, repeatmodeler_dir, trf_dir, rmblast_dir]: + if optional_path and not optional_path.is_dir(): + raise NotADirectoryError(f"Provided path is not a valid directory: {optional_path}") + + # 2. Output Directory Handling + # If an output directory is not specified, create a temporary one. + # This is a safe practice for server environments. + temp_dir_obj = None + if output_dir: + final_output_dir = output_dir + else: + temp_dir_obj = tempfile.TemporaryDirectory(prefix="redeemr_output_") + final_output_dir = Path(temp_dir_obj.name) + + final_output_dir.mkdir(parents=True, exist_ok=True) + + # 3. R Script Generation + # Building an R script dynamically is safer than complex command-line strings. + r_args = [ + f'genome = "{genome.resolve()}"', + f'species = "{species}"', + f'outputDir = "{final_output_dir.resolve()}"', + f'nproc = {nproc}' + ] + + def format_r_path(name: str, path: Optional[Path]) -> str: + """Helper to format optional paths for the R script (path or NULL).""" + if path: + return f'{name} = "{path.resolve()}"' + return f'{name} = NULL' + + r_args.append(format_r_path('RepeatMasker_dir', repeatmasker_dir)) + r_args.append(format_r_path('RepeatModeler_dir', repeatmodeler_dir)) + r_args.append(format_r_path('TRF_dir', trf_dir)) + r_args.append(format_r_path('RMBlast_dir', rmblast_dir)) + + r_code = f"library(redeemr)\nredeemr::redeem({', '.join(r_args)})" + + # 4. Subprocess Execution + script_file = None + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=final_output_dir) as fp: + script_file = Path(fp.name) + fp.write(r_code) + + cmd = ["Rscript", str(script_file)] + command_executed = " ".join(shlex.quote(c) for c in cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=final_output_dir # Execute from the output directory + ) + + # 5. Collect Output Files + output_files = [str(p) for p in final_output_dir.rglob('*') if p.is_file()] + + return { + "command_executed": command_executed, + "r_script_content": r_code, + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(final_output_dir), + "output_files": output_files + } + + except FileNotFoundError: + raise RuntimeError("`Rscript` command not found. Please ensure R is installed and in the system's PATH.") + except subprocess.CalledProcessError as e: + # Structured error return + return { + "command_executed": command_executed, + "r_script_content": r_code, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "r-redeemr execution failed with a non-zero exit code.", + "return_code": e.returncode + } + finally: + # Cleanup the temporary R script + if script_file and script_file.exists(): + script_file.unlink() + # Cleanup the temporary directory object if it was created + if temp_dir_obj: + temp_dir_obj.cleanup() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/r-redeemr_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/r-redeemr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd50945780f19f25a781c9030ec556174986676 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/r-redeemr_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_r-redeemr/app/r-redeemr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_redeemr' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..da7308bfd1fd8ecef5ac7487ca4610a6351c8ec5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-redeemr: + build: . + image: mcp-r-redeemr:latest + container_name: mcp-r-redeemr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-redeemr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3797808281b0dabf1ec3fff525d74d1a722cbe01 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-redeemr + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-redeemr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_racon/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_racon/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_racon/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_recognizer/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_recognizer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_recognizer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e940b3ea9cbe7abf8e2d595fd0802b3001474012 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install rnftools via conda (e.g., from bioconda) +RUN conda install -c bioconda rnftools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/rnftools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/rnftools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/rnftools_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/__pycache__/rnftools_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/__pycache__/rnftools_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79298897e03f8b6dce39a230804b2bb54a537b29 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/__pycache__/rnftools_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/rnftools_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/rnftools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a7044d050bd9a13f8dc12ee09a9e06592dfc3229 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/rnftools_server.py @@ -0,0 +1,162 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Note: 'mcp' is not imported as per instructions. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_rnftools' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def rnftools_run_generic( + command_args: List[str], + working_dir: Optional[Path] = None, + log_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes a generic rnftools command. + + This function serves as a placeholder because the specific subcommands and + their parameters for rnftools could not be extracted from the provided + documentation. To create a fully functional MCP tool, detailed command-line + help output (e.g., `rnftools --help`) is required to identify all + subcommands, their arguments, types, and default values. + + Args: + command_args: A list of strings representing the rnftools subcommand + and its arguments. For example: ["simulate", "--genome", "ref.fa"]. + This parameter is required to specify what rnftools should do. + working_dir: Optional path to the directory where the command should be executed. + If None, the current working directory is used. + log_file: Optional path to a file where stdout and stderr will be redirected. + If None, stdout and stderr are captured and returned. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any + output files. + """ + if not command_args: + raise ValueError("command_args cannot be empty. Please specify an rnftools subcommand and its arguments.") + + cmd = ["rnftools"] + command_args + + # Validate working_dir if provided + if working_dir: + if not working_dir.is_dir(): + raise ValueError(f"Working directory '{working_dir}' does not exist or is not a directory.") + working_dir_str = str(working_dir) + else: + working_dir_str = None + + # Prepare for output redirection if log_file is provided + stdout_capture = subprocess.PIPE + stderr_capture = subprocess.PIPE + log_file_handle = None + + if log_file: + try: + log_file.parent.mkdir(parents=True, exist_ok=True) + log_file_handle = open(log_file, 'w') + stdout_capture = log_file_handle + stderr_capture = log_file_handle + except IOError as e: + raise IOError(f"Could not open log file '{log_file}' for writing: {e}") + + command_line = shlex.join(cmd) + stdout_output = "" + stderr_output = "" + output_files: List[Path] = [] # This would be populated if specific subcommands were known + + try: + process = subprocess.run( + cmd, + cwd=working_dir_str, + stdout=stdout_capture, + stderr=stderr_capture, + check=True, + text=True, + encoding='utf-8' + ) + if log_file is None: + stdout_output = process.stdout + stderr_output = process.stderr + + except subprocess.CalledProcessError as e: + if log_file_handle: + log_file_handle.close() + return { + "command_executed": command_line, + "stdout": e.stdout if log_file is None else f"See log file: {log_file}", + "stderr": e.stderr if log_file is None else f"See log file: {log_file}", + "returncode": e.returncode, + "error": f"rnftools command failed with exit code {e.returncode}", + "output_files": output_files, + } + except FileNotFoundError: + if log_file_handle: + log_file_handle.close() + return { + "command_executed": command_line, + "stdout": "", + "stderr": "Error: rnftools executable not found. Please ensure it is installed and in your PATH.", + "returncode": 127, + "error": "rnftools executable not found", + "output_files": output_files, + } + except Exception as e: + if log_file_handle: + log_file_handle.close() + return { + "command_executed": command_line, + "stdout": stdout_output, + "stderr": str(e), + "returncode": 1, + "error": f"An unexpected error occurred: {e}", + "output_files": output_files, + } + finally: + if log_file_handle: + log_file_handle.close() + + return { + "command_executed": command_line, + "stdout": stdout_output if log_file is None else f"See log file: {log_file}", + "stderr": stderr_output if log_file is None else f"See log file: {log_file}", + "output_files": output_files, + } + +# Example of how specific subcommands would be implemented if documentation were available: +# +@mcp.tool() +# def rnftools_simulate( +# genome_fasta: Path, +# output_prefix: Path, +# read_length: int = 100, +# num_reads: int = 1000000, +# sequencing_model: str = "illumina", # Example, based on common simulators +# # ... other parameters specific to 'simulate' subcommand +# ) -> Dict[str, Any]: +# """ +# Simulates NGS reads using rnftools. +# """ +# # ... implementation for 'rnftools simulate' +# pass +# +@mcp.tool() +# def rnftools_evaluate( +# rnf_file: Path, +# mapper_output_bam: Path, +# report_dir: Path, +# # ... other parameters specific to 'evaluate' subcommand +# ) -> Dict[str, Any]: +# """ +# Evaluates mapper performance using RNF-compliant data. +# """ +# # ... implementation for 'rnftools evaluate' +# pass + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/rnftools_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/rnftools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c05a7263105bb0cc00a70bfbec4f1be0056b8277 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/app/rnftools_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_rnftools/app/rnftools_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_rnftools' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9397dcd5f01221073132142e8153d727c5530b5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-rnftools: + build: . + image: mcp-rnftools:latest + container_name: mcp-rnftools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=rnftools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4ce6b970982e7d9c7394dd670c86faacf8de4fb4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - rnftools + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_rnftools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c3466c3e1924a54976d282de13c5f020d8406c5b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install samtools via conda (e.g., from bioconda) +RUN conda install -c bioconda samtools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/samtools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/samtools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/samtools_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/__pycache__/samtools_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/__pycache__/samtools_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f28817de16f19b99be4b4e28c6fd6f0bc02bab32 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/__pycache__/samtools_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/__pycache__/samtools_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/__pycache__/samtools_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe86ada41f07e954bc9c84749d8457c56edd53bb Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/__pycache__/samtools_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/samtools_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/samtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e1c17ae7020a89991d8e4ca5f3079dbd3964ee8d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/samtools_server.py @@ -0,0 +1,1337 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +# Helper function to run samtools commands +def _run_samtools_command( + command_args: List[str], + input_files: Optional[List[Path]] = None, + output_files: Optional[List[Path]] = None, + check_existence: bool = True, +) -> dict: + """ + Executes a samtools command and handles output/errors. + + Args: + command_args: List of command-line arguments for samtools. + input_files: List of input file paths to check for existence. + output_files: List of expected output file paths. + check_existence: If True, checks if input_files exist before running. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + full_command = ["samtools"] + command_args + + if check_existence and input_files: + for f in input_files: + if not f.exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + try: + process = subprocess.run( + [str(arg) for arg in full_command], + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join([str(arg) for arg in full_command]), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(f) for f in output_files] if output_files else [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join([str(arg) for arg in full_command]), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Samtools command failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join([str(arg) for arg in full_command]), + "stdout": "", + "stderr": "Error: samtools command not found. Is it installed and in PATH?", + "error": "Samtools executable not found.", + "output_files": [], + } + + +# --- Indexing Commands --- + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_dict( + fasta_file: Path, + output_dict_file: Optional[Path] = None, + sequence_name_style: Optional[str] = None, +) -> dict: + """ + Creates a sequence dictionary file (.dict) from a FASTA reference. + + Args: + fasta_file: Path to the input FASTA reference file. + output_dict_file: Optional path for the output dictionary file. If not + provided, it defaults to .dict. + sequence_name_style: Optional style for sequence names in the dictionary. + (e.g., 'ucsc', 'ensembl', 'genbank'). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not fasta_file.exists(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + + cmd = ["dict", fasta_file] + output_file = output_dict_file if output_dict_file else fasta_file.with_suffix(".dict") + cmd.extend(["-o", output_file]) + + if sequence_name_style: + cmd.extend(["-s", sequence_name_style]) + + return _run_samtools_command(cmd, input_files=[fasta_file], output_files=[output_file]) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_faidx( + fasta_file: Path, + regions: Optional[List[str]] = None, + output_file: Optional[Path] = None, + regions_file: Optional[Path] = None, + line_length: Optional[int] = None, + chrom_only: bool = False, +) -> dict: + """ + Indexes a FASTA file or extracts sequences from an indexed FASTA. + + Args: + fasta_file: Path to the input FASTA file. + regions: Optional list of regions (e.g., "chr1:100-200") to extract. + If provided, sequences are extracted. + output_file: Optional path for the output FASTA file when extracting regions. + If not provided, extracted sequences go to stdout. + regions_file: Optional path to a file containing regions to extract. + line_length: Optional line length for output sequences (default is 60). + chrom_only: If True, only output chromosome names, not full headers. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not fasta_file.exists(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + + cmd = ["faidx", fasta_file] + + if output_file: + cmd.extend(["-o", output_file]) + if regions_file: + if not regions_file.exists(): + raise FileNotFoundError(f"Regions file not found: {regions_file}") + cmd.extend(["-r", regions_file]) + if line_length is not None: + if line_length < 1: + raise ValueError("Line length must be a positive integer.") + cmd.extend(["-n", str(line_length)]) + if chrom_only: + cmd.append("-c") + if regions: + cmd.extend(regions) + + output_files_list = [output_file] if output_file else [] + # faidx also creates a .fai file, but it's implicit and often not returned explicitly + # unless it's the primary output. For extraction, the output_file is primary. + return _run_samtools_command(cmd, input_files=[fasta_file], output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_fqidx( + fastq_file: Path, + regions: Optional[List[str]] = None, + output_file: Optional[Path] = None, + regions_file: Optional[Path] = None, + line_length: Optional[int] = None, + chrom_only: bool = False, +) -> dict: + """ + Indexes a FASTQ file or extracts sequences from an indexed FASTQ. + + Args: + fastq_file: Path to the input FASTQ file. + regions: Optional list of regions (e.g., "chr1:100-200") to extract. + If provided, sequences are extracted. + output_file: Optional path for the output FASTQ file when extracting regions. + If not provided, extracted sequences go to stdout. + regions_file: Optional path to a file containing regions to extract. + line_length: Optional line length for output sequences (default is 60). + chrom_only: If True, only output chromosome names, not full headers. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not fastq_file.exists(): + raise FileNotFoundError(f"Input FASTQ file not found: {fastq_file}") + + cmd = ["fqidx", fastq_file] + + if output_file: + cmd.extend(["-o", output_file]) + if regions_file: + if not regions_file.exists(): + raise FileNotFoundError(f"Regions file not found: {regions_file}") + cmd.extend(["-r", regions_file]) + if line_length is not None: + if line_length < 1: + raise ValueError("Line length must be a positive integer.") + cmd.extend(["-n", str(line_length)]) + if chrom_only: + cmd.append("-c") + if regions: + cmd.extend(regions) + + output_files_list = [output_file] if output_file else [] + # fqidx also creates a .fqi file, but it's implicit. + return _run_samtools_command(cmd, input_files=[fastq_file], output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_index( + alignment_file: Path, + use_csi: bool = False, + min_shift: Optional[int] = None, +) -> dict: + """ + Indexes a BAM or CRAM alignment file. + + Args: + alignment_file: Path to the input BAM or CRAM file. + use_csi: If True, create a CSI index (.csi) instead of a BAI index (.bai). + min_shift: Minimum shift for CSI indexing (default 14 for BAI, 13 for CSI). + Only applicable if `use_csi` is True. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not alignment_file.exists(): + raise FileNotFoundError(f"Input alignment file not found: {alignment_file}") + + cmd = ["index", alignment_file] + output_suffix = ".csi" if use_csi else ".bai" + output_index_file = alignment_file.with_suffix(alignment_file.suffix + output_suffix) + + if use_csi: + cmd.append("-c") + if min_shift is not None: + if min_shift < 1: + raise ValueError("Minimum shift must be a positive integer.") + cmd.extend(["-m", str(min_shift)]) + elif min_shift is not None: + # min_shift is only relevant for CSI, warn if used with BAI + print("Warning: --min-shift is only applicable for CSI indexing (-c). Ignoring for BAI.") + + return _run_samtools_command(cmd, input_files=[alignment_file], output_files=[output_index_file]) + + +# --- Editing Commands --- + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_calmd( + input_bam: Path, + reference_fasta: Path, + output_bam: Optional[Path] = None, + recalculate_tags: bool = False, + uncompressed_output: bool = False, + coefficient: Optional[int] = None, + threads: int = 0, +) -> dict: + """ + Recalculates MD/NM tags and '=' bases in an alignment file. + + Args: + input_bam: Path to the input BAM file. + reference_fasta: Path to the reference FASTA file. + output_bam: Optional path for the output BAM file. If not provided, output goes to stdout. + recalculate_tags: If True, recalculate NM and MD tags. + uncompressed_output: If True, output uncompressed BAM. + coefficient: Coefficient for calculating BQ. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + if not reference_fasta.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + + cmd = ["calmd", input_bam, reference_fasta] + + if output_bam: + cmd.extend(["-o", output_bam]) + if recalculate_tags: + cmd.append("-e") + if uncompressed_output: + cmd.append("-u") + if coefficient is not None: + cmd.extend(["-C", str(coefficient)]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + + output_files_list = [output_bam] if output_bam else [] + return _run_samtools_command( + cmd, input_files=[input_bam, reference_fasta], output_files=output_files_list + ) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_fixmate( + input_bam: Path, + output_bam: Path, + remove_secondary_supplementary: bool = False, + add_pg_tag: bool = False, + add_mate_score: bool = False, + threads: int = 0, +) -> dict: + """ + Fixes mate information for paired-end reads in a BAM file. + Input BAM must be sorted by read name. + + Args: + input_bam: Path to the input BAM file (must be sorted by read name). + output_bam: Path for the output BAM file. + remove_secondary_supplementary: If True, remove secondary and supplementary alignments. + add_pg_tag: If True, add PG tag to output. + add_mate_score: If True, add mate score (ms tag). + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + + cmd = ["fixmate", input_bam, output_bam] + + if remove_secondary_supplementary: + cmd.append("-r") + if add_pg_tag: + cmd.append("-p") + if add_mate_score: + cmd.append("-m") + if threads > 0: + cmd.extend(["-@", str(threads)]) + + return _run_samtools_command(cmd, input_files=[input_bam], output_files=[output_bam]) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_reheader( + new_header_file: Path, + input_bam: Path, + output_bam: Optional[Path] = None, +) -> dict: + """ + Replaces the header of a BAM file with a new header from a SAM file. + + Args: + new_header_file: Path to the SAM file containing the new header. + input_bam: Path to the input BAM file. + output_bam: Optional path for the output BAM file. If not provided, output goes to stdout. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not new_header_file.exists(): + raise FileNotFoundError(f"New header file not found: {new_header_file}") + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + + cmd = ["reheader", new_header_file, input_bam] + + if output_bam: + cmd.extend(["-o", output_bam]) + + output_files_list = [output_bam] if output_bam else [] + return _run_samtools_command( + cmd, input_files=[new_header_file, input_bam], output_files=output_files_list + ) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_targetcut( + input_bam: Path, + output_bam: Optional[Path] = None, + reference_fasta: Optional[Path] = None, +) -> dict: + """ + Cuts fosmid regions (for fosmid pool only). This is a specialized tool. + + Args: + input_bam: Path to the input BAM file. + output_bam: Optional path for the output BAM file. If not provided, output goes to stdout. + reference_fasta: Optional path to the reference FASTA file. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + if reference_fasta and not reference_fasta.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + + cmd = ["targetcut", input_bam] + + if output_bam: + cmd.extend(["-o", output_bam]) + if reference_fasta: + cmd.extend(["-f", reference_fasta]) + + output_files_list = [output_bam] if output_bam else [] + input_files_list = [input_bam] + if reference_fasta: + input_files_list.append(reference_fasta) + + return _run_samtools_command(cmd, input_files=input_files_list, output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_addreplacerg( + input_bam: Path, + rg_line: str, + output_bam: Optional[Path] = None, + overwrite_existing_rg: bool = False, + threads: int = 0, +) -> dict: + """ + Adds or replaces RG (Read Group) tags in an alignment file. + + Args: + input_bam: Path to the input BAM file. + rg_line: The full RG line to add or replace (e.g., '@RG\\tID:group1\\tSM:sample1'). + output_bam: Optional path for the output BAM file. If not provided, output goes to stdout. + overwrite_existing_rg: If True, overwrite existing RG tags. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + + cmd = ["addreplacerg", "-r", rg_line, input_bam] + + if output_bam: + cmd.extend(["-o", output_bam]) + if overwrite_existing_rg: + cmd.append("-w") + if threads > 0: + cmd.extend(["-@", str(threads)]) + + output_files_list = [output_bam] if output_bam else [] + return _run_samtools_command(cmd, input_files=[input_bam], output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_markdup( + input_bam: Path, + output_bam: Path, + remove_duplicates: bool = False, + mark_supplementary: bool = False, + fill_tags: bool = False, + max_isize: Optional[int] = None, + threads: int = 0, +) -> dict: + """ + Marks duplicates in a BAM file. Input BAM must be sorted by coordinate. + + Args: + input_bam: Path to the input BAM file (must be sorted by coordinate). + output_bam: Path for the output BAM file. + remove_duplicates: If True, remove duplicate reads instead of just marking them. + mark_supplementary: If True, mark supplementary alignments as duplicates. + fill_tags: If True, fill in the MC and ML tags. + max_isize: Maximum insert size to consider for duplicates. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + + cmd = ["markdup", input_bam, output_bam] + + if remove_duplicates: + cmd.append("-r") + if mark_supplementary: + cmd.append("-s") + if fill_tags: + cmd.append("-f") + if max_isize is not None: + if max_isize < 0: + raise ValueError("Maximum insert size must be a non-negative integer.") + cmd.extend(["-l", str(max_isize)]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + + return _run_samtools_command(cmd, input_files=[input_bam], output_files=[output_bam]) + + +# --- File Operations Commands --- + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_collate( + input_bam: Path, + output_prefix: Path, + uncompressed_output: bool = False, + threads: int = 0, +) -> dict: + """ + Shuffles and groups alignments by name. + + Args: + input_bam: Path to the input BAM file. + output_prefix: Prefix for the output BAM file(s). + E.g., if 'output_prefix' is 'out', output will be 'out.bam'. + uncompressed_output: If True, output uncompressed BAM. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + + cmd = ["collate", input_bam, output_prefix] + + if uncompressed_output: + cmd.append("-u") + if threads > 0: + cmd.extend(["-@", str(threads)]) + + # samtools collate outputs to .bam + output_file = output_prefix.with_suffix(".bam") + return _run_samtools_command(cmd, input_files=[input_bam], output_files=[output_file]) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_cat( + input_bams: List[Path], + output_bam: Optional[Path] = None, + threads: int = 0, +) -> dict: + """ + Concatenates BAM files. All input files must have identical headers. + + Args: + input_bams: List of paths to input BAM files. + output_bam: Optional path for the output concatenated BAM file. + If not provided, output goes to stdout. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bams: + raise ValueError("At least one input BAM file is required.") + for f in input_bams: + if not f.exists(): + raise FileNotFoundError(f"Input BAM file not found: {f}") + + cmd = ["cat"] + if output_bam: + cmd.extend(["-o", output_bam]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + cmd.extend(input_bams) + + output_files_list = [output_bam] if output_bam else [] + return _run_samtools_command(cmd, input_files=input_bams, output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_merge( + output_bam: Path, + input_bams: List[Path], + add_rg_tags: bool = False, + header_file: Optional[Path] = None, + uncompressed_output: bool = False, + threads: int = 0, +) -> dict: + """ + Merges multiple sorted alignment files into a single sorted file. + + Args: + output_bam: Path for the output merged BAM file. + input_bams: List of paths to input BAM files (must be sorted). + add_rg_tags: If True, add RG tags to output reads. + header_file: Optional path to a SAM header file to use. + uncompressed_output: If True, output uncompressed BAM. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bams: + raise ValueError("At least one input BAM file is required.") + for f in input_bams: + if not f.exists(): + raise FileNotFoundError(f"Input BAM file not found: {f}") + if header_file and not header_file.exists(): + raise FileNotFoundError(f"Header file not found: {header_file}") + + cmd = ["merge", output_bam] + + if add_rg_tags: + cmd.append("-r") + if header_file: + cmd.extend(["-h", header_file]) + if uncompressed_output: + cmd.append("-u") + if threads > 0: + cmd.extend(["-@", str(threads)]) + cmd.extend(input_bams) + + input_files_list = list(input_bams) + if header_file: + input_files_list.append(header_file) + + return _run_samtools_command(cmd, input_files=input_files_list, output_files=[output_bam]) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_mpileup( + reference_fasta: Path, + input_bams: List[Path], + output_file: Optional[Path] = None, + region: Optional[str] = None, + regions_file: Optional[Path] = None, + min_base_quality: int = 0, + min_mapping_quality: int = 0, + uncompressed_bcf_output: bool = False, + threads: int = 0, +) -> dict: + """ + Generates a multi-way pileup from multiple alignment files. + + Args: + reference_fasta: Path to the reference FASTA file. + input_bams: List of paths to input BAM/CRAM files. + output_file: Optional path for the output pileup file. If not provided, output goes to stdout. + region: Optional genomic region to pileup (e.g., "chr1:100-200"). + regions_file: Optional path to a BED file containing regions to pileup. + min_base_quality: Minimum base quality to consider (default 0). + min_mapping_quality: Minimum mapping quality to consider (default 0). + uncompressed_bcf_output: If True, output uncompressed BCF (implies -g). + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not reference_fasta.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + if not input_bams: + raise ValueError("At least one input BAM file is required.") + for f in input_bams: + if not f.exists(): + raise FileNotFoundError(f"Input BAM file not found: {f}") + if regions_file and not regions_file.exists(): + raise FileNotFoundError(f"Regions file not found: {regions_file}") + if min_base_quality < 0 or min_mapping_quality < 0: + raise ValueError("Quality scores must be non-negative.") + + cmd = ["mpileup", "-f", reference_fasta] + + if output_file: + cmd.extend(["-o", output_file]) + if region: + cmd.extend(["-r", region]) + if regions_file: + cmd.extend(["-l", regions_file]) + if min_base_quality > 0: + cmd.extend(["-q", str(min_base_quality)]) + if min_mapping_quality > 0: + cmd.extend(["-Q", str(min_mapping_quality)]) + if uncompressed_bcf_output: + cmd.append("-u") # -u implies -g for BCF output + if threads > 0: + cmd.extend(["-@", str(threads)]) + cmd.extend(input_bams) + + input_files_list = [reference_fasta] + list(input_bams) + if regions_file: + input_files_list.append(regions_file) + output_files_list = [output_file] if output_file else [] + + return _run_samtools_command(cmd, input_files=input_files_list, output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_sort( + input_alignment_file: Path, + output_alignment_file: Path, + sort_by_name: bool = False, + sort_by_tag: Optional[str] = None, + max_memory_per_thread: Optional[str] = None, + threads: int = 0, + output_format: Optional[str] = None, # 'bam', 'sam', 'cram' +) -> dict: + """ + Sorts an alignment file. + + Args: + input_alignment_file: Path to the input alignment file (BAM, SAM, or CRAM). + output_alignment_file: Path for the output sorted alignment file. + sort_by_name: If True, sort by read name instead of coordinate. + sort_by_tag: Optional tag to sort by (e.g., "RG"). + max_memory_per_thread: Maximum memory per thread (e.g., "750M", "4G"). + threads: Number of additional threads to use (0 for single thread). + output_format: Optional output format ('bam', 'sam', 'cram'). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_alignment_file.exists(): + raise FileNotFoundError(f"Input alignment file not found: {input_alignment_file}") + + cmd = ["sort", input_alignment_file, "-o", output_alignment_file] + + if sort_by_name: + cmd.append("-n") + if sort_by_tag: + cmd.extend(["-t", sort_by_tag]) + if max_memory_per_thread: + cmd.extend(["-m", max_memory_per_thread]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + if output_format: + if output_format not in ["bam", "sam", "cram"]: + raise ValueError(f"Invalid output format: {output_format}. Must be 'bam', 'sam', or 'cram'.") + cmd.extend(["-O", output_format]) + + return _run_samtools_command( + cmd, input_files=[input_alignment_file], output_files=[output_alignment_file] + ) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_split( + input_bam: Path, + output_prefix: Optional[Path] = None, + unmapped_output: Optional[Path] = None, + delete_rg_tag: bool = False, +) -> dict: + """ + Splits a BAM file by read group. + + Args: + input_bam: Path to the input BAM file. + output_prefix: Optional prefix for output files. If not provided, files are named + after read group IDs in the current directory. + unmapped_output: Optional path for a file to store unmapped reads. + delete_rg_tag: If True, delete the RG tag from output reads. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + + cmd = ["split", input_bam] + + if output_prefix: + cmd.extend(["-o", output_prefix]) + if unmapped_output: + cmd.extend(["-u", unmapped_output]) + if delete_rg_tag: + cmd.append("-d") + + # The output files are dynamic based on RG tags. We can't predict them precisely. + # If output_prefix is given, we can assume files like ..bam + # For now, we'll just return the prefix if provided, or an empty list. + output_files_list = [] + if output_prefix: + output_files_list.append(output_prefix) # This is a prefix, not a final file + if unmapped_output: + output_files_list.append(unmapped_output) + + return _run_samtools_command(cmd, input_files=[input_bam], output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_quickcheck( + input_files: List[Path], +) -> dict: + """ + Quickly checks if SAM/BAM/CRAM files appear intact. + + Args: + input_files: List of paths to SAM/BAM/CRAM files to check. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_files: + raise ValueError("At least one input file is required.") + for f in input_files: + if not f.exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + cmd = ["quickcheck"] + input_files + + return _run_samtools_command(cmd, input_files=input_files, output_files=[]) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_fastq( + input_alignment_file: Path, + output_fastq_file: Optional[Path] = None, + output_fastq_r1: Optional[Path] = None, + output_fastq_r2: Optional[Path] = None, + output_fastq_single_end: Optional[Path] = None, + no_comment: bool = False, + threads: int = 0, +) -> dict: + """ + Converts a BAM/CRAM file to FASTQ format. + + Args: + input_alignment_file: Path to the input BAM/CRAM file. + output_fastq_file: Optional path for a single output FASTQ file (for interleaved or single-end). + If not provided, output goes to stdout. + output_fastq_r1: Optional path for R1 output FASTQ file (for paired-end). + output_fastq_r2: Optional path for R2 output FASTQ file (for paired-end). + output_fastq_single_end: Optional path for single-end reads output FASTQ file. + no_comment: If True, do not output comments in FASTQ header. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_alignment_file.exists(): + raise FileNotFoundError(f"Input alignment file not found: {input_alignment_file}") + + cmd = ["fastq", input_alignment_file] + output_files_list = [] + + if output_fastq_file: + cmd.extend(["-o", output_fastq_file]) + output_files_list.append(output_fastq_file) + if output_fastq_r1: + cmd.extend(["-1", output_fastq_r1]) + output_files_list.append(output_fastq_r1) + if output_fastq_r2: + cmd.extend(["-2", output_fastq_r2]) + output_files_list.append(output_fastq_r2) + if output_fastq_single_end: + cmd.extend(["-s", output_fastq_single_end]) + output_files_list.append(output_fastq_single_end) + + if no_comment: + cmd.append("-N") + if threads > 0: + cmd.extend(["-@", str(threads)]) + + # Validate output file combinations + if sum([1 for x in [output_fastq_file, output_fastq_r1, output_fastq_r2] if x is not None]) > 1: + raise ValueError("Cannot specify -o, -1, or -2 simultaneously. Choose one output mode.") + if (output_fastq_r1 and not output_fastq_r2) or (output_fastq_r2 and not output_fastq_r1): + raise ValueError("Both -1 and -2 must be specified for paired-end output.") + + return _run_samtools_command( + cmd, input_files=[input_alignment_file], output_files=output_files_list + ) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_fasta( + input_alignment_file: Path, + output_fasta_file: Optional[Path] = None, + no_comment: bool = False, + region: Optional[str] = None, + regions_file: Optional[Path] = None, + threads: int = 0, +) -> dict: + """ + Converts a BAM/CRAM file to FASTA format. + + Args: + input_alignment_file: Path to the input BAM/CRAM file. + output_fasta_file: Optional path for the output FASTA file. If not provided, output goes to stdout. + no_comment: If True, do not output comments in FASTA header. + region: Optional genomic region to extract (e.g., "chr1:100-200"). + regions_file: Optional path to a BED file containing regions to extract. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_alignment_file.exists(): + raise FileNotFoundError(f"Input alignment file not found: {input_alignment_file}") + if regions_file and not regions_file.exists(): + raise FileNotFoundError(f"Regions file not found: {regions_file}") + + cmd = ["fasta", input_alignment_file] + output_files_list = [] + + if output_fasta_file: + cmd.extend(["-o", output_fasta_file]) + output_files_list.append(output_fasta_file) + if no_comment: + cmd.append("-N") + if region: + cmd.extend(["-r", region]) + if regions_file: + cmd.extend(["-L", regions_file]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + + input_files_list = [input_alignment_file] + if regions_file: + input_files_list.append(regions_file) + + return _run_samtools_command(cmd, input_files=input_files_list, output_files=output_files_list) + + +# --- Statistics Commands --- + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_bedcov( + bed_file: Path, + input_bams: List[Path], + min_base_quality: int = 0, + min_mapping_quality: int = 0, +) -> dict: + """ + Computes read depth per BED region. + + Args: + bed_file: Path to the input BED file. + input_bams: List of paths to input BAM/CRAM files. + min_base_quality: Minimum base quality to consider (default 0). + min_mapping_quality: Minimum mapping quality to consider (default 0). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not bed_file.exists(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + if not input_bams: + raise ValueError("At least one input BAM file is required.") + for f in input_bams: + if not f.exists(): + raise FileNotFoundError(f"Input BAM file not found: {f}") + if min_base_quality < 0 or min_mapping_quality < 0: + raise ValueError("Quality scores must be non-negative.") + + cmd = ["bedcov"] + + if min_base_quality > 0: + cmd.extend(["-q", str(min_base_quality)]) + if min_mapping_quality > 0: + cmd.extend(["-Q", str(min_mapping_quality)]) + + cmd.extend([bed_file] + input_bams) + + input_files_list = [bed_file] + list(input_bams) + return _run_samtools_command(cmd, input_files=input_files_list, output_files=[]) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_depth( + input_bams: List[Path], + output_file: Optional[Path] = None, + all_positions: bool = False, + bed_file: Optional[Path] = None, + region: Optional[str] = None, + min_base_quality: int = 0, + min_mapping_quality: int = 0, + threads: int = 0, +) -> dict: + """ + Computes the depth of coverage at each position or within specified regions. + + Args: + input_bams: List of paths to input BAM/CRAM files. + output_file: Optional path for the output depth file. If not provided, output goes to stdout. + all_positions: If True, output all positions, even if depth is 0. + bed_file: Optional path to a BED file to restrict depth calculation to specific regions. + region: Optional genomic region to calculate depth for (e.g., "chr1:100-200"). + min_base_quality: Minimum base quality to consider (default 0). + min_mapping_quality: Minimum mapping quality to consider (default 0). + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bams: + raise ValueError("At least one input BAM file is required.") + for f in input_bams: + if not f.exists(): + raise FileNotFoundError(f"Input BAM file not found: {f}") + if bed_file and not bed_file.exists(): + raise FileNotFoundError(f"BED file not found: {bed_file}") + if min_base_quality < 0 or min_mapping_quality < 0: + raise ValueError("Quality scores must be non-negative.") + + cmd = ["depth"] + + if output_file: + cmd.extend(["-o", output_file]) + if all_positions: + cmd.append("-a") + if bed_file: + cmd.extend(["-b", bed_file]) + if region: + cmd.extend(["-r", region]) + if min_base_quality > 0: + cmd.extend(["-q", str(min_base_quality)]) + if min_mapping_quality > 0: + cmd.extend(["-Q", str(min_mapping_quality)]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + + cmd.extend(input_bams) + + input_files_list = list(input_bams) + if bed_file: + input_files_list.append(bed_file) + output_files_list = [output_file] if output_file else [] + + return _run_samtools_command(cmd, input_files=input_files_list, output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_flagstat( + input_alignment_file: Path, + output_file: Optional[Path] = None, + threads: int = 0, +) -> dict: + """ + Generates simple statistics on alignment flags. + + Args: + input_alignment_file: Path to the input BAM/SAM/CRAM file. + output_file: Optional path for the output statistics file. If not provided, output goes to stdout. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_alignment_file.exists(): + raise FileNotFoundError(f"Input alignment file not found: {input_alignment_file}") + + cmd = ["flagstat", input_alignment_file] + + if output_file: + cmd.extend(["-o", output_file]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + + output_files_list = [output_file] if output_file else [] + return _run_samtools_command( + cmd, input_files=[input_alignment_file], output_files=output_files_list + ) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_idxstats( + input_alignment_file: Path, +) -> dict: + """ + Retrieves and prints statistics from the BAM index file. + + Args: + input_alignment_file: Path to the input BAM/CRAM file. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_alignment_file.exists(): + raise FileNotFoundError(f"Input alignment file not found: {input_alignment_file}") + + cmd = ["idxstats", input_alignment_file] + + return _run_samtools_command(cmd, input_files=[input_alignment_file], output_files=[]) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_phase( + input_bam: Path, + output_file: Optional[Path] = None, + min_base_quality: int = 0, + min_mapping_quality: int = 0, + min_coverage: int = 0, +) -> dict: + """ + Phases heterozygotes in a BAM file. + + Args: + input_bam: Path to the input BAM file. + output_file: Optional path for the output phased variants file. If not provided, output goes to stdout. + min_base_quality: Minimum base quality to consider (default 0). + min_mapping_quality: Minimum mapping quality to consider (default 0). + min_coverage: Minimum coverage to consider a site (default 0). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + if min_base_quality < 0 or min_mapping_quality < 0 or min_coverage < 0: + raise ValueError("Quality scores and coverage must be non-negative.") + + cmd = ["phase", input_bam] + + if output_file: + cmd.extend(["-o", output_file]) + if min_base_quality > 0: + cmd.extend(["-q", str(min_base_quality)]) + if min_mapping_quality > 0: + cmd.extend(["-Q", str(min_mapping_quality)]) + if min_coverage > 0: + cmd.extend(["-k", str(min_coverage)]) + + output_files_list = [output_file] if output_file else [] + return _run_samtools_command(cmd, input_files=[input_bam], output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_stats( + input_alignment_file: Path, + output_file: Optional[Path] = None, + reference_fasta: Optional[Path] = None, + coverage_cap: Optional[int] = None, + threads: int = 0, +) -> dict: + """ + Generates detailed statistics from an alignment file. + + Args: + input_alignment_file: Path to the input BAM/SAM/CRAM file. + output_file: Optional path for the output statistics file. If not provided, output goes to stdout. + reference_fasta: Optional path to the reference FASTA file. + coverage_cap: Optional maximum coverage to count (default 250). + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_alignment_file.exists(): + raise FileNotFoundError(f"Input alignment file not found: {input_alignment_file}") + if reference_fasta and not reference_fasta.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + if coverage_cap is not None and coverage_cap < 0: + raise ValueError("Coverage cap must be a non-negative integer.") + + cmd = ["stats", input_alignment_file] + + if output_file: + cmd.extend(["-o", output_file]) + if reference_fasta: + cmd.extend(["-r", reference_fasta]) + if coverage_cap is not None: + cmd.extend(["-c", str(coverage_cap)]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + + input_files_list = [input_alignment_file] + if reference_fasta: + input_files_list.append(reference_fasta) + output_files_list = [output_file] if output_file else [] + + return _run_samtools_command(cmd, input_files=input_files_list, output_files=output_files_list) + + +# --- Viewing Commands --- + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_flags( + flag_value: Union[int, str], +) -> dict: + """ + Explains BAM flags (integer value or symbolic string). + + Args: + flag_value: An integer representing the flag value or a symbolic string + (e.g., "0x4", "PAIRED", "UNMAP"). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + cmd = ["flags", str(flag_value)] + + return _run_samtools_command(cmd, check_existence=False) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_tview( + input_alignment_file: Path, + reference_fasta: Optional[Path] = None, + region: Optional[str] = None, + display_deletions: bool = False, + position: Optional[str] = None, + sequence: Optional[str] = None, +) -> dict: + """ + Provides a text alignment viewer. Note: This is an interactive tool and its + output is typically not suitable for automated parsing. This wrapper will + capture the initial screen output if not interactive. + + Args: + input_alignment_file: Path to the input BAM/SAM/CRAM file. + reference_fasta: Optional path to the reference FASTA file. + region: Optional genomic region to view (e.g., "chr1:100-200"). + display_deletions: If True, display deletions as '-'. + position: Optional starting position (e.g., "chr1:100"). + sequence: Optional sequence to highlight. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_alignment_file.exists(): + raise FileNotFoundError(f"Input alignment file not found: {input_alignment_file}") + if reference_fasta and not reference_fasta.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + + cmd = ["tview", input_alignment_file] + + if reference_fasta: + cmd.extend(["-f", reference_fasta]) + if region: + cmd.extend(["-r", region]) + if display_deletions: + cmd.append("-d") + if position: + cmd.extend(["-p", position]) + if sequence: + cmd.extend(["-s", sequence]) + + input_files_list = [input_alignment_file] + if reference_fasta: + input_files_list.append(reference_fasta) + + # tview is interactive, so capturing stdout might not be useful for all cases. + # It will capture the initial screen dump. + return _run_samtools_command(cmd, input_files=input_files_list, output_files=[]) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_view( + input_alignment_file: Path, + output_file: Optional[Path] = None, + output_format: Optional[str] = None, # 'sam', 'bam', 'cram' + input_is_sam: bool = False, + include_header: bool = False, + regions: Optional[List[str]] = None, + regions_file: Optional[Path] = None, + min_mapping_quality: int = 0, + filter_flags: Optional[int] = None, + require_flags: Optional[int] = None, + threads: int = 0, +) -> dict: + """ + Views, filters, and converts SAM/BAM/CRAM files. + + Args: + input_alignment_file: Path to the input SAM/BAM/CRAM file. + output_file: Optional path for the output alignment file. If not provided, output goes to stdout. + output_format: Optional output format ('sam', 'bam', 'cram'). + input_is_sam: If True, assume input is SAM format. + include_header: If True, include header in output. + regions: Optional list of genomic regions to extract (e.g., "chr1:100-200"). + regions_file: Optional path to a BED file containing regions to extract. + min_mapping_quality: Minimum mapping quality to include reads (default 0). + filter_flags: Exclude reads with any of these flags set (integer value). + require_flags: Only include reads with all of these flags set (integer value). + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_alignment_file.exists(): + raise FileNotFoundError(f"Input alignment file not found: {input_alignment_file}") + if regions_file and not regions_file.exists(): + raise FileNotFoundError(f"Regions file not found: {regions_file}") + if min_mapping_quality < 0: + raise ValueError("Minimum mapping quality must be non-negative.") + if filter_flags is not None and filter_flags < 0: + raise ValueError("Filter flags must be a non-negative integer.") + if require_flags is not None and require_flags < 0: + raise ValueError("Require flags must be a non-negative integer.") + if output_format and output_format not in ["sam", "bam", "cram"]: + raise ValueError(f"Invalid output format: {output_format}. Must be 'sam', 'bam', or 'cram'.") + + cmd = ["view", input_alignment_file] + output_files_list = [] + + if output_file: + cmd.extend(["-o", output_file]) + output_files_list.append(output_file) + if output_format == "sam": + cmd.append("-S") # This is usually for input, but samtools view -O SAM is also possible + # For output, -O is preferred. Let's use -O. + cmd.extend(["-O", "SAM"]) + elif output_format == "bam": + cmd.extend(["-O", "BAM"]) + elif output_format == "cram": + cmd.extend(["-O", "CRAM"]) + + if input_is_sam: + cmd.append("-S") + if include_header: + cmd.append("-h") + if regions_file: + cmd.extend(["-L", regions_file]) + if min_mapping_quality > 0: + cmd.extend(["-q", str(min_mapping_quality)]) + if filter_flags is not None: + cmd.extend(["-F", str(filter_flags)]) + if require_flags is not None: + cmd.extend(["-f", str(require_flags)]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + if regions: + cmd.extend(regions) + + input_files_list = [input_alignment_file] + if regions_file: + input_files_list.append(regions_file) + + return _run_samtools_command(cmd, input_files=input_files_list, output_files=output_files_list) + + +# @mcp.tool() # Uncomment this line when integrating with MCP +def samtools_depad( + input_bam: Path, + output_bam: Optional[Path] = None, + threads: int = 0, +) -> dict: + """ + Converts a padded BAM to an unpadded BAM. + + Args: + input_bam: Path to the input padded BAM file. + output_bam: Optional path for the output unpadded BAM file. If not provided, output goes to stdout. + threads: Number of additional threads to use (0 for single thread). + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_bam.exists(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + + cmd = ["depad", input_bam] + + if output_bam: + cmd.extend(["-o", output_bam]) + if threads > 0: + cmd.extend(["-@", str(threads)]) + + output_files_list = [output_bam] if output_bam else [] + return _run_samtools_command(cmd, input_files=[input_bam], output_files=output_files_list) \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/samtools_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/samtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..768d2736455ab3e71c84d0f409327f4361ac1d24 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/app/samtools_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_samtools/app/samtools_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_samtools' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f9f04a0472441a8d98331fc909defa24d3a7bb82 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-samtools: + build: . + image: mcp-samtools:latest + container_name: mcp-samtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=samtools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..863d9f9be5842148dc7d8b005e221928749232c5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - samtools + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_samtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d67440809be85f6d1dfadf357bbed328e43b193d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install scarches via conda (e.g., from bioconda) +RUN conda install -c bioconda scarches -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY scarches_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/scarches_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/scarches_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/app/__pycache__/scarches_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/app/__pycache__/scarches_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..290252061083e9b52ff94ef79beecf06469c0370 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/app/__pycache__/scarches_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/app/scarches_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/app/scarches_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eb4c0455aa0bebb00fbcc90751f2653e6a0dd699 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/app/scarches_server.py @@ -0,0 +1,361 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Dict, Any, Optional + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# MCP decorator is not defined here, but the functions are structured +# as if it were present (e.g., @mcp.tool()). + +def _run_scarches_command(cmd: List[str], output_path: Path) -> Dict[str, Any]: + """ + A helper function to execute scarches commands, handle errors, and + return a structured output. + """ + command_str = " ".join(cmd) + logger.info(f"Executing command: {command_str}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] if output_path.exists() else [], + } + except FileNotFoundError: + logger.error("Error: 'python' executable not found. Make sure Python is in your PATH.") + raise + except subprocess.CalledProcessError as e: + logger.error(f"Command failed with exit code {e.returncode}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise e + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_scarches' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def train_scvi( + adata_path: Path, + model_path: Path, + gpus: str = "0", + n_epochs: int = 400, + learning_rate: float = 1e-3, + batch_size: int = 128, + early_stopping: bool = False, +) -> Dict[str, Any]: + """ + Trains a scVI model using the scarches command-line interface. + + Args: + adata_path: Path to anndata object with raw counts. + model_path: Path where the trained model will be saved. + gpus: String specifying which GPUs to use (e.g., '0,1'). + n_epochs: Number of epochs for training. + learning_rate: Learning rate for training. + batch_size: Batch size for training. + early_stopping: If True, enables early stopping. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + if not adata_path.is_file(): + raise FileNotFoundError(f"Input anndata file not found: {adata_path}") + if not model_path.parent.exists(): + model_path.parent.mkdir(parents=True, exist_ok=True) + logger.info(f"Created output directory: {model_path.parent}") + if n_epochs <= 0: + raise ValueError("n_epochs must be a positive integer.") + if batch_size <= 0: + raise ValueError("batch_size must be a positive integer.") + + cmd = [ + "python", "-m", "scarches", "train-scvi", + str(adata_path), + str(model_path), + "--gpus", gpus, + "--n_epochs", str(n_epochs), + "--learning_rate", str(learning_rate), + "--batch_size", str(batch_size), + ] + if early_stopping: + cmd.append("--early_stopping") + + return _run_scarches_command(cmd, model_path) + +@mcp.tool() +def train_scanvi( + adata_path: Path, + model_path: Path, + labels_key: str, + unlabeled_category: str, + gpus: str = "0", + n_epochs_unsupervised: int = 400, + n_epochs_semisupervised: int = 400, + lr_unsupervised: float = 1e-3, + lr_semisupervised: float = 1e-3, + batch_size: int = 128, + early_stopping: bool = False, +) -> Dict[str, Any]: + """ + Trains a scANVI model using the scarches command-line interface. + + Args: + adata_path: Path to anndata object with raw counts. + model_path: Path where the trained model will be saved. + labels_key: Key in adata.obs for cell type labels. + unlabeled_category: Value in adata.obs[labels_key] for unlabeled cells. + gpus: String specifying which GPUs to use (e.g., '0,1'). + n_epochs_unsupervised: Number of epochs for unsupervised training. + n_epochs_semisupervised: Number of epochs for semi-supervised training. + lr_unsupervised: Learning rate for unsupervised training. + lr_semisupervised: Learning rate for semi-supervised training. + batch_size: Batch size for training. + early_stopping: If True, enables early stopping. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + if not adata_path.is_file(): + raise FileNotFoundError(f"Input anndata file not found: {adata_path}") + if not model_path.parent.exists(): + model_path.parent.mkdir(parents=True, exist_ok=True) + logger.info(f"Created output directory: {model_path.parent}") + + cmd = [ + "python", "-m", "scarches", "train-scanvi", + str(adata_path), + str(model_path), + "--labels_key", labels_key, + "--unlabeled_category", unlabeled_category, + "--gpus", gpus, + "--n_epochs_unsupervised", str(n_epochs_unsupervised), + "--n_epochs_semisupervised", str(n_epochs_semisupervised), + "--lr_unsupervised", str(lr_unsupervised), + "--lr_semisupervised", str(lr_semisupervised), + "--batch_size", str(batch_size), + ] + if early_stopping: + cmd.append("--early_stopping") + + return _run_scarches_command(cmd, model_path) + +@mcp.tool() +def train_trvae( + adata_path: Path, + model_path: Path, + condition_key: str, + gpus: str = "0", + n_epochs: int = 400, + learning_rate: float = 1e-3, + batch_size: int = 128, + early_stopping: bool = False, +) -> Dict[str, Any]: + """ + Trains a trVAE model using the scarches command-line interface. + + Args: + adata_path: Path to anndata object with raw counts. + model_path: Path where the trained model will be saved. + condition_key: Key in adata.obs for batch information. + gpus: String specifying which GPUs to use (e.g., '0,1'). + n_epochs: Number of epochs for training. + learning_rate: Learning rate for training. + batch_size: Batch size for training. + early_stopping: If True, enables early stopping. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + if not adata_path.is_file(): + raise FileNotFoundError(f"Input anndata file not found: {adata_path}") + if not model_path.parent.exists(): + model_path.parent.mkdir(parents=True, exist_ok=True) + logger.info(f"Created output directory: {model_path.parent}") + + cmd = [ + "python", "-m", "scarches", "train-trvae", + str(adata_path), + str(model_path), + "--condition_key", condition_key, + "--gpus", gpus, + "--n_epochs", str(n_epochs), + "--learning_rate", str(learning_rate), + "--batch_size", str(batch_size), + ] + if early_stopping: + cmd.append("--early_stopping") + + return _run_scarches_command(cmd, model_path) + +@mcp.tool() +def query_scvi( + adata_path: Path, + ref_model_path: Path, + new_model_path: Path, + gpus: str = "0", + n_epochs: int = 200, + learning_rate: float = 1e-3, + batch_size: int = 128, + early_stopping: bool = False, +) -> Dict[str, Any]: + """ + Maps a query dataset to a reference scVI model. + + Args: + adata_path: Path to query anndata object with raw counts. + ref_model_path: Path to the reference model. + new_model_path: Path where the updated query model will be saved. + gpus: String specifying which GPUs to use (e.g., '0,1'). + n_epochs: Number of epochs for training. + learning_rate: Learning rate for training. + batch_size: Batch size for training. + early_stopping: If True, enables early stopping. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + if not adata_path.is_file(): + raise FileNotFoundError(f"Input query anndata file not found: {adata_path}") + if not ref_model_path.is_dir(): + raise FileNotFoundError(f"Reference model directory not found: {ref_model_path}") + if not new_model_path.parent.exists(): + new_model_path.parent.mkdir(parents=True, exist_ok=True) + logger.info(f"Created output directory: {new_model_path.parent}") + + cmd = [ + "python", "-m", "scarches", "query-scvi", + str(adata_path), + str(ref_model_path), + str(new_model_path), + "--gpus", gpus, + "--n_epochs", str(n_epochs), + "--learning_rate", str(learning_rate), + "--batch_size", str(batch_size), + ] + if early_stopping: + cmd.append("--early_stopping") + + return _run_scarches_command(cmd, new_model_path) + +@mcp.tool() +def query_scanvi( + adata_path: Path, + ref_model_path: Path, + new_model_path: Path, + gpus: str = "0", + n_epochs_unsupervised: int = 200, + n_epochs_semisupervised: int = 100, + lr_unsupervised: float = 1e-3, + lr_semisupervised: float = 1e-3, + batch_size: int = 128, + early_stopping: bool = False, +) -> Dict[str, Any]: + """ + Maps a query dataset to a reference scANVI model. + + Args: + adata_path: Path to query anndata object with raw counts. + ref_model_path: Path to the reference model. + new_model_path: Path where the updated query model will be saved. + gpus: String specifying which GPUs to use (e.g., '0,1'). + n_epochs_unsupervised: Number of epochs for unsupervised training. + n_epochs_semisupervised: Number of epochs for semi-supervised training. + lr_unsupervised: Learning rate for unsupervised training. + lr_semisupervised: Learning rate for semi-supervised training. + batch_size: Batch size for training. + early_stopping: If True, enables early stopping. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + if not adata_path.is_file(): + raise FileNotFoundError(f"Input query anndata file not found: {adata_path}") + if not ref_model_path.is_dir(): + raise FileNotFoundError(f"Reference model directory not found: {ref_model_path}") + if not new_model_path.parent.exists(): + new_model_path.parent.mkdir(parents=True, exist_ok=True) + logger.info(f"Created output directory: {new_model_path.parent}") + + cmd = [ + "python", "-m", "scarches", "query-scanvi", + str(adata_path), + str(ref_model_path), + str(new_model_path), + "--gpus", gpus, + "--n_epochs_unsupervised", str(n_epochs_unsupervised), + "--n_epochs_semisupervised", str(n_epochs_semisupervised), + "--lr_unsupervised", str(lr_unsupervised), + "--lr_semisupervised", str(lr_semisupervised), + "--batch_size", str(batch_size), + ] + if early_stopping: + cmd.append("--early_stopping") + + return _run_scarches_command(cmd, new_model_path) + +@mcp.tool() +def query_trvae( + adata_path: Path, + ref_model_path: Path, + new_model_path: Path, + condition_key: str, + gpus: str = "0", + n_epochs: int = 200, + learning_rate: float = 1e-3, + batch_size: int = 128, + early_stopping: bool = False, +) -> Dict[str, Any]: + """ + Maps a query dataset to a reference trVAE model. + + Args: + adata_path: Path to query anndata object with raw counts. + ref_model_path: Path to the reference model. + new_model_path: Path where the updated query model will be saved. + condition_key: Key in adata.obs for batch information. + gpus: String specifying which GPUs to use (e.g., '0,1'). + n_epochs: Number of epochs for training. + learning_rate: Learning rate for training. + batch_size: Batch size for training. + early_stopping: If True, enables early stopping. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + if not adata_path.is_file(): + raise FileNotFoundError(f"Input query anndata file not found: {adata_path}") + if not ref_model_path.is_dir(): + raise FileNotFoundError(f"Reference model directory not found: {ref_model_path}") + if not new_model_path.parent.exists(): + new_model_path.parent.mkdir(parents=True, exist_ok=True) + logger.info(f"Created output directory: {new_model_path.parent}") + + cmd = [ + "python", "-m", "scarches", "query-trvae", + str(adata_path), + str(ref_model_path), + str(new_model_path), + "--condition_key", condition_key, + "--gpus", gpus, + "--n_epochs", str(n_epochs), + "--learning_rate", str(learning_rate), + "--batch_size", str(batch_size), + ] + if early_stopping: + cmd.append("--early_stopping") + + return _run_scarches_command(cmd, new_model_path) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/app/scarches_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/app/scarches_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d0fbf26f97e61de9b637b4b49aefde6216861f53 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/app/scarches_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_scarches/app/scarches_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_scarches' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..36515829bd5c93102752c1a043532a508bcab763 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-scarches: + build: . + image: mcp-scarches:latest + container_name: mcp-scarches + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=scarches + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ae141f0d6db963f6b50ae1249b206c468ca6d98 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - scarches + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scarches/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..951b1c9c12b9a51375afc80056f842c8211e1a93 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install sccaf via conda (e.g., from bioconda) +RUN conda install -c bioconda sccaf -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY sccaf_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/sccaf_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/sccaf_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/app/__pycache__/sccaf_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/app/__pycache__/sccaf_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52c00c1bd116343aa46953933563479de788c0c6 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/app/__pycache__/sccaf_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/app/sccaf_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/app/sccaf_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2f94928d2f15dd4fd616951b38021a43b761ab0d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/app/sccaf_server.py @@ -0,0 +1,180 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# MCP decorator placeholder. In a real MCP environment, this would be imported. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def sccaf( + input_adata: Path, + output_adata: Path, + self_project: bool = False, + min_acc: float = 0.9, + prefix: str = 'sccaf', + n_jobs: int = 1, + use_rep: str = 'X_pca', + n_features: int = 2000, + n_components: int = 50, + resolution: float = 0.2, + k: int = 15, + reference: Optional[Path] = None, + reference_leiden: str = 'leiden', + reference_cell_type: str = 'cell_type', + reference_embedding: str = 'X_umap', + reference_n_jobs: int = 1, + reference_n_features: int = 2000, + reference_n_components: int = 50, + reference_resolution: float = 0.2, + reference_k: int = 15, + log_file: Optional[Path] = None, + verbose: int = 1, +) -> Dict[str, Any]: + """ + Runs SCCAF (Single-Cell Clustering Assessment Framework) for clustering and cell type identification. + + SCCAF is a tool for automated cell type identification and clustering refinement based on the + self-projection of a dataset. It can also project a query dataset onto a reference. + + Args: + input_adata: Path to the input AnnData object (.h5ad). + output_adata: Path where the output AnnData object (.h5ad) will be saved. + self_project: If True, run in self-projection mode. + min_acc: Minimum accuracy for self-projection. + prefix: Prefix for the column names for the results in the output AnnData. + n_jobs: Number of jobs to run in parallel. + use_rep: The key in `.obsm` for the embedding to use (e.g., 'X_pca'). + n_features: Number of features to use. + n_components: Number of components to use. + resolution: Resolution for Louvain clustering. + k: Number of nearest neighbors. + reference: Path to the reference AnnData object for projection. + reference_leiden: The key in `.obs` for the reference leiden clusters. + reference_cell_type: The key in `.obs` for the reference cell type annotations. + reference_embedding: The key in `.obsm` for the reference embedding. + reference_n_jobs: Number of jobs to run in parallel for the reference analysis. + reference_n_features: Number of features to use for the reference. + reference_n_components: Number of components to use for the reference. + reference_resolution: Resolution for Louvain for the reference. + reference_k: Number of nearest neighbors for the reference. + log_file: Optional path to a file for logging output. + verbose: Verbosity level (e.g., 0 for silent, 1 for info). + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_adata.is_file(): + raise FileNotFoundError(f"Input file not found: {input_adata}") + if reference and not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + + # --- Output Directory Handling --- + output_adata.parent.mkdir(parents=True, exist_ok=True) + if log_file: + log_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Parameter Value Validation --- + if not (0.0 <= min_acc <= 1.0): + raise ValueError("min_acc must be between 0.0 and 1.0") + if n_jobs <= 0: + raise ValueError("n_jobs must be a positive integer") + if n_features <= 0: + raise ValueError("n_features must be a positive integer") + if n_components <= 0: + raise ValueError("n_components must be a positive integer") + if resolution <= 0: + raise ValueError("resolution must be a positive float") + if k <= 0: + raise ValueError("k must be a positive integer") + if verbose < 0: + raise ValueError("verbose must be a non-negative integer") + + # --- Command Construction --- + cmd = [ + "sccaf", + "-i", str(input_adata), + "-o", str(output_adata), + "--min-acc", str(min_acc), + "--prefix", prefix, + "--n-jobs", str(n_jobs), + "--use-rep", use_rep, + "--n-features", str(n_features), + "--n-components", str(n_components), + "--resolution", str(resolution), + "--k", str(k), + "--verbose", str(verbose), + ] + + if self_project: + cmd.append("--self-project") + + if reference: + if reference_n_jobs <= 0: + raise ValueError("reference_n_jobs must be a positive integer") + if reference_n_features <= 0: + raise ValueError("reference_n_features must be a positive integer") + if reference_n_components <= 0: + raise ValueError("reference_n_components must be a positive integer") + if reference_resolution <= 0: + raise ValueError("reference_resolution must be a positive float") + if reference_k <= 0: + raise ValueError("reference_k must be a positive integer") + + cmd.extend([ + "--reference", str(reference), + "--reference-leiden", reference_leiden, + "--reference-cell-type", reference_cell_type, + "--reference-embedding", reference_embedding, + "--reference-n-jobs", str(reference_n_jobs), + "--reference-n-features", str(reference_n_features), + "--reference-n-components", str(reference_n_components), + "--reference-resolution", str(reference_resolution), + "--reference-k", str(reference_k), + ]) + + if log_file: + cmd.extend(["--log-file", str(log_file)]) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'sccaf' command not found. Make sure the tool is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + output_files: List[str] = [str(output_adata)] + if log_file and log_file.exists(): + output_files.append(str(log_file)) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/app/sccaf_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/app/sccaf_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5f09b1779fcffbd485cefab31fb42c47a8275e39 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/app/sccaf_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_sccaf/app/sccaf_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_sccaf' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6068a48b1fd1b217fd92ff7a691d6ed4a3c02d61 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-sccaf: + build: . + image: mcp-sccaf:latest + container_name: mcp-sccaf + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=sccaf + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..629ed66308b69d792273a7db85a5e52aac46a7a6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - sccaf + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sccaf/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b9e2e0d3e23d257b1b03a5e33d938976fc0aba2c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install scirpy via conda (e.g., from bioconda) +RUN conda install -c bioconda scirpy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY scirpy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/scirpy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/scirpy_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/app/__pycache__/scirpy_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/app/__pycache__/scirpy_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..334fd20bff14b65e2361c144ad0194d37fa73019 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/app/__pycache__/scirpy_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/app/scirpy_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/app/scirpy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..28f75a481d4766eb7d6dae6876331447121f4e44 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/app/scirpy_server.py @@ -0,0 +1,341 @@ +import logging +import subprocess +import tempfile +from pathlib import Path +from typing import Literal, Optional, Sequence, Tuple + +# Set up logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# MCP-related decorator stub +class mcp: + @staticmethod + def tool(func): + return func + +try: + import anndata + import scanpy as sc + import scirpy as ir +except ImportError: + logger.error("Scirpy or its dependencies (scanpy, anndata) are not installed. Please install them using 'pip install scirpy'.") + # Define dummy functions if imports fail, to allow file parsing + def dummy_decorator(func): + def wrapper(*args, **kwargs): + raise ImportError("Scirpy or its dependencies are not installed.") + return wrapper + mcp.tool = dummy_decorator + + +@mcp.tool +def read_10x_vdj( + filtered_contig_annotations_path: Path, + filtered_contig_path: Optional[Path] = None, + gex_path: Optional[Path] = None, +) -> dict: + """ + Reads V(D)J data from 10x Genomics Cell Ranger. + + This function reads `filtered_contig_annotations.csv` and optionally + `filtered_contigs.fasta` and a GEX matrix. + + Args: + filtered_contig_annotations_path: Path to the `filtered_contig_annotations.csv` file. + filtered_contig_path: Path to the `filtered_contig.fasta` file. + gex_path: Path to the GEX matrix in h5ad format. If provided, the IR data will be matched + to the GEX data. + + Returns: + A dictionary containing the path to the output AnnData object file. + """ + if not filtered_contig_annotations_path.is_file(): + raise FileNotFoundError(f"Input file not found: {filtered_contig_annotations_path}") + if filtered_contig_path and not filtered_contig_path.is_file(): + raise FileNotFoundError(f"Input file not found: {filtered_contig_path}") + if gex_path and not gex_path.is_file(): + raise FileNotFoundError(f"Input file not found: {gex_path}") + + output_dir = tempfile.mkdtemp() + output_path = Path(output_dir) / "ir_anndata.h5ad" + + command_str = f"ir.io.read_10x_vdj(path='{filtered_contig_annotations_path.parent}'" + if gex_path: + command_str += f", gex_path='{gex_path}'" + command_str += ")" + + try: + adata_ir = ir.io.read_10x_vdj( + path=filtered_contig_annotations_path.parent, + filtered_contig_path=filtered_contig_path, + gex_path=gex_path, + ) + adata_ir.write_h5ad(output_path) + + return { + "command_executed": command_str, + "stdout": "Successfully read 10x VDJ data and created AnnData object.", + "stderr": "", + "output_files": [str(output_path)], + } + except Exception as e: + return { + "command_executed": command_str, + "stdout": "", + "stderr": f"An error occurred while running scirpy.io.read_10x_vdj: {e}", + "output_files": [], + } + + +@mcp.tool +def read_airr( + airr_rearrangement_path: Path, +) -> dict: + """ + Reads data from AIRR-compliant files. + + This function reads data from a TSV file compliant with the AIRR Rearrangement schema. + + Args: + airr_rearrangement_path: Path to the AIRR Rearrangement TSV file. + + Returns: + A dictionary containing the path to the output AnnData object file. + """ + if not airr_rearrangement_path.is_file(): + raise FileNotFoundError(f"Input file not found: {airr_rearrangement_path}") + + output_dir = tempfile.mkdtemp() + output_path = Path(output_dir) / "ir_anndata.h5ad" + command_str = f"ir.io.read_airr(path='{airr_rearrangement_path}')" + + try: + adata_ir = ir.io.read_airr(airr_rearrangement_path) + adata_ir.write_h5ad(output_path) + + return { + "command_executed": command_str, + "stdout": "Successfully read AIRR data and created AnnData object.", + "stderr": "", + "output_files": [str(output_path)], + } + except Exception as e: + return { + "command_executed": command_str, + "stdout": "", + "stderr": f"An error occurred while running scirpy.io.read_airr: {e}", + "output_files": [], + } + + +@mcp.tool +def clonotypes( + anndata_path: Path, + groupby: Optional[str] = None, + key_added: str = "clonotype", + receptor_arms: Literal["TRA", "TRB", "TRD", "TRG", "IGH", "IGK", "IGL", "all", "any"] = "all", + dual_ir: Literal["primary_only", "all", "any"] = "primary_only", + same_v_gene: bool = True, + sequence: Literal["cdr3", "junction", "cdr3_aa", "junction_aa"] = "cdr3", + metric: Literal["identity", "levenshtein", "hamming", "custom"] = "identity", + cutoff: int = 0, + n_jobs: Optional[int] = None, +) -> dict: + """ + Define clonotypes based on sequence identity or similarity. + + This is the central function of scirpy. It defines clonotypes based on the similarity + of immune receptor sequences. + + Args: + anndata_path: Path to the AnnData object file containing IR information. + groupby: A column in `adata.obs` that will be used to define groups. + Clonotype definition will be performed independently for each group. + key_added: Key under which the clonotype annotation will be stored in `adata.obs`. + receptor_arms: Which receptor arms to consider for clonotype definition. + dual_ir: How to handle cells with dual IR. + same_v_gene: If `True`, clonotypes are required to have the same V-gene. + sequence: The sequence to be used for distance calculation. + metric: The distance metric to use. + cutoff: The distance cutoff for clonotypes. For identity, this must be 0. + n_jobs: Number of jobs to use for parallel computing. + + Returns: + A dictionary containing the path to the updated AnnData object file. + """ + if not anndata_path.is_file(): + raise FileNotFoundError(f"Input file not found: {anndata_path}") + + output_dir = tempfile.mkdtemp() + output_path = Path(output_dir) / "clonotypes_anndata.h5ad" + + groupby_list = [groupby] if groupby else None + + command_str = ( + f"ir.tl.clonotypes(adata, groupby={groupby_list}, key_added='{key_added}', " + f"receptor_arms='{receptor_arms}', dual_ir='{dual_ir}', same_v_gene={same_v_gene}, " + f"sequence='{sequence}', metric='{metric}', cutoff={cutoff}, n_jobs={n_jobs})" + ) + + try: + adata = sc.read_h5ad(anndata_path) + + # The function modifies adata in place, so we work on the loaded object. + ir.tl.clonotypes( + adata, + groupby=groupby_list, + key_added=key_added, + receptor_arms=receptor_arms, + dual_ir=dual_ir, + same_v_gene=same_v_gene, + sequence=sequence, + metric=metric, + cutoff=cutoff, + n_jobs=n_jobs, + ) + + adata.write_h5ad(output_path) + + return { + "command_executed": command_str, + "stdout": f"Successfully defined clonotypes and saved to '{key_added}' column.", + "stderr": "", + "output_files": [str(output_path)], + } + except Exception as e: + return { + "command_executed": command_str, + "stdout": "", + "stderr": f"An error occurred while running scirpy.tl.clonotypes: {e}", + "output_files": [], + } + + +@mcp.tool +def clonal_expansion( + anndata_path: Path, + target_col: str = "clonotype", + expanded_in: Optional[str] = None, + key_added: str = "clonal_expansion", + inplace: bool = True, # Note: MCP wrapper always saves to a new file +) -> dict: + """ + Calculates the clonal expansion. + + Adds a column to `adata.obs` with the number of cells in a clonotype. + + Args: + anndata_path: Path to the AnnData object file with clonotype information. + target_col: The column in `adata.obs` containing the clonotype information. + expanded_in: If specified, a column in `adata.obs` that defines groups for expansion. + key_added: Key under which the clonal expansion data will be stored. + + Returns: + A dictionary containing the path to the updated AnnData object file. + """ + if not anndata_path.is_file(): + raise FileNotFoundError(f"Input file not found: {anndata_path}") + + output_dir = tempfile.mkdtemp() + output_path = Path(output_dir) / "expansion_anndata.h5ad" + + command_str = ( + f"ir.tl.clonal_expansion(adata, target_col='{target_col}', " + f"expanded_in={expanded_in}, key_added='{key_added}')" + ) + + try: + adata = sc.read_h5ad(anndata_path) + + ir.tl.clonal_expansion( + adata, + target_col=target_col, + expanded_in=expanded_in, + key_added=key_added, + inplace=True, + ) + + adata.write_h5ad(output_path) + + return { + "command_executed": command_str, + "stdout": f"Successfully calculated clonal expansion and saved to '{key_added}' column.", + "stderr": "", + "output_files": [str(output_path)], + } + except Exception as e: + return { + "command_executed": command_str, + "stdout": "", + "stderr": f"An error occurred while running scirpy.tl.clonal_expansion: {e}", + "output_files": [], + } + + +@mcp.tool +def clonotype_network( + anndata_path: Path, + color: Optional[str] = None, + basis: str = "clonotype_network", + layout: Literal["fr", "fa", "kk", "drl", "lgl", "rt", "rt_circular"] = "fr", + size_key: str = "clonotype_size", + output_format: Literal["png", "pdf", "svg"] = "png", +) -> dict: + """ + Visualize the clonotype network. + + Requires running `scirpy.tl.clonotype_network` on the AnnData object first to compute the layout. + This tool will compute the layout and then generate the plot. + + Args: + anndata_path: Path to the AnnData object file with clonotype information. + color: A column in `adata.obs` to color the nodes by. + basis: The key in `adata.obsm` where the network layout is stored. + layout: The layout algorithm to use for the network. + size_key: The key in `adata.obs` that specifies the size of the nodes. + output_format: The file format for the output plot. + + Returns: + A dictionary containing the path to the output plot file. + """ + if not anndata_path.is_file(): + raise FileNotFoundError(f"Input file not found: {anndata_path}") + + output_dir = tempfile.mkdtemp() + output_plot_path = Path(output_dir) / f"clonotype_network.{output_format}" + + command_str_layout = f"ir.tl.clonotype_network(adata, layout='{layout}', basis='{basis}')" + command_str_plot = ( + f"ir.pl.clonotype_network(adata, color='{color}', basis='{basis}', " + f"layout='{layout}', size_key='{size_key}', save='{output_plot_path}')" + ) + + try: + adata = sc.read_h5ad(anndata_path) + + # Step 1: Compute the network layout + ir.tl.clonotype_network(adata, layout=layout, basis=basis) + + # Step 2: Generate and save the plot + ir.pl.clonotype_network( + adata, + color=color, + basis=basis, + layout=layout, + size_key=size_key, + save=str(output_plot_path), + ) + + return { + "command_executed": f"{command_str_layout}; {command_str_plot}", + "stdout": f"Successfully generated clonotype network plot.", + "stderr": "", + "output_files": [str(output_plot_path)], + } + except Exception as e: + return { + "command_executed": f"{command_str_layout}; {command_str_plot}", + "stdout": "", + "stderr": f"An error occurred while running scirpy.pl.clonotype_network: {e}", + "output_files": [], + } diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/app/scirpy_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/app/scirpy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e8aa6ecd089e633a5219197317dd75832a59857f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/app/scirpy_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_scirpy/app/scirpy_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_scirpy' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8855eaf7923db329765217b59b6fc373d08b222e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-scirpy: + build: . + image: mcp-scirpy:latest + container_name: mcp-scirpy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=scirpy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ba6835d1e1086c0ab0eedc4abe787d1252ccd577 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - scirpy + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scirpy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6183bc9469cef3ee49858dcda6a3046d3ce37061 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install scvi via conda (e.g., from bioconda) +RUN conda install -c bioconda scvi -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY scvi_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/scvi_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/scvi_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/app/__pycache__/scvi_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/app/__pycache__/scvi_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c30f2f433f2814c27a89899eae0cec90893ea51b Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/app/__pycache__/scvi_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/app/scvi_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/app/scvi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f943eafda2304305525b748397f064926808b417 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/app/scvi_server.py @@ -0,0 +1,385 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List +import sys +import io +import contextlib + +# Mock decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def scvi_data_read_h5ad( + filename: Path, + backed: bool = False +) -> Dict: + """ + Reads .h5ad-formatted hdf5 file. + + This function wraps scvi.data.read_h5ad to load an AnnData object. + """ + if not filename.exists(): + raise FileNotFoundError(f"Input file not found: {filename}") + + output_h5ad_path = Path(tempfile.mkdtemp()) / "output.h5ad" + + # Since scvi is a library, we call its functions directly + # instead of using subprocess. + command_list = [ + "python", "-c", + f"import scvi; adata = scvi.data.read_h5ad('{filename}', backed={backed}); adata.write_h5ad('{output_h5ad_path}')" + ] + command_executed = " ".join(command_list) + + try: + # We execute the command in a separate python process to isolate dependencies + # and capture output accurately. + process = subprocess.run( + command_list, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"anndata_object": str(output_h5ad_path)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "scvi-tools command failed", + "return_code": e.returncode + } + +@mcp.tool +def scvi_data_read_csv( + filename: Path, + delimiter: str = ',', + first_column_names: bool = False, + dtype: str = 'float32' +) -> Dict: + """ + Read .csv file and return AnnData object. + + This function wraps scvi.data.read_csv. + """ + if not filename.exists(): + raise FileNotFoundError(f"Input file not found: {filename}") + + output_h5ad_path = Path(tempfile.mkdtemp()) / "output.h5ad" + + command_list = [ + "python", "-c", + ( + f"import scvi; " + f"adata = scvi.data.read_csv('{filename}', delimiter='{delimiter}', " + f"first_column_names={first_column_names}, dtype='{dtype}'); " + f"adata.write_h5ad('{output_h5ad_path}')" + ) + ] + command_executed = " ".join(command_list) + + try: + process = subprocess.run( + command_list, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"anndata_object": str(output_h5ad_path)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "scvi-tools command failed", + "return_code": e.returncode + } + +@mcp.tool +def scvi_data_read_loom( + filename: Path, + sparse: bool = True, + cleanup: bool = False, + x_name: str = 'X', + obs_names: str = 'obs_names', + obsm_names: Optional[List[str]] = None, + var_names: str = 'var_names', + varm_names: Optional[List[str]] = None, + uns_names: Optional[List[str]] = None, +) -> Dict: + """ + Read .loom file and returns AnnData object. + + This function wraps scvi.data.read_loom. + """ + if not filename.exists(): + raise FileNotFoundError(f"Input file not found: {filename}") + + output_h5ad_path = Path(tempfile.mkdtemp()) / "output.h5ad" + + # Constructing the python command string carefully + obsm_names_str = f"['{','.join(obsm_names)}']" if obsm_names else "None" + varm_names_str = f"['{','.join(varm_names)}']" if varm_names else "None" + uns_names_str = f"['{','.join(uns_names)}']" if uns_names else "None" + + py_command = ( + f"import scvi; " + f"adata = scvi.data.read_loom('{filename}', sparse={sparse}, cleanup={cleanup}, " + f"x_name='{x_name}', obs_names='{obs_names}', obsm_names={obsm_names_str}, " + f"var_names='{var_names}', varm_names={varm_names_str}, uns_names={uns_names_str}); " + f"adata.write_h5ad('{output_h5ad_path}')" + ) + + command_list = ["python", "-c", py_command] + command_executed = " ".join(command_list) + + try: + process = subprocess.run( + command_list, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"anndata_object": str(output_h5ad_path)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "scvi-tools command failed", + "return_code": e.returncode + } + +@mcp.tool +def scvi_data_read_text( + path: Path, + delimiter: Optional[str] = None, + first_column_names: bool = False, + dtype: str = 'float32' +) -> Dict: + """ + Read .txt, .tsv or .mtx file and return AnnData object. + + This function wraps scvi.data.read_text. + """ + if not path.exists(): + raise FileNotFoundError(f"Input path not found: {path}") + + output_h5ad_path = Path(tempfile.mkdtemp()) / "output.h5ad" + + delimiter_str = f"'{delimiter}'" if delimiter else "None" + + py_command = ( + f"import scvi; " + f"adata = scvi.data.read_text('{path}', delimiter={delimiter_str}, " + f"first_column_names={first_column_names}, dtype='{dtype}'); " + f"adata.write_h5ad('{output_h5ad_path}')" + ) + + command_list = ["python", "-c", py_command] + command_executed = " ".join(command_list) + + try: + process = subprocess.run( + command_list, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"anndata_object": str(output_h5ad_path)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "scvi-tools command failed", + "return_code": e.returncode + } + +@mcp.tool +def scvi_data_poisson_gene_selection( + adata_path: Path, + n_top_genes: int = 4000, + n_samples: int = 10000, + batch_key: Optional[str] = None, + min_cells: int = 10, + min_counts: int = 10 +) -> Dict: + """ + Performs Poisson gene selection. + + This function wraps scvi.data.poisson_gene_selection, which ranks genes by how well they fit a simple Poisson model. + The returned AnnData object is subsetted to the selected genes. + """ + if not adata_path.exists(): + raise FileNotFoundError(f"Input AnnData file not found: {adata_path}") + + output_h5ad_path = Path(tempfile.mkdtemp()) / "filtered_anndata.h5ad" + + batch_key_str = f"'{batch_key}'" if batch_key else "None" + + py_command = ( + f"import scvi; import anndata; " + f"adata = anndata.read_h5ad('{adata_path}'); " + f"adata_filtered = scvi.data.poisson_gene_selection(adata, n_top_genes={n_top_genes}, " + f"n_samples={n_samples}, batch_key={batch_key_str}, min_cells={min_cells}, min_counts={min_counts}); " + f"adata_filtered.write_h5ad('{output_h5ad_path}')" + ) + + command_list = ["python", "-c", py_command] + command_executed = " ".join(command_list) + + try: + process = subprocess.run( + command_list, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"filtered_anndata_object": str(output_h5ad_path)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "scvi-tools command failed", + "return_code": e.returncode + } + +@mcp.tool +def scvi_data_organize_cite_seq_10x( + adata_path: Path, + protein_expression_path: Path, + protein_names_path: Path +) -> Dict: + """ + Organizes CITE-seq data from 10x Genomics into a single AnnData object. + + This function wraps scvi.data.organize_cite_seq_10x. + """ + if not adata_path.exists(): + raise FileNotFoundError(f"Input AnnData file not found: {adata_path}") + if not protein_expression_path.exists(): + raise FileNotFoundError(f"Protein expression file not found: {protein_expression_path}") + if not protein_names_path.exists(): + raise FileNotFoundError(f"Protein names file not found: {protein_names_path}") + + output_h5ad_path = Path(tempfile.mkdtemp()) / "organized_cite_seq.h5ad" + + py_command = ( + f"import scvi; import anndata; " + f"adata = anndata.read_h5ad('{adata_path}'); " + f"adata_cite = scvi.data.organize_cite_seq_10x(adata, '{protein_expression_path}', '{protein_names_path}'); " + f"adata_cite.write_h5ad('{output_h5ad_path}')" + ) + + command_list = ["python", "-c", py_command] + command_executed = " ".join(command_list) + + try: + process = subprocess.run( + command_list, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"organized_anndata_object": str(output_h5ad_path)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "scvi-tools command failed", + "return_code": e.returncode + } + +@mcp.tool +def scvi_data_organize_multiome_anndatas( + adata_gex_path: Path, + adata_atac_path: Path +) -> Dict: + """ + Organizes 10x Multiome GEX and ATAC AnnData objects. + + This function wraps scvi.data.organize_multiome_anndatas. It ensures the two AnnData + objects have the same cells and adds a 'modality' column. + """ + if not adata_gex_path.exists(): + raise FileNotFoundError(f"GEX AnnData file not found: {adata_gex_path}") + if not adata_atac_path.exists(): + raise FileNotFoundError(f"ATAC AnnData file not found: {adata_atac_path}") + + output_dir = Path(tempfile.mkdtemp()) + output_gex_path = output_dir / "organized_gex.h5ad" + output_atac_path = output_dir / "organized_atac.h5ad" + + py_command = ( + f"import scvi; import anndata; " + f"adata_gex = anndata.read_h5ad('{adata_gex_path}'); " + f"adata_atac = anndata.read_h5ad('{adata_atac_path}'); " + f"gex_out, atac_out = scvi.data.organize_multiome_anndatas(adata_gex, adata_atac); " + f"gex_out.write_h5ad('{output_gex_path}'); " + f"atac_out.write_h5ad('{output_atac_path}'); " + ) + + command_list = ["python", "-c", py_command] + command_executed = " ".join(command_list) + + try: + process = subprocess.run( + command_list, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": { + "organized_gex_anndata": str(output_gex_path), + "organized_atac_anndata": str(output_atac_path) + } + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "scvi-tools command failed", + "return_code": e.returncode + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/app/scvi_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/app/scvi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f24cddfeb4c75ea11298a457cb44219a51fea9d2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/app/scvi_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_scvi/app/scvi_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_scvi' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dd06a8e8da0ff3387fa3b7a56129c7b376b53575 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-scvi: + build: . + image: mcp-scvi:latest + container_name: mcp-scvi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=scvi + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8b780ce465366545f9fbfd3c030e5fee0c4fd9e5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - scvi + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scvi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..82aaaf0b0b7550d0b7665ef4caf05988dfd4522a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install seqkit via conda (e.g., from bioconda) +RUN conda install -c bioconda seqkit -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/seqkit_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/seqkit_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/seqkit_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/__pycache__/seqkit_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/__pycache__/seqkit_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff8280e7b471be3e09e7bd04727d5c5b0156b318 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/__pycache__/seqkit_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/seqkit_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/seqkit_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c496cf3ed5342f1994aa189dd29441a381d52e2a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/seqkit_server.py @@ -0,0 +1,693 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import tempfile + +def _run_seqkit(args: List[str]): + """Helper function to execute seqkit commands and handle errors.""" + try: + result = subprocess.run( + ["seqkit"] + args, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"seqkit {' '.join(args)}", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"seqkit {' '.join(args)}", + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "error_message": str(e) + } + +def _validate_files(files: List[str]): + """Validates that input files exist.""" + for f in files: + if not Path(f).exists(): + raise FileNotFoundError(f"Input file not found: {f}") + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_seqkit' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def seqkit_stats( + input_files: List[str], + all_stats: bool = False, + tabular: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Simple statistics of FASTA/Q files. + + :param input_files: List of FASTA/Q files to analyze. + :param all_stats: Show all statistics including quartiles and N50. + :param tabular: Output in machine-friendly tabular format. + :param threads: Number of CPUs to use. + :param out_file: Output file path. + """ + _validate_files(input_files) + args = ["stats"] + if all_stats: args.append("-a") + if tabular: args.append("-T") + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_seq( + input_files: List[str], + name: bool = False, + seq: bool = False, + reverse: bool = False, + complement: bool = False, + min_len: int = -1, + max_len: int = -1, + remove_gaps: bool = False, + lower_case: bool = False, + upper_case: bool = False, + dna2rna: bool = False, + rna2dna: bool = False, + validate_seq: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Transform sequences (extract ID, filter by length, remove gaps, reverse complement...). + + :param input_files: List of FASTA/Q files. + :param name: Only print names. + :param seq: Only print sequences. + :param reverse: Reverse sequence. + :param complement: Complement sequence. + :param min_len: Minimum sequence length to keep (-1 to disable). + :param max_len: Maximum sequence length to keep (-1 to disable). + :param remove_gaps: Remove gaps. + :param lower_case: Print sequences in lower case. + :param upper_case: Print sequences in upper case. + :param dna2rna: DNA to RNA. + :param rna2dna: RNA to DNA. + :param validate_seq: Validate sequences. + """ + _validate_files(input_files) + args = ["seq"] + if name: args.append("-n") + if seq: args.append("-s") + if reverse: args.append("-r") + if complement: args.append("-p") + if min_len >= 0: args.extend(["-m", str(min_len)]) + if max_len >= 0: args.extend(["-M", str(max_len)]) + if remove_gaps: args.append("-g") + if lower_case: args.append("-l") + if upper_case: args.append("-u") + if dna2rna: args.append("--dna2rna") + if rna2dna: args.append("--rna2dna") + if validate_seq: args.append("-v") + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_grep( + input_files: List[str], + pattern: Optional[str] = None, + pattern_file: Optional[str] = None, + use_regexp: bool = False, + ignore_case: bool = False, + invert_match: bool = False, + by_name: bool = False, + by_seq: bool = False, + degenerate: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Search sequences by ID/name/sequence/sequence motifs. + + :param pattern: Search pattern (regular expression if use_regexp is True). + :param pattern_file: File containing patterns (one per line). + :param use_regexp: Use regular expression. + :param ignore_case: Ignore case. + :param invert_match: Invert match (grep -v). + :param by_name: Match by full name instead of just ID. + :param by_seq: Search in sequences instead of IDs. + :param degenerate: Pattern contains degenerate bases. + """ + _validate_files(input_files) + args = ["grep"] + if pattern: args.extend(["-p", pattern]) + if pattern_file: + if not Path(pattern_file).exists(): + raise FileNotFoundError(f"Pattern file not found: {pattern_file}") + args.extend(["-f", pattern_file]) + if use_regexp: args.append("-r") + if ignore_case: args.append("-i") + if invert_match: args.append("-v") + if by_name: args.append("-n") + if by_seq: args.append("-s") + if degenerate: args.append("-d") + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_subseq( + input_files: List[str], + region: Optional[str] = None, + gtf: Optional[str] = None, + bed: Optional[str] = None, + feature: Optional[str] = None, + flank: int = 0, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Get subsequences by region/gtf/bed. + + :param region: Region (e.g. 1:10, -100:-1). + :param gtf: GTF file. + :param bed: BED file. + :param feature: Feature type in GTF to extract (e.g. CDS). + :param flank: Flanking sequence length. + """ + _validate_files(input_files) + args = ["subseq"] + if region: args.extend(["-r", region]) + if gtf: args.extend(["--gtf", gtf]) + if bed: args.extend(["--bed", bed]) + if feature: args.extend(["--feature", feature]) + if flank > 0: args.extend(["-f", str(flank)]) + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_fq2fa( + input_files: List[str], + threads: int = 4, + out_file: Optional[str] = None +): + """Convert FASTQ to FASTA.""" + _validate_files(input_files) + args = ["fq2fa"] + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_fx2tab( + input_files: List[str], + length: bool = False, + gc: bool = False, + name: bool = False, + only_id: bool = False, + base_content: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Convert FASTA/Q to tabular format. + + :param length: Print sequence length. + :param gc: Print GC content. + :param name: Print full name instead of ID. + :param only_id: Only print ID. + :param base_content: Print base content (A, C, G, T, N). + """ + _validate_files(input_files) + args = ["fx2tab"] + if length: args.append("-l") + if gc: args.append("-g") + if name: args.append("-n") + if only_id: args.append("-i") + if base_content: args.append("-B") + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_tab2fx( + input_files: List[str], + threads: int = 4, + out_file: Optional[str] = None +): + """Convert tabular format to FASTA/Q format.""" + _validate_files(input_files) + args = ["tab2fx"] + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_translate( + input_files: List[str], + frame: int = 1, + table: int = 1, + trim: bool = False, + clean: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Translate DNA/RNA to protein sequence. + + :param frame: Frame(s) to translate (1, 2, 3, 4, 5, 6 or 0 for all 6 frames). + :param table: Genetic code table ID. + :param trim: Trim stop codon '*' at the end. + :param clean: Transform all non-AA characters to 'X'. + """ + _validate_files(input_files) + args = ["translate"] + args.extend(["-f", str(frame)]) + args.extend(["-l", str(table)]) + if trim: args.append("-T") + if clean: args.append("-c") + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_rmdup( + input_files: List[str], + by_id: bool = False, + by_name: bool = False, + by_seq: bool = False, + ignore_case: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Remove duplicated sequences by ID/name/sequence. + + :param by_id: Remove by ID. + :param by_name: Remove by full name. + :param by_seq: Remove by sequence. + :param ignore_case: Ignore case. + """ + _validate_files(input_files) + args = ["rmdup"] + if by_id: args.append("-n") + if by_name: args.append("-N") + if by_seq: args.append("-s") + if ignore_case: args.append("-i") + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_sample( + input_files: List[str], + number: int = -1, + proportion: float = -1.0, + seed: int = 11, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Sample sequences by number or proportion. + + :param number: Sample by number. + :param proportion: Sample by proportion (0-1). + :param seed: Random seed. + """ + _validate_files(input_files) + args = ["sample"] + if number > 0: args.extend(["-n", str(number)]) + if proportion > 0: args.extend(["-p", str(proportion)]) + args.extend(["-s", str(seed)]) + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_sort( + input_files: List[str], + by_id: bool = False, + by_name: bool = False, + by_seq: bool = False, + by_length: bool = False, + reverse: bool = False, + ignore_case: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Sort sequences by id/name/sequence/length. + + :param by_id: Sort by ID. + :param by_name: Sort by full name. + :param by_seq: Sort by sequence. + :param by_length: Sort by length. + :param reverse: Reverse order. + :param ignore_case: Ignore case. + """ + _validate_files(input_files) + args = ["sort"] + if by_id: args.append("-n") + if by_name: args.append("-N") + if by_seq: args.append("-s") + if by_length: args.append("-l") + if reverse: args.append("-r") + if ignore_case: args.append("-i") + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_split2( + input_files: List[str], + size: int = -1, + parts: int = -1, + out_dir: str = "split_out", + threads: int = 4 +): + """ + Split sequences into files by size or parts (FASTA, PE/SE FASTQ). + + :param size: Split by number of records per file. + :param parts: Split into N parts. + :param out_dir: Output directory. + """ + _validate_files(input_files) + args = ["split2"] + if size > 0: args.extend(["-s", str(size)]) + if parts > 0: args.extend(["-p", str(parts)]) + args.extend(["-O", out_dir]) + + args.extend(["-j", str(threads)]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_locate( + input_files: List[str], + pattern: Optional[str] = None, + pattern_file: Optional[str] = None, + max_mismatch: int = 0, + ignore_case: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Locate subsequences/motifs, mismatch allowed. + + :param pattern: Search pattern. + :param pattern_file: File containing patterns. + :param max_mismatch: Max mismatch. + :param ignore_case: Ignore case. + """ + _validate_files(input_files) + args = ["locate"] + if pattern: args.extend(["-p", pattern]) + if pattern_file: args.extend(["-f", pattern_file]) + args.extend(["-m", str(max_mismatch)]) + if ignore_case: args.append("-i") + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_replace( + input_files: List[str], + pattern: str, + replacement: str, + by_name: bool = False, + by_seq: bool = False, + ignore_case: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Replace name/sequence by regular expression. + + :param pattern: Regular expression pattern. + :param replacement: Replacement string (supports capture groups like $1). + :param by_name: Replace in full name. + :param by_seq: Replace in sequence. + :param ignore_case: Ignore case. + """ + _validate_files(input_files) + args = ["replace", "-p", pattern, "-r", replacement] + if by_name: args.append("-n") + if by_seq: args.append("-s") + if ignore_case: args.append("-i") + + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_faidx( + input_files: List[str], + subsequences: Optional[List[str]] = None, + bed: Optional[str] = None, + out_file: Optional[str] = None +): + """ + Create the FASTA index file and extract subsequences. + + :param input_files: FASTA files. + :param subsequences: List of sequence IDs or regions (e.g. "chr1:1-10"). + :param bed: BED file for extraction. + """ + _validate_files(input_files) + args = ["faidx"] + if bed: args.extend(["--bed", bed]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + if subsequences: args.extend(subsequences) + + return _run_seqkit(args) + +@mcp.tool() +def seqkit_sliding( + input_files: List[str], + step: int = 1, + window: int = 100, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Extract subsequences in sliding windows. + + :param step: Step size. + :param window: Window size. + """ + _validate_files(input_files) + args = ["sliding", "-s", str(step), "-W", str(window)] + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_common( + input_files: List[str], + by_id: bool = True, + by_name: bool = False, + by_seq: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Find common/shared sequences of multiple files by id/name/sequence. + """ + _validate_files(input_files) + args = ["common"] + if by_id: args.append("-n") + if by_name: args.append("-N") + if by_seq: args.append("-s") + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_duplicate( + input_files: List[str], + times: int = 2, + threads: int = 4, + out_file: Optional[str] = None +): + """Duplicate sequences N times.""" + _validate_files(input_files) + args = ["duplicate", "-n", str(times)] + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_head( + input_files: List[str], + number: int = 10, + threads: int = 4, + out_file: Optional[str] = None +): + """Print the first N FASTA/Q records.""" + _validate_files(input_files) + args = ["head", "-n", str(number)] + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_pair( + input_file1: str, + input_file2: str, + out_dir: str = "paired_out", + threads: int = 4 +): + """Match up paired-end reads from two fastq files.""" + _validate_files([input_file1, input_file2]) + args = ["pair", "-1", input_file1, "-2", input_file2, "-O", out_dir] + args.extend(["-j", str(threads)]) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_mutate( + input_files: List[str], + point_mutation: Optional[str] = None, + insertion: Optional[str] = None, + deletion: Optional[str] = None, + threads: int = 4, + out_file: Optional[str] = None +): + """ + Edit sequence (point mutation, insertion, deletion). + Example point_mutation: "1:A" (position 1 to A). + """ + _validate_files(input_files) + args = ["mutate"] + if point_mutation: args.extend(["-p", point_mutation]) + if insertion: args.extend(["-i", insertion]) + if deletion: args.extend(["-d", deletion]) + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_sum( + input_files: List[str], + threads: int = 4 +): + """Compute message digest (MD5/SHA1/SHA256) for all sequences.""" + _validate_files(input_files) + args = ["sum"] + args.extend(["-j", str(threads)]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_bam( + input_files: List[str], + threads: int = 4 +): + """Monitoring and online histograms of BAM record features.""" + _validate_files(input_files) + args = ["bam"] + args.extend(["-j", str(threads)]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_sana( + input_files: List[str], + threads: int = 4, + out_file: Optional[str] = None +): + """Sanitize broken single line FASTQ files.""" + _validate_files(input_files) + args = ["sana"] + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_shuffle( + input_files: List[str], + seed: int = 11, + threads: int = 4, + out_file: Optional[str] = None +): + """Shuffle sequences.""" + _validate_files(input_files) + args = ["shuffle", "-s", str(seed)] + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_convert( + input_files: List[str], + to_sanger: bool = False, + to_illumina: bool = False, + to_solexa: bool = False, + threads: int = 4, + out_file: Optional[str] = None +): + """Convert FASTQ quality encoding between Sanger, Solexa and Illumina.""" + _validate_files(input_files) + args = ["convert"] + if to_sanger: args.append("--to-sanger") + if to_illumina: args.append("--to-illumina") + if to_solexa: args.append("--to-solexa") + args.extend(["-j", str(threads)]) + if out_file: args.extend(["-o", out_file]) + args.extend(input_files) + return _run_seqkit(args) + +@mcp.tool() +def seqkit_version(): + """Print version information.""" + return _run_seqkit(["version"]) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/seqkit_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/seqkit_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e50e295b0858d46c2b9d4038e04272117d0f359d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/app/seqkit_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_seqkit/app/seqkit_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_seqkit' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6599e563d7803861b18844e03a80e89420333996 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-seqkit: + build: . + image: mcp-seqkit:latest + container_name: mcp-seqkit + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=seqkit + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..54a8d4cbeddc452a88fcbb9268b06226008f6a67 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - seqkit + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seqkit/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f4e4b4a46547cee15060efbc75086b222635927d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install simo-omics via conda (e.g., from bioconda) +RUN conda install -c bioconda simo-omics -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/simo-omics_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/simo-omics_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/simo-omics_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/__pycache__/simo-omics_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/__pycache__/simo-omics_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cda9adcc988384f2c01e890c61f73d4c97f37645 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/__pycache__/simo-omics_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/simo-omics_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/simo-omics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe2f64e60fb467ff3ebc68a74a97e28edb3efe9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/simo-omics_server.py @@ -0,0 +1,204 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# The mcp.tool decorator is assumed to be available in the environment. +# To make this code runnable, you would need to install the MCP framework. +# For demonstration, we assume a decorator `@mcp.tool()` exists. +class mcp: + def tool(func): + return func + +@mcp.tool +def run( + spatial_adata_path: Path, + scrna_adata_path: Path, + output_prefix: str, + n_top_genes: int = 3000, + n_pcs: int = 50, + n_neighbors: int = 30, + T: float = 0.01, + beta: float = 1.0, + beta2: float = 1.0, + lambda_g: float = 1.0, + lambda_d: float = 1.0, + lambda_ot: float = 1.0, + epochs: int = 500, + lr: float = 0.001, + w_pc: float = 1.0, + w_ge: float = 1.0, + w_da: float = 1.0, + w_ot: float = 1.0, +) -> dict: + """ + Integrates spatial and scRNA-seq datasets using the SIMO (Spatial Integration of Multi-Omics) library. + + SIMO is a computational method that performs spatial integration of multi-omics single-cell + datasets through probabilistic alignment. This tool wraps the simo-omics Python library. + + Args: + spatial_adata_path: Path to the input spatial AnnData file (.h5ad). + scrna_adata_path: Path to the input single-cell RNA-seq AnnData file (.h5ad). + output_prefix: Prefix for the output files. The main output will be named '{output_prefix}_integrated.h5ad'. + n_top_genes: Number of highly variable genes to use. + n_pcs: Number of principal components to compute. + n_neighbors: Number of neighbors to use for graph construction. + T: Temperature parameter for the model. + beta: Weight for graph regularization. + beta2: Weight for domain adversarial regularization. + lambda_g: Weight for gene expression reconstruction loss. + lambda_d: Weight for domain adversarial loss. + lambda_ot: Weight for optimal transport loss. + epochs: Number of training epochs. + lr: Learning rate for the optimizer. + w_pc: Weight for PC alignment. + w_ge: Weight for gene expression alignment. + w_da: Weight for domain adversarial alignment. + w_ot: Weight for optimal transport alignment. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not spatial_adata_path.is_file(): + raise FileNotFoundError(f"Input spatial AnnData file not found: {spatial_adata_path}") + if not scrna_adata_path.is_file(): + raise FileNotFoundError(f"Input scRNA-seq AnnData file not found: {scrna_adata_path}") + if not output_prefix: + raise ValueError("output_prefix cannot be empty.") + + # Validate numerical parameters + if n_top_genes <= 0: + raise ValueError("n_top_genes must be a positive integer.") + if n_pcs <= 0: + raise ValueError("n_pcs must be a positive integer.") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if epochs <= 0: + raise ValueError("epochs must be a positive integer.") + if lr <= 0: + raise ValueError("lr (learning rate) must be positive.") + if T <= 0: + raise ValueError("T (temperature) must be positive.") + + # Validate non-negative weight parameters + for param_name, param_value in { + "beta": beta, "beta2": beta2, "lambda_g": lambda_g, "lambda_d": lambda_d, + "lambda_ot": lambda_ot, "w_pc": w_pc, "w_ge": w_ge, "w_da": w_da, "w_ot": w_ot + }.items(): + if param_value < 0: + raise ValueError(f"{param_name} must be non-negative.") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + script_path = temp_dir / "run_simo_script.py" + # Define output path in the current working directory + output_adata_path = Path.cwd() / f"{output_prefix}_integrated.h5ad" + + # --- Script Generation --- + # This script will be executed in a separate Python process to isolate dependencies. + # It loads the data, runs the SIMO workflow, and saves the result. + script_content = f""" +import sys +import warnings +import scanpy as sc +import simo + +# Suppress warnings from the library for cleaner output +warnings.filterwarnings('ignore') + +try: + # Load data + spatial_data = sc.read_h5ad(r'{spatial_adata_path.resolve()}') + scrna_data = sc.read_h5ad(r'{scrna_adata_path.resolve()}') + + # Initialize SIMO object + simo_model = simo.SIMO(spatial_data, scrna_data) + + # Preprocess data + simo_model.preprocess( + n_top_genes={n_top_genes}, + n_pcs={n_pcs}, + n_neighbors={n_neighbors} + ) + + # Train the model + simo_model.train( + T={T}, + beta={beta}, + beta2={beta2}, + lambda_g={lambda_g}, + lambda_d={lambda_d}, + lambda_ot={lambda_ot}, + epochs={epochs}, + lr={lr}, + w_pc={w_pc}, + w_ge={w_ge}, + w_da={w_da}, + w_ot={w_ot} + ) + + # Get results and save + integrated_adata = simo_model.get_results() + integrated_adata.write_h5ad(r'{output_adata_path.resolve()}') + + print(f"Successfully integrated data and saved to {{str(output_adata_path.resolve())}}") + +except Exception as e: + print(f"An error occurred during SIMO execution: {{e}}", file=sys.stderr) + sys.exit(1) +""" + with open(script_path, "w") as f: + f.write(script_content) + + # --- Subprocess Execution --- + command = ["python", str(script_path)] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=Path.cwd(), + ) + + if not output_adata_path.is_file(): + # This case is important if the script runs without error but fails to produce the file. + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "error": "SIMO script completed, but the output file was not created.", + "return_code": 1, + "output_files": [] + } + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_adata_path)], + } + except subprocess.CalledProcessError as e: + # This catches errors from within the executed script (e.g., Python exceptions that cause a non-zero exit code) + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "SIMO execution failed with a non-zero exit code.", + "return_code": e.returncode, + "output_files": [] + } + except FileNotFoundError: + # This catches an error if 'python' is not in the system's PATH + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: The 'python' interpreter was not found in the system's PATH.", + "error": "Python interpreter not found.", + "return_code": 1, + "output_files": [] + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/simo-omics_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/simo-omics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa6b131490d023cf4da4cad7e71e97e142a7352 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/app/simo-omics_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_simo-omics/app/simo-omics_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_simo_omics' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dcdd4f34ad0e589c6b405cb49928e5660b93a398 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-simo-omics: + build: . + image: mcp-simo-omics:latest + container_name: mcp-simo-omics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=simo-omics + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..11c88f273b92a5d3816c0683a0489d2d024ca0db --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - simo-omics + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_simo-omics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..04a08af6fa70d29424dbe1c4e61af933b50b481f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install snakemake-wrapper-utils via conda (e.g., from bioconda) +RUN conda install -c bioconda snakemake-wrapper-utils -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/snakemake-wrapper-utils_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/snakemake-wrapper-utils_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/snakemake-wrapper-utils_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/__pycache__/snakemake-wrapper-utils_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/__pycache__/snakemake-wrapper-utils_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa136471237d060e8e3674fb6c21451760f64f40 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/__pycache__/snakemake-wrapper-utils_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/snakemake-wrapper-utils_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/snakemake-wrapper-utils_server.py new file mode 100644 index 0000000000000000000000000000000000000000..29d487e4df4f43946798b50129c442a75d56bd0b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/snakemake-wrapper-utils_server.py @@ -0,0 +1,299 @@ +import subprocess +from typing import Optional, List +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_snakemake_wrapper_utils' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def get_java_opts( + mem_mb: int = 1024, + tmpdir: Optional[str] = None, + java_opts: str = "", +) -> dict: + """ + Construct Java options (e.g., -Xmx, -Djava.io.tmpdir) for bioinformatics tools. + This mimics the logic used in Snakemake wrappers to ensure consistent resource allocation. + + Args: + mem_mb: Total memory allocated in Megabytes. + tmpdir: Path to the temporary directory. + java_opts: Existing Java options to prepend/merge. + """ + if mem_mb <= 0: + return {"error": "mem_mb must be a positive integer"} + + # Constructing the python command to execute the library function + # We simulate the snakemake object structure expected by the library + python_code = f""" +try: + from snakemake_wrapper_utils.java import get_java_opts + class Mock: + pass + snakemake = Mock() + snakemake.resources = {{"mem_mb": {mem_mb}}} + if "{tmpdir}" != "None": + snakemake.resources["tmpdir"] = "{tmpdir}" + snakemake.params = {{"java_opts": "{java_opts}"}} + print(get_java_opts(snakemake)) +except ImportError: + # Fallback logic if library not installed + opts = "{java_opts}" + if "-Xmx" not in opts: + opts += " -Xmx{mem_mb}M" + if "-Djava.io.tmpdir" not in opts and "{tmpdir}" != "None": + opts += " -Djava.io.tmpdir={tmpdir}" + print(opts.strip()) +""" + + try: + result = subprocess.run( + ["python3", "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "snakemake_wrapper_utils.java.get_java_opts", + "stdout": result.stdout.strip(), + "stderr": result.stderr, + "java_opts": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to calculate Java options: {e.stderr}", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def get_samtools_opts( + threads: int = 1, + mem_mb: int = 2048, + extra: str = "", + parse_threads: bool = True, + parse_mem: bool = True, +) -> dict: + """ + Construct samtools options for threads (-@) and memory per thread (-m). + + Args: + threads: Number of threads to use. + mem_mb: Total memory available in Megabytes. + extra: Additional command line arguments. + parse_threads: Whether to include the thread count option. + parse_mem: Whether to include the memory per thread option. + """ + if threads <= 0: + return {"error": "threads must be at least 1"} + if mem_mb <= 0: + return {"error": "mem_mb must be a positive integer"} + + python_code = f""" +try: + from snakemake_wrapper_utils.samtools import get_samtools_opts + class Mock: + pass + snakemake = Mock() + snakemake.threads = {threads} + snakemake.resources = {{"mem_mb": {mem_mb}}} + print(get_samtools_opts(snakemake, extra="{extra}", parse_threads={parse_threads}, parse_mem={parse_mem})) +except ImportError: + # Fallback logic + opts = "{extra}" + if {parse_threads}: + opts += f" -@ {threads - 1}" + if {parse_mem}: + # Samtools -m is memory per thread + m_per_thread = {mem_mb} // {threads} + opts += f" -m {{m_per_thread}}M" + print(opts.strip()) +""" + + try: + result = subprocess.run( + ["python3", "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "snakemake_wrapper_utils.samtools.get_samtools_opts", + "stdout": result.stdout.strip(), + "stderr": result.stderr, + "samtools_opts": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to calculate samtools options: {e.stderr}", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def get_bcftools_opts( + threads: int = 1, + mem_mb: int = 2048, + extra: str = "", + parse_threads: bool = True, + parse_mem: bool = True, +) -> dict: + """ + Construct bcftools options for threads (--threads) and memory (--max-mem). + + Args: + threads: Number of threads to use. + mem_mb: Total memory available in Megabytes. + extra: Additional command line arguments. + parse_threads: Whether to include the thread count option. + parse_mem: Whether to include the max memory option. + """ + if threads <= 0: + return {"error": "threads must be at least 1"} + + python_code = f""" +try: + from snakemake_wrapper_utils.bcftools import get_bcftools_opts + class Mock: + pass + snakemake = Mock() + snakemake.threads = {threads} + snakemake.resources = {{"mem_mb": {mem_mb}}} + print(get_bcftools_opts(snakemake, extra="{extra}", parse_threads={parse_threads}, parse_mem={parse_mem})) +except ImportError: + opts = "{extra}" + if {parse_threads}: + opts += f" --threads {threads}" + if {parse_mem}: + opts += f" --max-mem {mem_mb}M" + print(opts.strip()) +""" + + try: + result = subprocess.run( + ["python3", "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "snakemake_wrapper_utils.bcftools.get_bcftools_opts", + "stdout": result.stdout.strip(), + "stderr": result.stderr, + "bcftools_opts": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to calculate bcftools options: {e.stderr}", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def get_vcf_type( + output_file: str, +) -> dict: + """ + Determine the VCF format (VCF, VCF.GZ, or BCF) based on the file extension. + + Args: + output_file: Path or filename of the VCF/BCF file. + """ + path_obj = Path(output_file) + + python_code = f""" +try: + from snakemake_wrapper_utils.vcf import get_vcf_type + print(get_vcf_type("{output_file}")) +except ImportError: + if "{output_file}".endswith(".bcf"): + print("b") + elif "{output_file}".endswith(".vcf.gz"): + print("z") + elif "{output_file}".endswith(".vcf"): + print("v") + else: + print("v") +""" + + try: + result = subprocess.run( + ["python3", "-c", python_code], + capture_output=True, + text=True, + check=True + ) + vcf_type_code = result.stdout.strip() + type_map = {"b": "BCF", "z": "Compressed VCF (vcf.gz)", "v": "Uncompressed VCF"} + + return { + "command_executed": "snakemake_wrapper_utils.vcf.get_vcf_type", + "stdout": vcf_type_code, + "vcf_type_code": vcf_type_code, + "vcf_type_label": type_map.get(vcf_type_code, "Unknown") + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to determine VCF type: {e.stderr}", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def parse_mem_to_mb( + mem_string: str, +) -> dict: + """ + Convert a memory string (e.g., '8G', '512M', '1024') into Megabytes (int). + + Args: + mem_string: String representing memory size with units. + """ + python_code = f""" +try: + # Note: snakemake-wrapper-utils often uses internal snakemake resource parsing + import re + def parse_mem(mem_str): + if isinstance(mem_str, int): + return mem_str + match = re.match(r"^(\d+)([KMGkmg])?$", str(mem_str)) + if not match: + return 0 + val = int(match.group(1)) + unit = match.group(2).upper() if match.group(2) else "M" + if unit == "K": + return val // 1024 + if unit == "M": + return val + if unit == "G": + return val * 1024 + return val + + print(parse_mem("{mem_string}")) +except Exception as e: + print(f"Error: {{e}}") +""" + + try: + result = subprocess.run( + ["python3", "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "custom_mem_parser", + "stdout": result.stdout.strip(), + "mem_mb": int(result.stdout.strip()) if result.stdout.strip().isdigit() else 0 + } + except (subprocess.CalledProcessError, ValueError) as e: + return { + "error": f"Failed to parse memory string: {str(e)}", + "stdout": getattr(e, 'stdout', ""), + "stderr": getattr(e, 'stderr', "") + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/snakemake-wrapper-utils_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/snakemake-wrapper-utils_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..438b30a22910983ac125081d4e54116b898f1d78 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/app/snakemake-wrapper-utils_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_snakemake-wrapper-utils/app/snakemake-wrapper-utils_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_snakemake_wrapper_utils' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d88a66070e78b2ac05a8a89ba517b9e90e26c910 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-snakemake-wrapper-utils: + build: . + image: mcp-snakemake-wrapper-utils:latest + container_name: mcp-snakemake-wrapper-utils + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=snakemake-wrapper-utils + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eaa9a2737032a56f641be76625ac1435fca9790d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - snakemake-wrapper-utils + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-wrapper-utils/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e079e3f88fbaad22b22c41b0d553ac76a0b1fc04 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install snakemake via conda (e.g., from bioconda) +RUN conda install -c bioconda snakemake -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/snakemake_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/snakemake_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/snakemake_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/__pycache__/snakemake_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/__pycache__/snakemake_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbb06bc7721c3ff165b2e1f4e23e889c94ee3d3d Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/__pycache__/snakemake_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/snakemake_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/snakemake_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6c817bdb59d870e869107b32192fb1ac9852b7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/snakemake_server.py @@ -0,0 +1,314 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict +import os + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_snakemake' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def snakemake_run( + snakefile: Optional[str] = None, + cores: int = 1, + targets: Optional[List[str]] = None, + dryrun: bool = False, + use_conda: bool = False, + use_singularity: bool = False, + config: Optional[List[str]] = None, + configfiles: Optional[List[str]] = None, + workdir: Optional[str] = None, + forceall: bool = False, + keep_going: bool = False, + printshellcmds: bool = True, + reason: bool = False, + latency_wait: int = 5, + rerun_incomplete: bool = True, +): + """ + Execute a Snakemake workflow. + + Args: + snakefile: Path to the Snakemake file (default: Snakefile). + cores: Number of CPU cores to use (required for execution). + targets: Specific files or rules to build. + dryrun: If True, only show what would be done. + use_conda: If True, use Conda to deploy software dependencies. + use_singularity: If True, use Singularity containers. + config: Set or overwrite configuration variables (list of "key=value"). + configfiles: List of configuration files to use. + workdir: Set the working directory. + forceall: Force the execution of all rules. + keep_going: Go on with independent jobs if a job fails. + printshellcmds: Print out the shell commands that will be executed. + reason: Print the reason for each executed rule. + latency_wait: Wait given seconds if an output file of a job is not present after the job finished. + rerun_incomplete: Re-run jobs that have been interrupted. + """ + cmd = ["snakemake", "--cores", str(cores)] + + if snakefile: + path_sf = Path(snakefile) + if not path_sf.exists(): + return {"error": f"Snakefile not found: {snakefile}"} + cmd.extend(["--snakefile", str(path_sf)]) + + if dryrun: + cmd.append("--dry-run") + if use_conda: + cmd.append("--use-conda") + if use_singularity: + cmd.append("--use-singularity") + if forceall: + cmd.append("--forceall") + if keep_going: + cmd.append("--keep-going") + if printshellcmds: + cmd.append("--printshellcmds") + if reason: + cmd.append("--reason") + if rerun_incomplete: + cmd.append("--rerun-incomplete") + + cmd.extend(["--latency-wait", str(latency_wait)]) + + if workdir: + cmd.extend(["--directory", workdir]) + + if config: + cmd.append("--config") + cmd.extend(config) + + if configfiles: + cmd.append("--configfiles") + cmd.extend(configfiles) + + if targets: + cmd.extend(targets) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def snakemake_info( + snakefile: Optional[str] = None, + mode: str = "list", +): + """ + Get information about the Snakemake workflow without executing it. + + Args: + snakefile: Path to the Snakemake file. + mode: Information mode: 'list' (list rules), 'summary' (table of rules/files), 'lint' (check code quality). + """ + cmd = ["snakemake"] + + if snakefile: + cmd.extend(["--snakefile", snakefile]) + + if mode == "list": + cmd.append("--list") + elif mode == "summary": + cmd.append("--summary") + elif mode == "lint": + cmd.append("--lint") + else: + return {"error": f"Invalid mode: {mode}. Choose from 'list', 'summary', 'lint'."} + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def snakemake_visualize( + snakefile: Optional[str] = None, + graph_type: str = "dag", + output_file: str = "workflow.dot", + targets: Optional[List[str]] = None, +): + """ + Generate a visualization of the workflow (DAG or Rulegraph) in DOT format. + + Args: + snakefile: Path to the Snakemake file. + graph_type: Type of graph: 'dag' (Directed Acyclic Graph of jobs) or 'rulegraph' (Graph of rules). + output_file: Path to save the .dot file. + targets: Specific files or rules to include in the graph. + """ + cmd = ["snakemake"] + + if snakefile: + cmd.extend(["--snakefile", snakefile]) + + if graph_type == "dag": + cmd.append("--dag") + elif graph_type == "rulegraph": + cmd.append("--rulegraph") + else: + return {"error": "graph_type must be 'dag' or 'rulegraph'"} + + if targets: + cmd.extend(targets) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + output_path = Path(output_file) + output_path.write_text(result.stdout) + + return { + "command_executed": " ".join(cmd), + "output_file": str(output_path.absolute()), + "message": f"Graph saved to {output_file}. Use 'dot -Tpdf {output_file} > graph.pdf' to render." + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def snakemake_report( + snakefile: Optional[str] = None, + report_path: str = "report.html", + config: Optional[List[str]] = None, +): + """ + Create an HTML report containing results and statistics. + + Args: + snakefile: Path to the Snakemake file. + report_path: Path where the HTML report should be saved. + config: Set or overwrite configuration variables (list of "key=value"). + """ + cmd = ["snakemake", "--report", report_path] + + if snakefile: + cmd.extend(["--snakefile", snakefile]) + + if config: + cmd.append("--config") + cmd.extend(config) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(report_path).absolute())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def snakemake_management( + snakefile: Optional[str] = None, + unlock: bool = False, + cleanup_metadata: Optional[List[str]] = None, + cleanup_shadow: bool = False, +): + """ + Perform maintenance tasks on the Snakemake working directory. + + Args: + snakefile: Path to the Snakemake file. + unlock: Remove a lock on the working directory. + cleanup_metadata: Cleanup the metadata of given files. + cleanup_shadow: Cleanup old shadow directories. + """ + cmd = ["snakemake"] + + if snakefile: + cmd.extend(["--snakefile", snakefile]) + + if unlock: + cmd.append("--unlock") + elif cleanup_metadata: + cmd.append("--cleanup-metadata") + cmd.extend(cleanup_metadata) + elif cleanup_shadow: + cmd.append("--cleanup-shadow") + else: + return {"error": "No management action specified (unlock, cleanup_metadata, or cleanup_shadow)."} + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def snakemake_archive( + output_file: str, + snakefile: Optional[str] = None, +): + """ + Archive the workflow into a tarball, including all input files and software environment. + + Args: + output_file: Path to the output archive (e.g., workflow.tar.gz). + snakefile: Path to the Snakemake file. + """ + cmd = ["snakemake", "--archive", output_file] + + if snakefile: + cmd.extend(["--snakefile", snakefile]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(output_file).absolute())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stderr": e.stderr, + "error": str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/snakemake_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/snakemake_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c06c90a6efcc35cf479acc1dd02920d9c0bd6bd2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/app/snakemake_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_snakemake/app/snakemake_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_snakemake' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..06457ecd8749d433ab983eff3cc1dbed6121b260 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-snakemake: + build: . + image: mcp-snakemake:latest + container_name: mcp-snakemake + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=snakemake + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8b397091e44e26bf726ec2926ccb3db895f108a4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - snakemake + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..398d24f6a46c4efce3f710ce8a176975cb6e5257 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install snpeff via conda (e.g., from bioconda) +RUN conda install -c bioconda snpeff -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/snpeff_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/snpeff_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/snpeff_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/__pycache__/snpeff_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/__pycache__/snpeff_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9430a43742b194f41556e86db4afcd5aa6a8917 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/__pycache__/snpeff_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/snpeff_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/snpeff_server.py new file mode 100644 index 0000000000000000000000000000000000000000..86f20bc711474a2cea2d7baace552bba9fc77a67 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/snpeff_server.py @@ -0,0 +1,355 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_snpeff' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def snpeff_ann( + genome_version: str, + input_vcf: str, + output_vcf: Optional[str] = None, + config: Optional[str] = None, + data_dir: Optional[str] = None, + no_stats: bool = False, + stats_file: Optional[str] = None, + csv_stats: Optional[str] = None, + up_down_stream_len: int = 5000, + hgvs: bool = True, + lof: bool = True, + only_canonical: bool = False, + only_protein: bool = False, + no_intergenic: bool = False, + no_intron: bool = False, + no_downstream: bool = False, + no_upstream: bool = False, + no_utr: bool = False, + output_format: str = "vcf", + verbose: bool = False, +): + """ + Annotate and predict effects of genetic variants (VCF) using SnpEff. + + Args: + genome_version: Genome version (e.g., 'GRCh38.105'). + input_vcf: Path to the input VCF file. + output_vcf: Path to the output VCF file. If not provided, output is returned in stdout. + config: Path to the snpEff.config file. + data_dir: Path to the directory containing the genomic databases. + no_stats: Do not create a stats file. + stats_file: Path to the HTML stats file (default: snpEff_summary.html). + csv_stats: Path to the CSV stats file. + up_down_stream_len: Set upstream/downstream interval length (in bases). + hgvs: Use HGVS notation for amino acid changes. + lof: Add Loss-of-Function (LOF) and Nonsense-Mediated Decay (NMD) tags. + only_canonical: Only use canonical transcripts. + only_protein: Only use protein-coding transcripts. + no_intergenic: Do not show intergenic variants. + no_intron: Do not show intronic variants. + no_downstream: Do not show downstream variants. + no_upstream: Do not show upstream variants. + no_utr: Do not show UTR variants. + output_format: Output format [vcf, gatk, bed, txt]. + verbose: Enable verbose output. + """ + # Input validation + input_path = Path(input_vcf) + if not input_path.exists(): + return {"error": f"Input VCF file not found: {input_vcf}"} + + if up_down_stream_len < 0: + return {"error": "up_down_stream_len must be a non-negative integer."} + + cmd = ["snpEff", "ann"] + + # Add options + if config: + config_path = Path(config) + if config_path.exists(): + cmd.extend(["-c", str(config_path)]) + + if data_dir: + data_path = Path(data_dir) + if data_path.exists(): + cmd.extend(["-dataDir", str(data_path)]) + + if no_stats: + cmd.append("-noStats") + if stats_file: + cmd.extend(["-s", stats_file]) + if csv_stats: + cmd.extend(["-csvStats", csv_stats]) + + cmd.extend(["-ud", str(up_down_stream_len)]) + + if not hgvs: + cmd.append("-noHgvs") + if not lof: + cmd.append("-noLof") + if only_canonical: + cmd.append("-canon") + if only_protein: + cmd.append("-protein") + if no_intergenic: + cmd.append("-noIntergenic") + if no_intron: + cmd.append("-noIntron") + if no_downstream: + cmd.append("-noDownstream") + if no_upstream: + cmd.append("-noUpstream") + if no_utr: + cmd.append("-noUtr") + + cmd.extend(["-o", output_format]) + + if verbose: + cmd.append("-v") + + # Positional arguments + cmd.append(genome_version) + cmd.append(str(input_path)) + + try: + if output_vcf: + with open(output_vcf, "w") as out_f: + process = subprocess.run(cmd, stdout=out_f, stderr=subprocess.PIPE, text=True, check=True) + return { + "command_executed": " ".join(cmd) + f" > {output_vcf}", + "stdout": f"Output written to {output_vcf}", + "stderr": process.stderr, + "output_files": [output_vcf] + } + else: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def snpeff_download( + genome_version: str, + config: Optional[str] = None, + data_dir: Optional[str] = None, + verbose: bool = False, +): + """ + Download a pre-built SnpEff database for a specific genome version. + + Args: + genome_version: Genome version to download (e.g., 'GRCh38.105'). + config: Path to the snpEff.config file. + data_dir: Path to the directory where the database should be saved. + verbose: Enable verbose output. + """ + cmd = ["snpEff", "download"] + + if config: + cmd.extend(["-c", config]) + if data_dir: + cmd.extend(["-dataDir", data_dir]) + if verbose: + cmd.append("-v") + + cmd.append(genome_version) + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def snpeff_databases( + config: Optional[str] = None, + verbose: bool = False, +): + """ + List all available databases in SnpEff. + + Args: + config: Path to the snpEff.config file. + verbose: Enable verbose output. + """ + cmd = ["snpEff", "databases"] + + if config: + cmd.extend(["-c", config]) + if verbose: + cmd.append("-v") + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def snpeff_build( + genome_version: str, + config: Optional[str] = None, + data_dir: Optional[str] = None, + gff3: bool = False, + gtf22: bool = False, + refseq: bool = False, + verbose: bool = False, +): + """ + Build a SnpEff database from local files (GFF, GTF, etc.). + + Args: + genome_version: Name of the genome version to build. + config: Path to the snpEff.config file. + data_dir: Path to the directory containing the input files. + gff3: Use GFF3 format. + gtf22: Use GTF 2.2 format. + refseq: Use RefSeq format. + verbose: Enable verbose output. + """ + cmd = ["snpEff", "build"] + + if config: + cmd.extend(["-c", config]) + if data_dir: + cmd.extend(["-dataDir", data_dir]) + if gff3: + cmd.append("-gff3") + if gtf22: + cmd.append("-gtf22") + if refseq: + cmd.append("-refSeq") + if verbose: + cmd.append("-v") + + cmd.append(genome_version) + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def snpeff_dump( + genome_version: str, + config: Optional[str] = None, + data_dir: Optional[str] = None, + verbose: bool = False, +): + """ + Dump a SnpEff database to stdout (useful for debugging or inspection). + + Args: + genome_version: Genome version to dump. + config: Path to the snpEff.config file. + data_dir: Path to the directory containing the genomic databases. + verbose: Enable verbose output. + """ + cmd = ["snpEff", "dump"] + + if config: + cmd.extend(["-c", config]) + if data_dir: + cmd.extend(["-dataDir", data_dir]) + if verbose: + cmd.append("-v") + + cmd.append(genome_version) + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def snpeff_show( + genome_version: str, + gene_id: str, + config: Optional[str] = None, + data_dir: Optional[str] = None, +): + """ + Show details of a specific gene or transcript in the database. + + Args: + genome_version: Genome version. + gene_id: Gene or Transcript ID to show. + config: Path to the snpEff.config file. + data_dir: Path to the directory containing the genomic databases. + """ + cmd = ["snpEff", "show"] + + if config: + cmd.extend(["-c", config]) + if data_dir: + cmd.extend(["-dataDir", data_dir]) + + cmd.extend([genome_version, gene_id]) + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/snpeff_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/snpeff_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..323995157ab4628148eb231b0ecb5b1f12ecd8c2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/app/snpeff_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_snpeff/app/snpeff_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_snpeff' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3e79b88a3f41381b46eea80d66501a681f1becac --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-snpeff: + build: . + image: mcp-snpeff:latest + container_name: mcp-snpeff + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=snpeff + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..210dbb8e6072d5b88f7f63c1c7431792b95a2393 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - snpeff + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snpeff/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sorted_nearest/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sorted_nearest/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sorted_nearest/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..517328aacda6a9b32488e23d0efe1cbc8d36a446 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install sourmash via conda (e.g., from bioconda) +RUN conda install -c bioconda sourmash -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/sourmash_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/sourmash_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/sourmash_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/__pycache__/sourmash_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/__pycache__/sourmash_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5038579db36ce365fec12d22c9d0b584916b054 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/__pycache__/sourmash_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/sourmash_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/sourmash_server.py new file mode 100644 index 0000000000000000000000000000000000000000..82ec5a419af8b9200046bcd579ea93d63a5dd68d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/sourmash_server.py @@ -0,0 +1,384 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import os + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_sourmash' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def sourmash_sketch_dna( + input_files: List[str], + output: str, + ksize: int = 31, + scaled: int = 1000, + name: Optional[str] = None, + singleton: bool = False, + merge: Optional[str] = None, + param_string: Optional[str] = None, +): + """ + Create DNA signatures (sketches) from genomic or metagenomic sequences. + + Args: + input_files: List of paths to FASTA/FASTQ files (can be gzipped). + output: Path to save the resulting .sig or .zip signature file. + ksize: K-mer size to use (default 31). + scaled: Compression ratio (default 1000). + name: Name to give to the signature(s). + singleton: Create a separate signature for each sequence in the input files. + merge: Merge all input files into a single signature with this name. + param_string: Advanced parameter string (e.g., 'k=21,k=31,scaled=1000'). + """ + # Input validation + for f in input_files: + if not Path(f).exists(): + return {"error": f"Input file not found: {f}"} + + cmd = ["sourmash", "sketch", "dna"] + + for f in input_files: + cmd.append(f) + + cmd.extend(["-o", output]) + cmd.extend(["--param-string", f"k={ksize},scaled={scaled}"]) + + if name: + cmd.extend(["--name", name]) + if singleton: + cmd.append("--singleton") + if merge: + cmd.extend(["--merge", merge]) + if param_string: + # Overwrites the default k/scaled if provided + cmd.extend(["--param-string", param_string]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output] if Path(output).exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr, + "stdout": e.stdout + } + +@mcp.tool() +def sourmash_compare( + signatures: List[str], + output: str, + ksize: int = 31, + ignore_abundance: bool = False, + containment: bool = False, + processes: int = 1, +): + """ + Compare multiple signatures to create a similarity or containment matrix. + + Args: + signatures: List of paths to signature files (.sig, .zip, or directories). + output: Path to save the comparison matrix. + ksize: K-mer size to use for comparison (default 31). + ignore_abundance: Do not use k-mer abundances if present. + containment: Calculate containment instead of Jaccard similarity. + processes: Number of processes to use for parallelization. + """ + for s in signatures: + if not Path(s).exists(): + return {"error": f"Signature file not found: {s}"} + + cmd = ["sourmash", "compare"] + cmd.extend(signatures) + cmd.extend(["-o", output, "-k", str(ksize)]) + + if ignore_abundance: + cmd.append("--ignore-abundance") + if containment: + cmd.append("--containment") + if processes > 1: + cmd.extend(["--processes", str(processes)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # sourmash compare creates a binary matrix file and often a .labels.txt file + output_files = [output] + labels_file = f"{output}.labels.txt" + if Path(labels_file).exists(): + output_files.append(labels_file) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def sourmash_gather( + query: str, + databases: List[str], + output: Optional[str] = None, + threshold_bp: int = 50000, + ksize: int = 31, + save_unassigned: Optional[str] = None, + num_results: Optional[int] = None, +): + """ + Search a metagenome signature against a database to find the minimum set of genomes that cover it. + + Args: + query: Path to the query signature file. + databases: List of paths to database signatures or SBT/LCA indexes. + output: Path to save the results in CSV format. + threshold_bp: Minimum number of base pairs in common to report a match (default 50,000). + ksize: K-mer size to use (default 31). + save_unassigned: Path to save unassigned k-mers as a signature. + num_results: Stop after finding this many matches. + """ + if not Path(query).exists(): + return {"error": f"Query file not found: {query}"} + + cmd = ["sourmash", "gather", query] + cmd.extend(databases) + cmd.extend(["-k", str(ksize), "--threshold-bp", str(threshold_bp)]) + + if output: + cmd.extend(["-o", output]) + if save_unassigned: + cmd.extend(["--save-unassigned", save_unassigned]) + if num_results: + cmd.extend(["--num-results", str(num_results)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [] + if output and Path(output).exists(): + output_files.append(output) + if save_unassigned and Path(save_unassigned).exists(): + output_files.append(save_unassigned) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def sourmash_search( + query: str, + databases: List[str], + output: Optional[str] = None, + threshold: float = 0.08, + ksize: int = 31, + containment: bool = False, + num_results: int = 3, +): + """ + Search a query signature against a database for similar signatures. + + Args: + query: Path to the query signature file. + databases: List of paths to database signatures or indexes. + output: Path to save results in CSV format. + threshold: Minimum similarity/containment to report (default 0.08). + ksize: K-mer size to use (default 31). + containment: Search for containment instead of Jaccard similarity. + num_results: Number of results to return (default 3). + """ + if not Path(query).exists(): + return {"error": f"Query file not found: {query}"} + + cmd = ["sourmash", "search", query] + cmd.extend(databases) + cmd.extend(["-k", str(ksize), "--threshold", str(threshold), "-n", str(num_results)]) + + if output: + cmd.extend(["-o", output]) + if containment: + cmd.append("--containment") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output] if output and Path(output).exists() else [] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def sourmash_plot( + matrix: str, + output_prefix: str, + labels: bool = False, + indices: bool = False, + vmax: float = 1.0, + vmin: float = 0.0, +): + """ + Visualize a comparison matrix created by 'sourmash compare'. + + Args: + matrix: Path to the matrix file created by 'sourmash compare'. + output_prefix: Prefix for the output plot files (.png, .pdf). + labels: Show signature names on the plot (requires .labels.txt file). + indices: Show matrix indices on the plot. + vmax: Maximum value for the color scale (default 1.0). + vmin: Minimum value for the color scale (default 0.0). + """ + if not Path(matrix).exists(): + return {"error": f"Matrix file not found: {matrix}"} + + cmd = ["sourmash", "plot", matrix, "--output-dir", os.path.dirname(output_prefix) or "."] + + # sourmash plot uses the matrix filename to find labels, but we can specify prefix + # Note: sourmash plot usually outputs {matrix}.matrix.png + + if labels: + cmd.append("--labels") + if indices: + cmd.append("--indices") + cmd.extend(["--vmax", str(vmax), "--vmin", str(vmin)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # Identify generated files + base = Path(matrix).name + output_files = [str(f) for f in Path(".").glob(f"{base}*") if f.suffix in ['.png', '.pdf', '.matrix.png']] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def sourmash_tax_metagenome( + gather_csv: List[str], + taxonomy_csv: List[str], + output_prefix: str, + rank: str = "species", + force: bool = False, +): + """ + Summarize 'sourmash gather' results using taxonomic information. + + Args: + gather_csv: List of CSV files from 'sourmash gather'. + taxonomy_csv: List of CSV files containing taxonomic information (e.g., GTDB or NCBI). + output_prefix: Prefix for the output summary files. + rank: Taxonomic rank to summarize at (default 'species'). + force: Force overwrite of existing files. + """ + for f in gather_csv + taxonomy_csv: + if not Path(f).exists(): + return {"error": f"Input file not found: {f}"} + + cmd = ["sourmash", "tax", "metagenome"] + cmd.extend(["--gather-results"]) + cmd.extend(gather_csv) + cmd.extend(["--taxonomy"]) + cmd.extend(taxonomy_csv) + cmd.extend(["--output-prefix", output_prefix, "--rank", rank]) + + if force: + cmd.append("--force") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [f"{output_prefix}.summarized.csv"] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [f for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def sourmash_sig_merge( + signatures: List[str], + output: str, + ksize: Optional[int] = None, + flatten: bool = False, +): + """ + Merge multiple signatures into a single signature file. + + Args: + signatures: List of signature files to merge. + output: Path to the output signature file. + ksize: Filter by k-mer size before merging. + flatten: Remove abundance information (set all counts to 1). + """ + for s in signatures: + if not Path(s).exists(): + return {"error": f"Signature file not found: {s}"} + + cmd = ["sourmash", "sig", "merge"] + cmd.extend(signatures) + cmd.extend(["-o", output]) + + if ksize: + cmd.extend(["-k", str(ksize)]) + if flatten: + cmd.append("--flatten") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output] if Path(output).exists() else [] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def sourmash_sig_describe( + signatures: List[str], +): + """ + Provide a human-readable summary of the contents of signature files. + + Args: + signatures: List of signature files to describe. + """ + for s in signatures: + if not Path(s).exists(): + return {"error": f"Signature file not found: {s}"} + + cmd = ["sourmash", "sig", "describe"] + cmd.extend(signatures) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/sourmash_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/sourmash_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..886c36f1c1df90dc9568620f80c9ffbc1212cfdf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/app/sourmash_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_sourmash/app/sourmash_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_sourmash' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b163b34254d72f5261702b8546bd29767ef1b46d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-sourmash: + build: . + image: mcp-sourmash:latest + container_name: mcp-sourmash + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=sourmash + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..749ba7b7fd416595e392aef0a7b338bd6b9e63fc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - sourmash + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sourmash/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7224410c369400b5f7ae40ce07327d9938ad0b70 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install spades via conda (e.g., from bioconda) +RUN conda install -c bioconda spades -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/spades_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/spades_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/spades_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/__pycache__/spades_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/__pycache__/spades_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2a242e304330900a5c1e99652acce591ea93136 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/__pycache__/spades_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/__pycache__/spades_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/__pycache__/spades_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e43b4db9c14f518336e930b16e4127f80c6bf0f6 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/__pycache__/spades_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/spades_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/spades_server.py new file mode 100644 index 0000000000000000000000000000000000000000..36235b21c90b80974616e8b3d42d447c24327479 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/spades_server.py @@ -0,0 +1,355 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +def _run_command(command: List[str]): + """Internal helper to execute subprocess commands""" + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "error_message": str(e) + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_spades' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def spades_py( + output_dir: str, + pe1_1: Optional[str] = None, + pe1_2: Optional[str] = None, + pe1_merged: Optional[str] = None, + pe1_single: Optional[str] = None, + single_reads: Optional[str] = None, + pacbio: Optional[str] = None, + nanopore: Optional[str] = None, + trusted_contigs: Optional[str] = None, + untrusted_contigs: Optional[str] = None, + threads: int = 16, + memory: int = 16, + k_mers: str = "auto", + isolate: bool = False, + sc: bool = False, + meta: bool = False, + rna: bool = False, + plasmid: bool = False, + metaplasmid: bool = False, + metaviral: bool = False, + rnaviral: bool = False, + bio: bool = False, + corona: bool = False, + sewage: bool = False, + iontorrent: bool = False, + only_error_correction: bool = False, + only_assembler: bool = False, + continue_run: bool = False, + restart_from: Optional[str] = None, + tmp_dir: Optional[str] = None, +): + """ + SPAdes genome assembler for standard isolates, single-cell, metagenomic, and transcriptomic data. + + Args: + output_dir: Directory to store output files. + pe1_1: File with forward paired-end reads for the first library. + pe1_2: File with reverse paired-end reads for the first library. + pe1_merged: File with merged paired-end reads for the first library. + pe1_single: File with unpaired reads from the first paired-end library. + single_reads: File with single reads. + pacbio: File with PacBio reads. + nanopore: File with Oxford Nanopore reads. + trusted_contigs: File with trusted contigs for hybrid assembly. + untrusted_contigs: File with untrusted contigs. + threads: Number of threads to use (default: 16). + memory: RAM limit in Gb (default: 16). + k_mers: Comma-separated list of k-mer sizes (e.g. '21,33,55') or 'auto'. + isolate: Use isolate mode (highly recommended for isolate data). + sc: Use single-cell mode (MDA data). + meta: Use metagenomic mode. + rna: Use transcriptomic mode. + plasmid: Use plasmid mode. + metaplasmid: Use metagenomic plasmid mode. + metaviral: Use metagenomic viral mode. + rnaviral: Use transcriptomic viral mode. + bio: Use biosynthetic gene cluster mode. + corona: Use coronavirus mode. + sewage: Use sewage metagenome mode. + iontorrent: Required for IonTorrent data. + only_error_correction: Run only read error correction. + only_assembler: Run only assembly (skip error correction). + continue_run: Continue from the last available checkpoint. + restart_from: Restart from a specific stage (ec, as, k, mc, last). + tmp_dir: Directory for temporary files. + """ + cmd = ["spades.py", "-o", output_dir] + + # Input validation + out_path = Path(output_dir) + if not continue_run and not restart_from and out_path.exists() and any(out_path.iterdir()): + return {"error": f"Output directory {output_dir} already exists and is not empty."} + + # Modes + if isolate: cmd.append("--isolate") + if sc: cmd.append("--sc") + if meta: cmd.append("--meta") + if rna: cmd.append("--rna") + if plasmid: cmd.append("--plasmid") + if metaplasmid: cmd.append("--metaplasmid") + if metaviral: cmd.append("--metaviral") + if rnaviral: cmd.append("--rnaviral") + if bio: cmd.append("--bio") + if corona: cmd.append("--corona") + if sewage: cmd.append("--sewage") + if iontorrent: cmd.append("--iontorrent") + + # Inputs + if pe1_1: cmd.extend(["-1", pe1_1]) + if pe1_2: cmd.extend(["-2", pe1_2]) + if pe1_merged: cmd.extend(["--merged", pe1_merged]) + if pe1_single: cmd.extend(["--pe1-s", pe1_single]) + if single_reads: cmd.extend(["-s", single_reads]) + if pacbio: cmd.extend(["--pacbio", pacbio]) + if nanopore: cmd.extend(["--nanopore", nanopore]) + if trusted_contigs: cmd.extend(["--trusted-contigs", trusted_contigs]) + if untrusted_contigs: cmd.extend(["--untrusted-contigs", untrusted_contigs]) + + # Parameters + cmd.extend(["-t", str(threads)]) + cmd.extend(["-m", str(memory)]) + cmd.extend(["-k", k_mers]) + + if only_error_correction: cmd.append("--only-error-correction") + if only_assembler: cmd.append("--only-assembler") + if continue_run: cmd.append("--continue") + if restart_from: cmd.extend(["--restart-from", restart_from]) + if tmp_dir: cmd.extend(["--tmp-dir", tmp_dir]) + + result = _run_command(cmd) + + # Identify key output files + output_files = [] + if out_path.exists(): + for filename in ["contigs.fasta", "scaffolds.fasta", "assembly_graph.fastg", "spades.log"]: + if (out_path / filename).exists(): + output_files.append(str(out_path / filename)) + + result["output_files"] = output_files + return result + +@mcp.tool() +def metaspades_py( + output_dir: str, + pe1_1: Optional[str] = None, + pe1_2: Optional[str] = None, + single_reads: Optional[str] = None, + threads: int = 16, + memory: int = 64, +): + """ + Convenience wrapper for metaSPAdes (metagenomic assembly). + + Args: + output_dir: Directory to store output files. + pe1_1: Forward paired-end reads. + pe1_2: Reverse paired-end reads. + single_reads: Single reads. + threads: Number of threads (default: 16). + memory: RAM limit in Gb (default: 64). + """ + cmd = ["metaspades.py", "-o", output_dir] + if pe1_1: cmd.extend(["-1", pe1_1]) + if pe1_2: cmd.extend(["-2", pe1_2]) + if single_reads: cmd.extend(["-s", single_reads]) + cmd.extend(["-t", str(threads), "-m", str(memory)]) + + result = _run_command(cmd) + out_path = Path(output_dir) + if out_path.exists(): + result["output_files"] = [str(f) for f in out_path.glob("*.fasta")] + return result + +@mcp.tool() +def rnaspades_py( + output_dir: str, + pe1_1: Optional[str] = None, + pe1_2: Optional[str] = None, + ss_type: Optional[str] = None, + threads: int = 16, + memory: int = 64, +): + """ + Convenience wrapper for rnaSPAdes (transcriptome assembly). + + Args: + output_dir: Directory to store output files. + pe1_1: Forward paired-end reads. + pe1_2: Reverse paired-end reads. + ss_type: Strand-specific data type (fr-firststrand or fr-secondstrand). + threads: Number of threads (default: 16). + memory: RAM limit in Gb (default: 64). + """ + cmd = ["rnaspades.py", "-o", output_dir] + if pe1_1: cmd.extend(["-1", pe1_1]) + if pe1_2: cmd.extend(["-2", pe1_2]) + if ss_type: cmd.extend(["--ss-type", ss_type]) + cmd.extend(["-t", str(threads), "-m", str(memory)]) + + result = _run_command(cmd) + out_path = Path(output_dir) + if out_path.exists(): + result["output_files"] = [str(f) for f in out_path.glob("*.fasta")] + return result + +@mcp.tool() +def plasmidspades_py( + output_dir: str, + pe1_1: Optional[str] = None, + pe1_2: Optional[str] = None, + threads: int = 16, + memory: int = 64, +): + """ + Convenience wrapper for plasmidSPAdes (plasmid assembly from isolate/single-cell data). + + Args: + output_dir: Directory to store output files. + pe1_1: Forward paired-end reads. + pe1_2: Reverse paired-end reads. + threads: Number of threads (default: 16). + memory: RAM limit in Gb (default: 64). + """ + cmd = ["plasmidspades.py", "-o", output_dir] + if pe1_1: cmd.extend(["-1", pe1_1]) + if pe1_2: cmd.extend(["-2", pe1_2]) + cmd.extend(["-t", str(threads), "-m", str(memory)]) + + result = _run_command(cmd) + out_path = Path(output_dir) + if out_path.exists(): + result["output_files"] = [str(f) for f in out_path.glob("*.fasta")] + return result + +@mcp.tool() +def metaviralspades_py( + output_dir: str, + pe1_1: Optional[str] = None, + pe1_2: Optional[str] = None, + threads: int = 16, + memory: int = 64, +): + """ + Convenience wrapper for metaviralSPAdes (viral assembly from metagenomic data). + """ + cmd = ["metaviralspades.py", "-o", output_dir] + if pe1_1: cmd.extend(["-1", pe1_1]) + if pe1_2: cmd.extend(["-2", pe1_2]) + cmd.extend(["-t", str(threads), "-m", str(memory)]) + + result = _run_command(cmd) + return result + +@mcp.tool() +def coronaspades_py( + output_dir: str, + pe1_1: Optional[str] = None, + pe1_2: Optional[str] = None, + threads: int = 16, + memory: int = 64, +): + """ + Convenience wrapper for coronaSPAdes (coronavirus assembly). + """ + cmd = ["coronaspades.py", "-o", output_dir] + if pe1_1: cmd.extend(["-1", pe1_1]) + if pe1_2: cmd.extend(["-2", pe1_2]) + cmd.extend(["-t", str(threads), "-m", str(memory)]) + + result = _run_command(cmd) + return result + +@mcp.tool() +def biosyntheticspades_py( + output_dir: str, + pe1_1: Optional[str] = None, + pe1_2: Optional[str] = None, + threads: int = 16, + memory: int = 64, +): + """ + Convenience wrapper for biosyntheticSPAdes (BGC assembly). + """ + cmd = ["biosyntheticspades.py", "-o", output_dir] + if pe1_1: cmd.extend(["-1", pe1_1]) + if pe1_2: cmd.extend(["-2", pe1_2]) + cmd.extend(["-t", str(threads), "-m", str(memory)]) + + result = _run_command(cmd) + return result + +@mcp.tool() +def spades_test(): + """ + Run SPAdes installation test. + """ + cmd = ["spades.py", "--test"] + return _run_command(cmd) + +@mcp.tool() +def spades_kmercount( + input_file: str, + output_file: str, + k: int = 21, + threads: int = 16, +): + """ + Standalone k-mer counting tool from the SPAdes package. + + Args: + input_file: Input FASTQ/FASTA file. + output_file: Output file for k-mer counts. + k: K-mer size (default: 21). + threads: Number of threads (default: 16). + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + cmd = ["spades-kmercount", "--input", input_file, "--output", output_file, "-k", str(k), "-t", str(threads)] + result = _run_command(cmd) + if Path(output_file).exists(): + result["output_files"] = [output_file] + return result + +@mcp.tool() +def spades_hammer( + input_config: str, + threads: int = 16, +): + """ + Standalone BayesHammer error correction tool. + + Args: + input_config: Path to the configuration file (usually generated by spades.py). + threads: Number of threads. + """ + if not Path(input_config).exists(): + return {"error": f"Config file {input_config} not found."} + + cmd = ["spades-hammer", input_config, "-t", str(threads)] + return _run_command(cmd) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/spades_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/spades_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..74d59af9c55c471bd12d98b8f781522573304a79 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/app/spades_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_spades/app/spades_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_spades' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3592956f96ca0bcd40ddd9c48d89cd7c3045c798 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-spades: + build: . + image: mcp-spades:latest + container_name: mcp-spades + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=spades + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..64c36918d71c1891e52bcfd06b8a0ec9a8b63426 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - spades + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spades/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..03712376d884e40e2d789940320927103dacc29c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install switchtfi via conda (e.g., from bioconda) +RUN conda install -c bioconda switchtfi -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/switchtfi_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/switchtfi_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/switchtfi_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/__pycache__/switchtfi_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/__pycache__/switchtfi_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7678df024b94d9777f0449c83f712133541ec23c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/__pycache__/switchtfi_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/switchtfi_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/switchtfi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8df769c4adf310faeeb6cabb510b7496ec4fe764 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/switchtfi_server.py @@ -0,0 +1,87 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import List, Dict, Union + +# MCP decorator is assumed to be available in the execution environment. +# No import is included as per the instructions. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_switchtfi' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_example_analysis( + dataset: str, +) -> Dict[str, Union[str, List[str], int]]: + """ + Runs the SwitchTFI example analysis on a preprocessed scRNA-seq dataset. + + This function executes the 'example.py' script provided in the SwitchTFI + repository to identify transcription factors driving cell differentiation + for one of the built-in example datasets. + + Args: + dataset: The example dataset to use. Must be one of 'ery', 'beta', or 'alpha'. + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and a list of output files generated. + """ + # 1. Input Validation + allowed_datasets = ['ery', 'beta', 'alpha'] + if dataset not in allowed_datasets: + raise ValueError(f"Dataset must be one of {allowed_datasets}, but got '{dataset}'.") + + # The command assumes 'example.py' is in the current working directory or PATH. + # This is based on the usage instructions: `python example.py -d ery` + cmd = ["python", "example.py", "-d", dataset] + command_str = " ".join(cmd) + + # 2. Subprocess Execution in a temporary directory to isolate the run + try: + with tempfile.TemporaryDirectory() as tmpdir: + tmpdir_path = Path(tmpdir) + + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + cwd=tmpdir_path, # Run inside the temp directory to capture all outputs + encoding='utf-8' + ) + + # 3. Collect any files generated in the temporary directory + output_files = [str(tmpdir_path / f) for f in os.listdir(tmpdir_path)] + + # 4. Return structured output for success + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + + except FileNotFoundError: + # This error occurs if 'python' or 'example.py' is not found. + return { + "error": "Execution failed: 'python' or 'example.py' not found. Please ensure Python is installed and the SwitchTFI 'example.py' script is in the execution path.", + "command_executed": command_str, + "stdout": "", + "stderr": "FileNotFoundError: The command could not be located.", + } + except subprocess.CalledProcessError as e: + # This error occurs if the script runs but returns a non-zero exit code. + return { + "error": "SwitchTFI example script failed with a non-zero exit code.", + "command_executed": command_str, + "return_code": e.returncode, + "stdout": e.stdout, + "stderr": e.stderr, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/switchtfi_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/switchtfi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e5a9a6ab327a5ab1f26a00238ad1f2811daeff17 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/app/switchtfi_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_switchtfi/app/switchtfi_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_switchtfi' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..12093a3a645e749d4d580dcb5107cd46e470c904 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-switchtfi: + build: . + image: mcp-switchtfi:latest + container_name: mcp-switchtfi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=switchtfi + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..970b9f9178c7f08ec02252bd51e85f91e08dbfcc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - switchtfi + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_switchtfi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..809f0aade38e4bd7d694237a26d36411d3f88fd7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install t-coffee via conda (e.g., from bioconda) +RUN conda install -c bioconda t-coffee -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/t-coffee_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/t-coffee_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/t-coffee_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/__pycache__/t-coffee_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/__pycache__/t-coffee_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b136f5cd69f3805b340d27ce85f42f9c1611c819 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/__pycache__/t-coffee_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/t-coffee_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/t-coffee_server.py new file mode 100644 index 0000000000000000000000000000000000000000..09803e2fe2a0cf39ad1699f2dbdb0899240907b8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/t-coffee_server.py @@ -0,0 +1,240 @@ + +from typing import Optional, List +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_t_coffee' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def t_coffee_align( + input_sequences: str, + method: Optional[str] = None, + mode: Optional[str] = None, + output_format: str = "fasta_aln", + outfile: Optional[str] = None, + n_core: int = 1, + gapopen: int = -50, + gapext: int = 0, +): + """ + Perform Multiple Sequence Alignment (MSA) using T-Coffee. + + Args: + input_sequences: Path to the input sequence file (FASTA format). + method: Optional list of methods to use (e.g., 'clustalw_msa,mafft_msa,muscle_msa'). + mode: T-Coffee mode (e.g., 'mcoffee', 'expresso', 'rcoffee', 'quickaln', 'accurate'). + output_format: Format of the output alignment (e.g., 'fasta_aln', 'clustalw_aln', 'msf_aln', 'score_ascii'). + outfile: Name of the output alignment file. + n_core: Number of CPU cores to use. + gapopen: Gap opening penalty (default -50). + gapext: Gap extension penalty (default 0). + """ + input_path = Path(input_sequences) + if not input_path.exists(): + return {"error": f"Input file not found: {input_sequences}"} + + if n_core < 1: + n_core = 1 + + cmd = ["t_coffee", "-seq", str(input_path)] + + if method: + cmd.extend(["-method", method]) + + if mode: + cmd.extend(["-mode", mode]) + + if output_format: + cmd.extend(["-output", output_format]) + + if outfile: + cmd.extend(["-outfile", outfile]) + + cmd.extend(["-n_core", str(n_core)]) + cmd.extend(["-gapopen", str(gapopen)]) + cmd.extend(["-gapext", str(gapext)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] if outfile else ["Default T-Coffee output files (.aln, .dnd, etc.)"] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def t_coffee_reformat( + input_file: str, + output_format: str = "fasta_aln", + outfile: Optional[str] = None, + action: Optional[str] = None +): + """ + Reformat sequences or alignments using T-Coffee's seq_reformat utility. + + Args: + input_file: Path to the input alignment or sequence file. + output_format: Target format (e.g., 'fasta_aln', 'clustalw', 'phylip', 'pir', 'stockholm'). + outfile: Name of the output file. + action: Optional specific reformatting action (e.g., 'translate', 'keep_name'). + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["t_coffee", "-other_pg", "seq_reformat", "-in", str(input_path), "-output", output_format] + + if outfile: + cmd.extend(["-out", outfile]) + + if action: + cmd.extend(["-action", action]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] if outfile else ["Standard Output"] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def t_coffee_compare( + aln1: str, + aln2: str, + compare_mode: str = "sum_of_pairs", + outfile: Optional[str] = None +): + """ + Compare two multiple sequence alignments. + + Args: + aln1: Path to the first alignment file. + aln2: Path to the second alignment file. + compare_mode: Comparison metric (e.g., 'sum_of_pairs', 'column'). + outfile: Path to save the comparison results. + """ + path1 = Path(aln1) + path2 = Path(aln2) + + if not path1.exists() or not path2.exists(): + return {"error": "One or both input alignment files not found."} + + cmd = ["t_coffee", "-other_pg", "aln_compare", "-al1", str(path1), "-al2", str(path2), "-compare_mode", compare_mode] + + if outfile: + cmd.extend(["-outfile", outfile]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] if outfile else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def t_coffee_evaluate( + input_alignment: str, + output_format: str = "score_ascii", + outfile: Optional[str] = None +): + """ + Evaluate the quality of an existing alignment using T-Coffee scoring. + + Args: + input_alignment: Path to the alignment file to evaluate. + output_format: Scoring output format ('score_ascii', 'score_html', 'score_pdf'). + outfile: Name of the output score file. + """ + input_path = Path(input_alignment) + if not input_path.exists(): + return {"error": f"Alignment file not found: {input_alignment}"} + + cmd = ["t_coffee", "-infile", str(input_path), "-output", output_format] + + if outfile: + cmd.extend(["-outfile", outfile]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] if outfile else ["Default score file"] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def t_coffee_extract_pdb( + pdb_id: str, + chain: Optional[str] = None, + outfile: Optional[str] = None +): + """ + Extract sequences or structural data from PDB files using T-Coffee utilities. + + Args: + pdb_id: PDB Identifier (e.g., '1pdb'). + chain: Specific chain to extract. + outfile: Output filename. + """ + cmd = ["t_coffee", "-other_pg", "extract_from_pdb", "-pdb", pdb_id] + + if chain: + cmd.extend(["-chain", chain]) + if outfile: + cmd.extend(["-out", outfile]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] if outfile else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/t-coffee_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/t-coffee_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1df2d84e8a8820541fa31befbf12b045d5b7b6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/app/t-coffee_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_t-coffee/app/t-coffee_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_t_coffee' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2658253058b820ffcc209422dd4c93eff7eeb155 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-t-coffee: + build: . + image: mcp-t-coffee:latest + container_name: mcp-t-coffee + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=t-coffee + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b39c8fbb1385568b2dfd73ba951240a3cdda0a09 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - t-coffee + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t-coffee/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..223acad79c2b7696f61fde1d7f36635c164247d7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install t_coffee via conda (e.g., from bioconda) +RUN conda install -c bioconda t_coffee -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/t_coffee_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/t_coffee_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/t_coffee_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/__pycache__/t_coffee_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/__pycache__/t_coffee_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e092769e4f756b2ab313eeb8f28b7aa91b15f3b2 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/__pycache__/t_coffee_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/t_coffee_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/t_coffee_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae128261afd767d308a9ad7ee01fdd85d877749 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/t_coffee_server.py @@ -0,0 +1,261 @@ +import subprocess +from pathlib import Path +from typing import Optional, List +import os + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_t_coffee' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def t_coffee_align( + seq: str, + mode: Optional[str] = None, + method: Optional[str] = None, + output: Optional[str] = "clustalw_aln", + outfile: Optional[str] = None, + n_core: int = 1, + run_name: Optional[str] = None, + quiet: bool = False, + template_file: Optional[str] = None, + tree: Optional[str] = None, +): + """ + Perform Multiple Sequence Alignment using T-Coffee. + + Args: + seq: Input sequence file (FASTA format). + mode: Predefined T-Coffee mode (e.g., 'expresso', 'mcoffee', 'rcoffee', 'accurate', 'quick_aln'). + method: Specific alignment methods to combine (comma-separated). + output: Output formats (e.g., 'clustalw_aln', 'fasta_aln', 'score_ascii', 'score_html'). + outfile: Name of the output alignment file. + n_core: Number of CPU cores to use. + run_name: Prefix for all generated files. + quiet: If True, minimizes console output. + template_file: File containing structural templates (for Expresso/structural modes). + tree: Guide tree file to use for the alignment. + """ + # Input validation + seq_path = Path(seq) + if not seq_path.exists(): + return {"error": f"Input sequence file not found: {seq}"} + + cmd = ["t_coffee", "-seq", str(seq_path)] + + if mode: + cmd.extend(["-mode", mode]) + if method: + cmd.extend(["-method", method]) + if output: + cmd.extend(["-output", output]) + if outfile: + cmd.extend(["-outfile", outfile]) + if n_core > 1: + cmd.extend(["-n_core", str(n_core)]) + if run_name: + cmd.extend(["-run_name", run_name]) + if quiet: + cmd.extend(["-quiet"]) + if template_file: + if not Path(template_file).exists(): + return {"error": f"Template file not found: {template_file}"} + cmd.extend(["-template_file", template_file]) + if tree: + if not Path(tree).exists(): + return {"error": f"Tree file not found: {tree}"} + cmd.extend(["-tree", tree]) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + + # Identify output files based on run_name or default naming + output_files = [] + prefix = run_name if run_name else seq_path.stem + for f in os.listdir("."): + if f.startswith(prefix): + output_files.append(f) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def t_coffee_reformat( + input_file: str, + action: str, + output_format: str = "fasta_seq", + output_file: Optional[str] = None, +): + """ + Reformat or manipulate sequences and alignments using t_coffee -other_pg seq_reformat. + + Args: + input_file: Input file (alignment or sequence). + action: Action to perform (e.g., '+translate', '+cat', '+extract_seq', '+rm_gap'). + output_format: Desired output format (e.g., 'fasta_seq', 'clustalw_aln', 'phylip'). + output_file: Name of the output file. + """ + in_path = Path(input_file) + if not in_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = [ + "t_coffee", "-other_pg", "seq_reformat", + "-in", str(in_path), + "-action", action, + "-output", output_format + ] + + if output_file: + cmd.extend(["-out", output_file]) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] if output_file else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def t_coffee_compare( + al1: str, + al2: str, + method: str = "sp", +): + """ + Compare two multiple sequence alignments. + + Args: + al1: First alignment file. + al2: Second alignment file. + method: Comparison method (e.g., 'sp' for Sum of Pairs, 'tc' for Total Column). + """ + path1 = Path(al1) + path2 = Path(al2) + if not path1.exists() or not path2.exists(): + return {"error": "One or both alignment files not found."} + + cmd = [ + "t_coffee", "-other_pg", "compare", + "-al1", str(path1), + "-al2", str(path2), + "-method", method + ] + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def t_coffee_evaluate( + infile: str, + output_format: str = "score_ascii", + outfile: Optional[str] = None, +): + """ + Evaluate the quality of an existing alignment. + + Args: + infile: The alignment file to evaluate. + output_format: Evaluation output format ('score_ascii', 'score_html', 'score_pdf'). + outfile: Output filename for the evaluation. + """ + in_path = Path(infile) + if not in_path.exists(): + return {"error": f"Input alignment file not found: {infile}"} + + cmd = [ + "t_coffee", + "-infile", str(in_path), + "-output", output_format + ] + + if outfile: + cmd.extend(["-outfile", outfile]) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] if outfile else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def t_coffee_extract_from_pdb( + pdb_id: str, + chain: Optional[str] = None, + outfile: Optional[str] = None, +): + """ + Extract sequences or information from PDB files using T-Coffee utilities. + + Args: + pdb_id: PDB ID or path to a PDB file. + chain: Specific chain to extract. + outfile: Output filename. + """ + cmd = ["t_coffee", "-other_pg", "extract_from_pdb", "-pdb", pdb_id] + + if chain: + cmd.extend(["-chain", chain]) + if outfile: + cmd.extend(["-out", outfile]) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [outfile] if outfile else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/t_coffee_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/t_coffee_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..16c8ebf6fe154937ffafd523fff6026e49628f7f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/app/t_coffee_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_t_coffee/app/t_coffee_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_t_coffee' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ea2ab537ebaa5a0b829cc9d7ea6ec5c7d4c7471f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-t_coffee: + build: . + image: mcp-t_coffee:latest + container_name: mcp-t_coffee + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=t_coffee + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..be170ea3bf48d08a8d6d103d174a6c14cc81cdac --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - t_coffee + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_t_coffee/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..043c914d07061e56ab65b062f8ebe7bdf88ae2dd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install tabixpp via conda (e.g., from bioconda) +RUN conda install -c bioconda tabixpp -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/tabixpp_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/tabixpp_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/tabixpp_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/__pycache__/tabixpp_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/__pycache__/tabixpp_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a81c4d3a6b9eacd8c430a275a420c531cfd4bd9 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/__pycache__/tabixpp_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/tabixpp_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/tabixpp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..de22b3daa970f2cf871362f9105a91c252facfb3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/tabixpp_server.py @@ -0,0 +1,80 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_tabixpp' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_tabixpp_executable( + version_flag: bool = False, +) -> Dict[str, Any]: + """ + Attempts to execute the 'tabixpp' command-line tool. + + Based on the provided documentation, 'tabixpp' appears to be a C++ library + wrapper around the tabix project, rather than a standalone command-line tool + with documented subcommands or specific parameters. + + This function attempts to run 'tabixpp' with no arguments or with a common + '--version' flag to check for its existence and basic output. + It is not possible to define specific command-line parameters or subcommands + as they are not present in the provided documentation. + + Args: + version_flag: If True, attempts to run 'tabixpp --version'. Otherwise, + runs 'tabixpp' with no arguments. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any + output files (none expected for this operation). + """ + command = ["tabixpp"] + if version_flag: + command.append("--version") + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + command_executed = " ".join(command) + output_files: List[Path] = [] + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'tabixpp' executable not found. " + "Please ensure it is installed and available in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"An unexpected error occurred: {str(e)}", + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/tabixpp_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/tabixpp_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4eca7532a15b26087db3cc05f8a22373b2dd19a7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/app/tabixpp_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_tabixpp/app/tabixpp_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_tabixpp' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e9fe390142d53e1d38388d15f5a18bcdd6347434 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-tabixpp: + build: . + image: mcp-tabixpp:latest + container_name: mcp-tabixpp + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=tabixpp + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1949fd34e232ed01cb852bd1fb3fd00f3473415f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - tabixpp + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tabixpp/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d5add988a337bffd9172c19c3687c5bb4f1a7b93 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install trimadap via conda (e.g., from bioconda) +RUN conda install -c bioconda trimadap -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/trimadap_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/trimadap_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/trimadap_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/__pycache__/trimadap_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/__pycache__/trimadap_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ac1816b0e195a07d44e92ad990818d25c74bc26 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/__pycache__/trimadap_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/trimadap_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/trimadap_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b0e34c5dc71a8bf9864700baeafbd8e90e33503e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/trimadap_server.py @@ -0,0 +1,108 @@ +from pathlib import Path +from typing import Optional +import subprocess + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_trimadap' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def trimadap( + input_fastq: str, + output_fastq: str, + adapter_5: Optional[str] = None, + adapter_3: Optional[str] = None, + min_match_len: int = 15, + max_error_rate: float = 0.10, + min_read_len: int = 20, + threads: int = 1, +): + """ + Fast but inaccurate adapter trimmer for Illumina reads. + + Args: + input_fastq: Path to the input FASTQ file (can be gzipped). + output_fastq: Path where the trimmed FASTQ output will be saved. + adapter_5: 5'-end adapter sequence to trim. + adapter_3: 3'-end adapter sequence to trim. + min_match_len: Minimum match length for an adapter to be trimmed (default: 15). + max_error_rate: Maximum allowed error rate for adapter matching (default: 0.10). + min_read_len: Minimum length of reads to keep after trimming (default: 20). + threads: Number of threads to use (default: 1). + """ + # Input validation + input_path = Path(input_fastq) + if not input_path.exists(): + return { + "command_executed": "None", + "stdout": "", + "stderr": f"Error: Input file '{input_fastq}' does not exist.", + "output_files": [] + } + + output_path = Path(output_fastq) + # Ensure output directory exists + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Parameter constraints validation + if min_match_len < 1: + return {"error": "min_match_len must be a positive integer."} + if not (0.0 <= max_error_rate <= 1.0): + return {"error": "max_error_rate must be between 0.0 and 1.0."} + if min_read_len < 0: + return {"error": "min_read_len cannot be negative."} + if threads < 1: + return {"error": "threads must be at least 1."} + + # Construct command + # Usage: trimadap [options] + cmd = ["trimadap"] + + if adapter_5: + cmd.extend(["-5", adapter_5]) + if adapter_3: + cmd.extend(["-3", adapter_3]) + + cmd.extend(["-l", str(min_match_len)]) + cmd.extend(["-e", str(max_error_rate)]) + cmd.extend(["-s", str(min_read_len)]) + cmd.extend(["-p", str(threads)]) + + cmd.append(str(input_path)) + + try: + # trimadap outputs the trimmed reads to stdout + with open(output_path, "w") as f_out: + process = subprocess.run( + cmd, + stdout=f_out, + stderr=subprocess.PIPE, + text=True, + check=True + ) + + return { + "command_executed": " ".join(cmd), + "stdout": f"Trimmed reads successfully written to {output_fastq}", + "stderr": process.stderr, + "output_files": [str(output_path)] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": f"Execution failed with return code {e.returncode}: {e.stderr}", + "output_files": [] + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"An unexpected error occurred: {str(e)}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/trimadap_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/trimadap_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..81d3f8a45304aac7238762a405e737062c75158c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/app/trimadap_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_trimadap/app/trimadap_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_trimadap' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..567bf0f89982aa6353607e7c7f15739b4a27bfb3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-trimadap: + build: . + image: mcp-trimadap:latest + container_name: mcp-trimadap + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=trimadap + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c62333ba72bddb2b8bfe7610e48e3ffe281ee74a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - trimadap + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimadap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5363d49cc8c3c7a11b284a31b651a49b4dc90353 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ucsc-bedtobigbed via conda (e.g., from bioconda) +RUN conda install -c bioconda ucsc-bedtobigbed -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ucsc-bedtobigbed_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ucsc-bedtobigbed_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ucsc-bedtobigbed_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/__pycache__/ucsc-bedtobigbed_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/__pycache__/ucsc-bedtobigbed_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6546b0fe72c92ffa9f03d0fba22393be7d15ac81 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/__pycache__/ucsc-bedtobigbed_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/ucsc-bedtobigbed_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/ucsc-bedtobigbed_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b0c44de6bce3b6cd96948e6bf300e36ed6448c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/ucsc-bedtobigbed_server.py @@ -0,0 +1,170 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_ucsc_bedtobigbed' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def bed_to_bigbed( + bed_file: Path, + chrom_sizes_file: Path, + output_bigbed_file: Path, + auto_sql_file: Optional[Path] = None, + bed_type: Optional[str] = None, + delimiter: Optional[str] = None, + extra_index_fields: Optional[List[str]] = None, + block_size: int = 256, + items_per_slot: int = 1024, + uncompressed_blocks: bool = False, + udc_directory: Optional[Path] = None, + max_memory: Optional[str] = None, + temp_directory: Optional[Path] = None, + allow_1000g_chrom_names: bool = False, + warn_on_all_errors: bool = False, + verbose_level: int = 1, +) -> Dict[str, Union[str, List[str]]]: + """ + Converts a BED file to a bigBed file using ucsc-bedtobigbed. + + This tool takes a BED file and a chromosome sizes file to create a binary + bigBed file, which is optimized for display in the UCSC Genome Browser. + + Args: + bed_file: Path to the input BED file. Must exist. + chrom_sizes_file: Path to the chromosome sizes file (e.g., hg38.chrom.sizes). + This file should contain two columns: chromosome name and size. Must exist. + output_bigbed_file: Path for the output bigBed file. Its parent directory will be created if it doesn't exist. + auto_sql_file: Optional path to an autoSql (.as) file defining a custom BED format. + Required for BED files with more than 12 fields or custom fields. Must exist if provided. + bed_type: Optional string specifying the BED format (e.g., "bed3", "bed6", "bed9+2"). + If not specified, the tool attempts to infer it. + delimiter: Optional character to use as a field delimiter if not tab. + By default, the tool expects tab-separated input. + extra_index_fields: Optional list of field names to create extra indexes on. + Each string in the list will be passed as a separate -extraIndex argument. + block_size: The number of items that are grouped into a block in the bigBed file. + Default is 256. Must be a positive integer. + items_per_slot: The number of items that are stored in each slot of the bigBed index. + Default is 1024. Must be a positive integer. + uncompressed_blocks: If True, blocks in the bigBed file will not be compressed. + udc_directory: Optional path to a directory for UDC files (e.g., for remote files). + Must exist if provided. + max_memory: Optional string specifying the maximum memory to use (e.g., "1G", "500M"). + temp_directory: Optional path to a directory for temporary files. + Will be created if it doesn't exist. + allow_1000g_chrom_names: If True, allows 1000Genomes style chromosome names + (e.g., "1" instead of "chr1"). + warn_on_all_errors: If True, warns on all errors, not just the first 1000. + verbose_level: Set verbose level. Default is 1. Must be a non-negative integer. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + + Raises: + FileNotFoundError: If required input files or directories do not exist. + ValueError: If invalid parameter values are provided (e.g., non-positive block_size). + subprocess.CalledProcessError: If the ucsc-bedtobigbed command fails. + """ + # Input validation + if not bed_file.is_file(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + if not chrom_sizes_file.is_file(): + raise FileNotFoundError(f"Chromosome sizes file not found: {chrom_sizes_file}") + if auto_sql_file and not auto_sql_file.is_file(): + raise FileNotFoundError(f"AutoSql file not found: {auto_sql_file}") + if udc_directory and not udc_directory.is_dir(): + raise FileNotFoundError(f"UDC directory not found: {udc_directory}") + if block_size <= 0: + raise ValueError("block_size must be a positive integer.") + if items_per_slot <= 0: + raise ValueError("items_per_slot must be a positive integer.") + if verbose_level < 0: + raise ValueError("verbose_level cannot be negative.") + + # Ensure output directory exists + output_bigbed_file.parent.mkdir(parents=True, exist_ok=True) + + command = ["bedToBigBed"] + + # Add optional parameters + if auto_sql_file: + command.append(f"-as={auto_sql_file.resolve()}") + if bed_type: + command.append(f"-type={bed_type}") + if delimiter: + command.append(f"-delim={delimiter}") + + if extra_index_fields: + for field in extra_index_fields: + command.append(f"-extraIndex={field}") + + command.append(f"-blockSize={block_size}") + command.append(f"-itemsPerSlot={items_per_slot}") + + if uncompressed_blocks: + command.append("-unc") + + if udc_directory: + command.append(f"-udcDir={udc_directory.resolve()}") + + if max_memory: + command.append(f"-maxMem={max_memory}") + + if temp_directory: + temp_directory.mkdir(parents=True, exist_ok=True) + command.append(f"-tempDir={temp_directory.resolve()}") + + if allow_1000g_chrom_names: + command.append("-allow1000g") + + if warn_on_all_errors: + command.append("-warnOnAllErrors") + + command.append(f"-verbose={verbose_level}") + + # Add positional arguments + command.extend([ + str(bed_file.resolve()), + str(chrom_sizes_file.resolve()), + str(output_bigbed_file.resolve()) + ]) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + output_files = [str(output_bigbed_file.resolve())] + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"bedToBigBed command failed with exit code {e.returncode}", + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: bedToBigBed executable not found. Please ensure it is in your PATH.", + "output_files": [], + "error": "bedToBigBed executable not found.", + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/ucsc-bedtobigbed_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/ucsc-bedtobigbed_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cf0e6d6ebcad0addccd59211a565e9a9094923b7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/app/ucsc-bedtobigbed_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ucsc-bedtobigbed/app/ucsc-bedtobigbed_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_ucsc_bedtobigbed' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0f62bb91a7bfb557f52f80241dcbf4d06f5bb82b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ucsc-bedtobigbed: + build: . + image: mcp-ucsc-bedtobigbed:latest + container_name: mcp-ucsc-bedtobigbed + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ucsc-bedtobigbed + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d56ac5c51316dd34bc7cf388d0ce1e452431c313 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ucsc-bedtobigbed + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-bedtobigbed/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_umi_tools/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_umi_tools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_umi_tools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_upimapi/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_upimapi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_upimapi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2ec170992dd2cf69a7708eb1bbef9f7fa8650bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install vardict-java via conda (e.g., from bioconda) +RUN conda install -c bioconda vardict-java -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/vardict-java_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/vardict-java_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/vardict-java_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/__pycache__/vardict-java_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/__pycache__/vardict-java_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6886ef1795cad18c2dc99dd593a4f19a79e5630 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/__pycache__/vardict-java_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/vardict-java_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/vardict-java_server.py new file mode 100644 index 0000000000000000000000000000000000000000..299d33fcf43450efd4601c907ebb7e717c3dffd6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/vardict-java_server.py @@ -0,0 +1,358 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_vardict_java' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def vardict_java( + reference_fasta: str, + bam_path: str, + sample_name: str, + bed_file: Optional[str] = None, + region: Optional[str] = None, + min_af: float = 0.01, + chrom_col: int = 1, + start_col: int = 2, + end_col: int = 3, + gene_col: int = 4, + min_reads: int = 2, + min_base_qual: float = 22.5, + min_pos: int = 5, + hq_lq_ratio: float = 1.5, + min_map_qual: Optional[float] = None, + mnv_dist: int = 2, + realign: int = 1, + no_sv: bool = False, + all_positions: bool = False, + amplicon_params: str = "10:0.95", + output_file: Optional[str] = None, +) -> Dict[str, Any]: + """ + Run VarDictJava for variant discovery. + + Args: + reference_fasta: Path to the reference genome in FASTA format. + bam_path: Path to BAM file(s). For paired mode, use 'tumor.bam|normal.bam'. + sample_name: Sample name for the output. + bed_file: Path to target regions in BED format. + region: Region to call variants in (e.g., 'chr7:55270300-55270348:EGFR'). + min_af: Minimum allele frequency threshold (default: 0.01). + chrom_col: Column index for chromosome in BED file (default: 1). + start_col: Column index for start position in BED file (default: 2). + end_col: Column index for end position in BED file (default: 3). + gene_col: Column index for gene name in BED file (default: 4). + min_reads: Minimum number of high-quality reads supporting variant (default: 2). + min_base_qual: Minimum mean base quality (phred score) (default: 22.5). + min_pos: Minimum mean position of the variant in reads (default: 5). + hq_lq_ratio: Minimum ratio of high-quality reads to low-quality reads (default: 1.5). + min_map_qual: Minimum mean mapping quality (default: no filtering). + mnv_dist: Combine SNVs into MNV if closer than this distance (default: 2). + realign: Enable realignment of insertions/deletions (1 to enable, 0 to disable). + no_sv: Disable structural variant calling. + all_positions: Output all positions (useful for amplicon mode). + amplicon_params: Criteria for discarding reads far from segments (default: '10:0.95'). + output_file: Path to save the intermediate tabular output. + """ + # Input validation + ref_path = Path(reference_fasta) + if not ref_path.exists(): + return {"error": f"Reference FASTA not found: {reference_fasta}"} + + # Check BAM paths (handle paired pipe syntax) + for b_path in bam_path.split('|'): + if not Path(b_path).exists(): + return {"error": f"BAM file not found: {b_path}"} + + if not bed_file and not region: + return {"error": "Either bed_file or region (-R) must be provided."} + + cmd = [ + "VarDict", + "-G", str(ref_path), + "-f", str(min_af), + "-N", sample_name, + "-b", bam_path, + "-c", str(chrom_col), + "-S", str(start_col), + "-E", str(end_col), + "-g", str(gene_col), + "-r", str(min_reads), + "-q", str(min_base_qual), + "-P", str(min_pos), + "-o", str(hq_lq_ratio), + "-X", str(mnv_dist), + "-k", str(realign), + "-a", amplicon_params + ] + + if region: + cmd.extend(["-R", region]) + if no_sv: + cmd.append("-U") + if all_positions: + cmd.append("-p") + if min_map_qual is not None: + cmd.extend(["-O", str(min_map_qual)]) + + if bed_file: + bed_p = Path(bed_file) + if not bed_p.exists(): + return {"error": f"BED file not found: {bed_file}"} + cmd.append(str(bed_p)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_file: + out_p = Path(output_file) + out_p.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Output written to file", + "stderr": result.stderr, + "output_files": [str(out_p)] + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def test_strand_bias( + input_file: str, + output_file: Optional[str] = None, +) -> Dict[str, Any]: + """ + Perform statistical test for strand bias using teststrandbias.R (Single Sample). + + Args: + input_file: Path to the intermediate tabular output from VarDict. + output_file: Path to save the output with strand bias statistics. + """ + in_p = Path(input_file) + if not in_p.exists(): + return {"error": f"Input file not found: {input_file}"} + + # Assuming teststrandbias.R is in the PATH or VarDict directory + cmd = ["teststrandbias.R"] + + try: + with open(in_p, 'r') as f_in: + result = subprocess.run(cmd, stdin=f_in, capture_output=True, text=True, check=True) + + if output_file: + out_p = Path(output_file) + out_p.write_text(result.stdout) + return { + "command_executed": f"cat {input_file} | {' '.join(cmd)}", + "stdout": "Output written to file", + "stderr": result.stderr, + "output_files": [str(out_p)] + } + + return { + "command_executed": f"cat {input_file} | {' '.join(cmd)}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def test_somatic( + input_file: str, + output_file: Optional[str] = None, +) -> Dict[str, Any]: + """ + Perform statistical test for somatic variants using testsomatic.R (Paired Sample). + + Args: + input_file: Path to the intermediate tabular output from VarDict (paired mode). + output_file: Path to save the output with somatic statistics. + """ + in_p = Path(input_file) + if not in_p.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["testsomatic.R"] + + try: + with open(in_p, 'r') as f_in: + result = subprocess.run(cmd, stdin=f_in, capture_output=True, text=True, check=True) + + if output_file: + out_p = Path(output_file) + out_p.write_text(result.stdout) + return { + "command_executed": f"cat {input_file} | {' '.join(cmd)}", + "stdout": "Output written to file", + "stderr": result.stderr, + "output_files": [str(out_p)] + } + + return { + "command_executed": f"cat {input_file} | {' '.join(cmd)}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def var2vcf_valid( + input_file: str, + sample_name: str, + min_af: float = 0.01, + ext_info: bool = True, + all_variants: bool = False, + output_vcf: Optional[str] = None, +) -> Dict[str, Any]: + """ + Convert VarDict intermediate format to VCF for single sample. + + Args: + input_file: Path to the output from teststrandbias.R. + sample_name: Sample name for the VCF header. + min_af: Minimum allele frequency threshold (default: 0.01). + ext_info: Output extended information (default: True). + all_variants: Output all variants at a position, not just the one with highest AF. + output_vcf: Path to save the final VCF file. + """ + in_p = Path(input_file) + if not in_p.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = [ + "var2vcf_valid.pl", + "-N", sample_name, + "-f", str(min_af) + ] + + if ext_info: + cmd.append("-E") + if all_variants: + cmd.append("-A") + + try: + with open(in_p, 'r') as f_in: + result = subprocess.run(cmd, stdin=f_in, capture_output=True, text=True, check=True) + + if output_vcf: + out_p = Path(output_vcf) + out_p.write_text(result.stdout) + return { + "command_executed": f"cat {input_file} | {' '.join(cmd)}", + "stdout": "VCF written to file", + "stderr": result.stderr, + "output_files": [str(out_p)] + } + + return { + "command_executed": f"cat {input_file} | {' '.join(cmd)}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def var2vcf_paired( + input_file: str, + sample_names: str, + min_af: float = 0.01, + all_variants: bool = False, + min_matches: Optional[int] = None, + somatic_only: bool = False, + output_vcf: Optional[str] = None, +) -> Dict[str, Any]: + """ + Convert VarDict intermediate format to VCF for paired samples. + + Args: + input_file: Path to the output from testsomatic.R. + sample_names: Sample names in 'tumor|normal' format. + min_af: Minimum allele frequency threshold (default: 0.01). + all_variants: Output all variants at a position, not just the one with highest AF. + min_matches: Minimum matches for a variant to be considered (optional). + somatic_only: Only output somatic variants (optional). + output_vcf: Path to save the final VCF file. + """ + in_p = Path(input_file) + if not in_p.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = [ + "var2vcf_paired.pl", + "-N", sample_names, + "-f", str(min_af) + ] + + if all_variants: + cmd.append("-A") + if min_matches is not None: + cmd.extend(["-M", str(min_matches)]) + if somatic_only: + cmd.append("-S") + + try: + with open(in_p, 'r') as f_in: + result = subprocess.run(cmd, stdin=f_in, capture_output=True, text=True, check=True) + + if output_vcf: + out_p = Path(output_vcf) + out_p.write_text(result.stdout) + return { + "command_executed": f"cat {input_file} | {' '.join(cmd)}", + "stdout": "VCF written to file", + "stderr": result.stderr, + "output_files": [str(out_p)] + } + + return { + "command_executed": f"cat {input_file} | {' '.join(cmd)}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/vardict-java_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/vardict-java_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f57488428631929e3112c9c5f0e030fb0649b9c9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/app/vardict-java_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_vardict-java/app/vardict-java_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_vardict_java' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4f5ecc9793000b84ad1ae1f08849fda6abba8cbe --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-vardict-java: + build: . + image: mcp-vardict-java:latest + container_name: mcp-vardict-java + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=vardict-java + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8fa188efcb53123883dbdc10cd466dadd0e67255 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - vardict-java + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vardict-java/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vcflib/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vcflib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vcflib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f8dcad7b877ae7fd7d20ef8f91c6ae35a2e2037b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install womtool via conda (e.g., from bioconda) +RUN conda install -c bioconda womtool -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/womtool_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/womtool_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/womtool_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/__pycache__/womtool_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/__pycache__/womtool_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88302f15356c662f434762013c8f9c1035f5f5cb Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/__pycache__/womtool_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/womtool_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/womtool_server.py new file mode 100644 index 0000000000000000000000000000000000000000..98c71bab436b04159c38dab9cd5be21ca692b1fb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/womtool_server.py @@ -0,0 +1,359 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Literal, Dict, Any + +# Helper function to run the Java command for womtool +def _run_womtool_command( + womtool_jar_path: Path, + action: str, + params: List[str], + java_options: Optional[List[str]] = None, + capture_output_to_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Internal helper to execute womtool commands. + + Args: + womtool_jar_path: Path to the womtool.jar executable. + action: The womtool subcommand to execute (e.g., "validate", "inputs"). + params: A list of string arguments specific to the womtool subcommand. + java_options: Optional list of additional Java options (e.g., JVM memory settings). + capture_output_to_file: Optional Path to a file where stdout should be redirected. + If None, stdout is captured as a string. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not womtool_jar_path.is_file(): + raise FileNotFoundError(f"womtool JAR file not found at: {womtool_jar_path}") + + command = ["java"] + if java_options: + command.extend(java_options) + command.extend(["-jar", str(womtool_jar_path), action]) + command.extend(params) + + stdout_content = "" + stderr_content = "" + output_files = [] + + try: + if capture_output_to_file: + # Ensure the directory for the output file exists + capture_output_to_file.parent.mkdir(parents=True, exist_ok=True) + with open(capture_output_to_file, "w") as f: + process = subprocess.run( + command, + stdout=f, + stderr=subprocess.PIPE, + check=False, + text=True, + encoding="utf-8" + ) + stderr_content = process.stderr + output_files.append(str(capture_output_to_file)) + else: + process = subprocess.run( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + text=True, + encoding="utf-8" + ) + stdout_content = process.stdout + stderr_content = process.stderr + + if process.returncode != 0: + return { + "command_executed": " ".join(command), + "stdout": stdout_content, + "stderr": stderr_content, + "error": f"womtool command failed with exit code {process.returncode}", + "output_files": output_files, + } + + return { + "command_executed": " ".join(command), + "stdout": stdout_content, + "stderr": stderr_content, + "output_files": output_files, + } + + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'java' command not found. Please ensure Java is installed and in your PATH.", + "error": "Java executable not found.", + "output_files": [], + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": stdout_content, + "stderr": stderr_content, + "error": f"An unexpected error occurred: {e}", + "output_files": output_files, + } + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_womtool' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def womtool_validate( + wdl_file: Path, + womtool_jar_path: Path, + list_dependencies: bool = False, + java_options: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Performs full validation of a WDL file including syntax and semantic checking. + Optionally lists files referenced in import statements. + + Args: + wdl_file: Path to the WDL file to validate. + womtool_jar_path: Path to the womtool.jar executable. + list_dependencies: If True, lists files referenced in import statements + for successful validations. + java_options: Optional list of additional Java options (e.g., JVM memory settings). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not wdl_file.is_file(): + raise FileNotFoundError(f"WDL file not found at: {wdl_file}") + + params = [] + if list_dependencies: + params.append("--list-dependencies") + params.append(str(wdl_file)) + + return _run_womtool_command( + womtool_jar_path=womtool_jar_path, + action="validate", + params=params, + java_options=java_options, + ) + + +@mcp.tool() +def womtool_inputs( + wdl_file: Path, + womtool_jar_path: Path, + java_options: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Examines a WDL file with one workflow, computes all the inputs needed for that + workflow, and outputs a JSON template to stdout. + + Args: + wdl_file: Path to the WDL file. + womtool_jar_path: Path to the womtool.jar executable. + java_options: Optional list of additional Java options (e.g., JVM memory settings). + + Returns: + A dictionary containing the command executed, stdout (JSON template), stderr, + and any output files. + """ + if not wdl_file.is_file(): + raise FileNotFoundError(f"WDL file not found at: {wdl_file}") + + params = [str(wdl_file)] + + return _run_womtool_command( + womtool_jar_path=womtool_jar_path, + action="inputs", + params=params, + java_options=java_options, + ) + + +@mcp.tool() +def womtool_highlight( + wdl_file: Path, + output_type: Literal["html", "console"], + womtool_jar_path: Path, + java_options: Optional[List[str]] = None, + output_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Reformats and colorizes/tags a WDL file. + Output can be HTML (with tags) or colorized console text. + + Args: + wdl_file: Path to the WDL file to highlight. + output_type: The desired output format ("html" or "console"). + womtool_jar_path: Path to the womtool.jar executable. + java_options: Optional list of additional Java options (e.g., JVM memory settings). + output_file: Optional path to write the output. If 'html' output_type is chosen + and this is not provided, a temporary HTML file will be created. + If 'console' output_type is chosen, output is always to stdout + unless this is provided. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not wdl_file.is_file(): + raise FileNotFoundError(f"WDL file not found at: {wdl_file}") + + params = [str(wdl_file), output_type] + + capture_to_file = None + if output_type == "html": + if output_file: + capture_to_file = output_file + else: + # Create a temporary file for HTML output if not specified + temp_output = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".html") + temp_output.close() + capture_to_file = Path(temp_output.name) + elif output_file: + # If console output is requested but output_file is provided, redirect stdout + capture_to_file = output_file + + return _run_womtool_command( + womtool_jar_path=womtool_jar_path, + action="highlight", + params=params, + java_options=java_options, + capture_output_to_file=capture_to_file, + ) + + +@mcp.tool() +def womtool_parse( + wdl_file: Path, + womtool_jar_path: Path, + java_options: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Compares a WDL file against the grammar and writes out an abstract syntax tree + if it is valid, and a syntax error otherwise. Note that higher-level AST checks + are not done via this sub-command; 'validate' should be used for full validation. + + Args: + wdl_file: Path to the WDL file to parse. + womtool_jar_path: Path to the womtool.jar executable. + java_options: Optional list of additional Java options (e.g., JVM memory settings). + + Returns: + A dictionary containing the command executed, stdout (AST), stderr, + and any output files. + """ + if not wdl_file.is_file(): + raise FileNotFoundError(f"WDL file not found at: {wdl_file}") + + params = [str(wdl_file)] + + return _run_womtool_command( + womtool_jar_path=womtool_jar_path, + action="parse", + params=params, + java_options=java_options, + ) + + +@mcp.tool() +def womtool_graph( + wdl_file: Path, + womtool_jar_path: Path, + all_nodes: bool = False, + java_options: Optional[List[str]] = None, + output_dot_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Generates the data-flow graph of a WDL file in .dot format. + Note: graph currently DOES NOT WORK on version 1.0 workflows. + + Args: + wdl_file: Path to the WDL file. + womtool_jar_path: Path to the womtool.jar executable. + all_nodes: If True, all WDL graph nodes (including task declarations and call outputs) + become nodes in the generated DAG. + java_options: Optional list of additional Java options (e.g., JVM memory settings). + output_dot_file: Optional path to write the .dot graph output. If not provided, + a temporary .dot file will be created. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the generated .dot file. + """ + if not wdl_file.is_file(): + raise FileNotFoundError(f"WDL file not found at: {wdl_file}") + + params = [] + if all_nodes: + params.append("--all") + params.append(str(wdl_file)) + + capture_to_file = output_dot_file + if not capture_to_file: + temp_output = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".dot") + temp_output.close() + capture_to_file = Path(temp_output.name) + + return _run_womtool_command( + womtool_jar_path=womtool_jar_path, + action="graph", + params=params, + java_options=java_options, + capture_output_to_file=capture_to_file, + ) + + +@mcp.tool() +def womtool_womgraph( + wdl_file: Path, + womtool_jar_path: Path, + ancillary_files: Optional[List[Path]] = None, + java_options: Optional[List[str]] = None, + output_dot_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Reads a WDL file, converts it to a Workflow Object Model (WOM) representation, + and prints out a graph of the WOM produced in .dot format. + + Args: + wdl_file: Path to the main WDL file. + womtool_jar_path: Path to the womtool.jar executable. + ancillary_files: Optional list of paths to imported WDL files. + java_options: Optional list of additional Java options (e.g., JVM memory settings). + output_dot_file: Optional path to write the .dot graph output. If not provided, + a temporary .dot file will be created. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the generated .dot file. + """ + if not wdl_file.is_file(): + raise FileNotFoundError(f"WDL file not found at: {wdl_file}") + if ancillary_files: + for f in ancillary_files: + if not f.is_file(): + raise FileNotFoundError(f"Ancillary file not found at: {f}") + + params = [str(wdl_file)] + if ancillary_files: + params.extend([str(f) for f in ancillary_files]) + + capture_to_file = output_dot_file + if not capture_to_file: + temp_output = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".dot") + temp_output.close() + capture_to_file = Path(temp_output.name) + + return _run_womtool_command( + womtool_jar_path=womtool_jar_path, + action="womgraph", + params=params, + java_options=java_options, + capture_output_to_file=capture_to_file, + ) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/womtool_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/womtool_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..728bb6d60ad998bf0bcafaca3bf5939201d4aa04 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/app/womtool_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_womtool/app/womtool_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_womtool' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..33da8392afaa2cd335bdacb040d698d59c495ff4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-womtool: + build: . + image: mcp-womtool:latest + container_name: mcp-womtool + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=womtool + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..345d4dfce4c34e2a40740fd1e0ba7a0709695637 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - womtool + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_womtool/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff3d2f74884826a42033add3d0a4386784d23c27 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install xclone via conda (e.g., from bioconda) +RUN conda install -c bioconda xclone -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/xclone_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/xclone_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/xclone_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/__pycache__/xclone_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/__pycache__/xclone_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e77c08d749905adb35e001e11c47a213bafc0c7 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/__pycache__/xclone_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/xclone_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/xclone_server.py new file mode 100644 index 0000000000000000000000000000000000000000..802b2592ebd04103cccf7bcb159c2e2b3ae0890e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/xclone_server.py @@ -0,0 +1,295 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_xclone' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def xclone_preprocess( + input_bam: str, + barcode_file: str, + gtf_file: str, + output_dir: str, + genome: str = "hg38", + n_cores: int = 1, + sample_name: str = "sample", +): + """ + Preprocess BAM files for xClone analysis, including RDR and BAF data preparation. + + Args: + input_bam: Path to the input BAM file (indexed). + barcode_file: Path to the cell barcode file (TSV/TXT). + gtf_file: Path to the gene annotation GTF file. + output_dir: Directory to save preprocessed results. + genome: Reference genome version (e.g., hg38, mm10). + n_cores: Number of CPU cores to use. + sample_name: Name of the sample for output prefixing. + """ + # Input validation + bam_path = Path(input_bam) + bc_path = Path(barcode_file) + gtf_path = Path(gtf_file) + out_path = Path(output_dir) + + if not bam_path.exists(): + return {"error": f"BAM file not found: {input_bam}"} + if not bc_path.exists(): + return {"error": f"Barcode file not found: {barcode_file}"} + if not gtf_path.exists(): + return {"error": f"GTF file not found: {gtf_file}"} + + out_path.mkdir(parents=True, exist_ok=True) + + # Construct command + # Note: xclone often uses a specific entry point or script for preprocessing + cmd = [ + "xclone-preprocess", + "--input_bam", str(bam_path), + "--barcode", str(bc_path), + "--gtf", str(gtf_path), + "--outdir", str(out_path), + "--genome", genome, + "--threads", str(n_cores), + "--sample", sample_name + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(f) for f in out_path.glob("*")] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xclone_run_rdr( + input_h5ad: str, + output_dir: str, + config_file: Optional[str] = None, + n_cores: int = 1, + smoothing: bool = True, +): + """ + Run the Read Depth Ratio (RDR) module of xClone to detect CNVs. + + Args: + input_h5ad: Path to the preprocessed RDR AnnData file (.h5ad). + output_dir: Directory to save RDR results. + config_file: Optional path to a YAML configuration file. + n_cores: Number of CPU cores for parallel processing. + smoothing: Whether to apply spatial/genomic smoothing. + """ + h5ad_path = Path(input_h5ad) + out_path = Path(output_dir) + + if not h5ad_path.exists(): + return {"error": f"Input H5AD file not found: {input_h5ad}"} + + out_path.mkdir(parents=True, exist_ok=True) + + cmd = [ + "xclone-rdr", + "--input", str(h5ad_path), + "--outdir", str(out_path), + "--threads", str(n_cores) + ] + + if config_file: + if Path(config_file).exists(): + cmd.extend(["--config", config_file]) + + if smoothing: + cmd.append("--smoothing") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(f) for f in out_path.glob("*.h5ad")] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xclone_run_baf( + input_h5ad: str, + output_dir: str, + config_file: Optional[str] = None, + n_cores: int = 1, + min_counts: int = 20, +): + """ + Run the B-Allele Frequency (BAF) module of xClone to detect CNVs and LOH. + + Args: + input_h5ad: Path to the preprocessed BAF AnnData file (.h5ad). + output_dir: Directory to save BAF results. + config_file: Optional path to a YAML configuration file. + n_cores: Number of CPU cores for parallel processing. + min_counts: Minimum allele counts for a site to be included. + """ + h5ad_path = Path(input_h5ad) + out_path = Path(output_dir) + + if not h5ad_path.exists(): + return {"error": f"Input H5AD file not found: {input_h5ad}"} + + out_path.mkdir(parents=True, exist_ok=True) + + cmd = [ + "xclone-baf", + "--input", str(h5ad_path), + "--outdir", str(out_path), + "--threads", str(n_cores), + "--min_counts", str(min_counts) + ] + + if config_file: + if Path(config_file).exists(): + cmd.extend(["--config", config_file]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(f) for f in out_path.glob("*.h5ad")] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xclone_combine( + rdr_h5ad: str, + baf_h5ad: str, + output_dir: str, + config_file: Optional[str] = None, + combine_method: str = "joint", +): + """ + Combine RDR and BAF results for integrated CNV calling. + + Args: + rdr_h5ad: Path to the processed RDR AnnData file. + baf_h5ad: Path to the processed BAF AnnData file. + output_dir: Directory to save combined results. + config_file: Optional path to a YAML configuration file. + combine_method: Method for integration ('joint' or 'weighted'). + """ + rdr_path = Path(rdr_h5ad) + baf_path = Path(baf_h5ad) + out_path = Path(output_dir) + + if not rdr_path.exists(): + return {"error": f"RDR file not found: {rdr_h5ad}"} + if not baf_path.exists(): + return {"error": f"BAF file not found: {baf_h5ad}"} + + out_path.mkdir(parents=True, exist_ok=True) + + cmd = [ + "xclone-combine", + "--rdr", str(rdr_path), + "--baf", str(baf_path), + "--outdir", str(out_path), + "--method", combine_method + ] + + if config_file: + if Path(config_file).exists(): + cmd.extend(["--config", config_file]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(f) for f in out_path.glob("*.h5ad")] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xclone_plot( + input_h5ad: str, + output_dir: str, + plot_type: str = "heatmap", + genome: str = "hg38", + feature: str = "cnv", +): + """ + Generate visualizations for xClone results. + + Args: + input_h5ad: Path to the final xClone AnnData file. + output_dir: Directory to save plots. + plot_type: Type of plot to generate (heatmap, scatter, genome_view). + genome: Reference genome for coordinate mapping. + feature: The data layer to plot (e.g., 'cnv', 'rdr', 'baf'). + """ + h5ad_path = Path(input_h5ad) + out_path = Path(output_dir) + + if not h5ad_path.exists(): + return {"error": f"Input H5AD file not found: {input_h5ad}"} + + out_path.mkdir(parents=True, exist_ok=True) + + cmd = [ + "xclone-plot", + "--input", str(h5ad_path), + "--outdir", str(out_path), + "--type", plot_type, + "--genome", genome, + "--feature", feature + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(f) for f in out_path.glob("*.pdf")] + [str(f) for f in out_path.glob("*.png")] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/xclone_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/xclone_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ae929c769298921a1d6282abc4b1998da1b406ff --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/app/xclone_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_xclone/app/xclone_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_xclone' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..fafd7349f800dcf5e9750dc9f95261b05f2138de --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-xclone: + build: . + image: mcp-xclone:latest + container_name: mcp-xclone + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=xclone + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f75472aa3b0f3bbe5893196bd903f66405e6d2f3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - xclone + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_xclone/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4f9549fc105d7a52e56c12ef90556549a065d976 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install yacrd via conda (e.g., from bioconda) +RUN conda install -c bioconda yacrd -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/yacrd_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/yacrd_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/yacrd_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/__pycache__/yacrd_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/__pycache__/yacrd_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a67a15b7ec66059036ed05a144a942cd0fb01110 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/__pycache__/yacrd_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/yacrd_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/yacrd_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fc8869fbc3561c39841c33829a97dbaae55bda --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/yacrd_server.py @@ -0,0 +1,468 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any +import tempfile +import shutil + +# Placeholder for the ondisk prefix that will be replaced with a safe temporary path +ONDISK_PREFIX_PLACEHOLDER = "__MCP_ONDISK_PREFIX_PLACEHOLDER__" + +def _run_yacrd_command( + command_args: List[str], + output_files: List[Path], + user_ondisk_prefix: Optional[str] = None +) -> Dict[str, Any]: + """ + Helper function to run yacrd commands and handle output. + + Args: + command_args: A list of command-line arguments for yacrd. + output_files: A list of expected output file paths to check for existence. + user_ondisk_prefix: The user-provided prefix for on-disk temporary files. + If provided, a safe temporary directory will be used. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + temp_dir_obj = None + final_command_args = list(command_args) # Work with a mutable copy + + if user_ondisk_prefix: + temp_dir_obj = tempfile.TemporaryDirectory() + temp_dir_path = Path(temp_dir_obj.name) + # yacrd will create files like temp_dir_path/user_ondisk_prefix.0 + # If user_ondisk_prefix contains path separators, yacrd might delete the parent. + # By using temp_dir_path as the parent, we ensure only our temporary directory is affected. + actual_ondisk_path_for_yacrd = str(temp_dir_path / user_ondisk_prefix) + + # Find and replace the placeholder for -d/--ondisk + try: + ondisk_idx = final_command_args.index(ONDISK_PREFIX_PLACEHOLDER) + final_command_args[ondisk_idx] = actual_ondisk_path_for_yacrd + except ValueError: + # This should not happen if _build_base_options is correctly used with ondisk_prefix + pass + + cmd = ["yacrd"] + final_command_args + command_executed = " ".join(map(str, cmd)) + + stdout = "" + stderr = "" + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + error_output = { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"yacrd command failed with exit code {e.returncode}", + "output_files": [] + } + return error_output + except FileNotFoundError: + error_output = { + "command_executed": command_executed, + "stdout": "", + "stderr": "yacrd executable not found. Please ensure it is installed and in your PATH.", + "error": "yacrd executable not found", + "output_files": [] + } + return error_output + finally: + if temp_dir_obj: + temp_dir_obj.cleanup() # Ensure cleanup after success or any error + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(f) for f in output_files if f.exists()] + } + +def _build_base_options( + coverage_threshold: int, + ondisk_prefix: Optional[str], + not_coverage_ratio: float, + ondisk_buffer_size: int, + read_buffer_size: int, + threads: int, +) -> List[str]: + """ + Builds the common base options for yacrd. + + Args: + coverage_threshold: If coverage reaches this value, the region is marked as bad. + ondisk_prefix: The user-provided prefix for on-disk temporary files. + not_coverage_ratio: If the ratio of bad region length on total length is lower than + this value, the read is marked as NotCovered. + ondisk_buffer_size: Buffer size for on-disk mode. + read_buffer_size: Buffer size for reading PAF file. + threads: Number of threads use by yacrd. + + Returns: + A list of command-line arguments for the common yacrd options. + """ + options = [] + + if coverage_threshold < 0: + raise ValueError("Coverage threshold must be non-negative.") + options.extend(["-c", str(coverage_threshold)]) + + if ondisk_prefix is not None: + options.extend(["-d", ONDISK_PREFIX_PLACEHOLDER]) # Add placeholder for later replacement + + if not 0.0 <= not_coverage_ratio <= 1.0: + raise ValueError("Not-coverage ratio must be between 0.0 and 1.0.") + options.extend(["-n", str(not_coverage_ratio)]) + + if ondisk_buffer_size <= 0: + raise ValueError("Ondisk buffer size must be positive.") + options.extend(["--ondisk-buffer-size", str(ondisk_buffer_size)]) + + if read_buffer_size <= 0: + raise ValueError("Read buffer size must be positive.") + options.extend(["--read-buffer-size", str(read_buffer_size)]) + + if threads < 0: + raise ValueError("Number of threads must be non-negative.") + options.extend(["-t", str(threads)]) + + return options + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_yacrd' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def yacrd_report( + input_overlap_file: Path, + output_report_file: Path, + coverage_threshold: int = 0, + ondisk_prefix: Optional[str] = None, + not_coverage_ratio: float = 0.8, + ondisk_buffer_size: int = 64000000, + read_buffer_size: int = 8192, + threads: int = 1, +) -> Dict[str, Any]: + """ + Detects chimeric and not-covered regions in long reads based on overlap mapping results + and generates a yacrd report file. + + Args: + input_overlap_file: Path to input overlap file (.paf|.m4|.mhap) or yacrd report (.yacrd). + Format is autodetected and compression is allowed (gz|bzip2|lzma). + output_report_file: Path to the output yacrd report file. + coverage_threshold: If coverage reaches this value, the region is marked as bad. + Default is 0. + ondisk_prefix: yacrd switches to 'ondisk' mode which will reduce memory usage but + increase computation time. The value passed as a parameter is used + as a prefix for the temporary files created by yacrd. If None, + on-disk mode is not used. + not_coverage_ratio: If the ratio of bad region length on total length is lower than + this value, the read is marked as NotCovered. Default is 0.8. + ondisk_buffer_size: With the default value, yacrd in 'ondisk' mode uses around 1 GBytes. + You can increase to reduce runtime but increase memory usage. + Default is 64000000. + read_buffer_size: Control the size of the buffer used to read paf file. Default is 8192. + threads: Number of threads use by yacrd. 0 means all threads available. Default is 1. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if not input_overlap_file.is_file(): + raise FileNotFoundError(f"Input overlap file not found: {input_overlap_file}") + if not output_report_file.parent.is_dir(): + output_report_file.parent.mkdir(parents=True, exist_ok=True) + + base_options = _build_base_options( + coverage_threshold, ondisk_prefix, not_coverage_ratio, + ondisk_buffer_size, read_buffer_size, threads + ) + + command_args = [ + "-i", str(input_overlap_file), + "-o", str(output_report_file), + ] + base_options + + result = _run_yacrd_command(command_args, [output_report_file], user_ondisk_prefix=ondisk_prefix) + return result + +@mcp.tool() +def yacrd_filter( + input_overlap_file: Path, + output_report_file: Path, + input_sequence_file: Path, + output_sequence_file: Path, + coverage_threshold: int = 0, + ondisk_prefix: Optional[str] = None, + not_coverage_ratio: float = 0.8, + ondisk_buffer_size: int = 64000000, + read_buffer_size: int = 8192, + threads: int = 1, +) -> Dict[str, Any]: + """ + Filters a sequence file, removing records marked as Chimeric or NotCovered + based on an internally generated yacrd report. + + Args: + input_overlap_file: Path to input overlap file (.paf|.m4|.mhap). + Used to generate the internal yacrd report. + output_report_file: Path to the intermediate yacrd report file that will be generated. + This file is used internally by the filter subcommand. + input_sequence_file: Path to the input sequence file (.fasta|.fastq). + output_sequence_file: Path to the output filtered sequence file. + coverage_threshold: If coverage reaches this value, the region is marked as bad. + Default is 0. + ondisk_prefix: yacrd switches to 'ondisk' mode which will reduce memory usage but + increase computation time. The value passed as a parameter is used + as a prefix for the temporary files created by yacrd. If None, + on-disk mode is not used. + not_coverage_ratio: If the ratio of bad region length on total length is lower than + this value, the read is marked as NotCovered. Default is 0.8. + ondisk_buffer_size: With the default value, yacrd in 'ondisk' mode uses around 1 GBytes. + You can increase to reduce runtime but increase memory usage. + Default is 64000000. + read_buffer_size: Control the size of the buffer used to read paf file. Default is 8192. + threads: Number of threads use by yacrd. 0 means all threads available. Default is 1. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if not input_overlap_file.is_file(): + raise FileNotFoundError(f"Input overlap file not found: {input_overlap_file}") + if not input_sequence_file.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {input_sequence_file}") + if not output_report_file.parent.is_dir(): + output_report_file.parent.mkdir(parents=True, exist_ok=True) + if not output_sequence_file.parent.is_dir(): + output_sequence_file.parent.mkdir(parents=True, exist_ok=True) + + base_options = _build_base_options( + coverage_threshold, ondisk_prefix, not_coverage_ratio, + ondisk_buffer_size, read_buffer_size, threads + ) + + command_args = [ + "-i", str(input_overlap_file), + "-o", str(output_report_file), + "filter", + "-i", str(input_sequence_file), + "-o", str(output_sequence_file), + ] + base_options + + result = _run_yacrd_command(command_args, [output_report_file, output_sequence_file], user_ondisk_prefix=ondisk_prefix) + return result + +@mcp.tool() +def yacrd_extract( + input_overlap_file: Path, + output_report_file: Path, + input_sequence_file: Path, + output_sequence_file: Path, + coverage_threshold: int = 0, + ondisk_prefix: Optional[str] = None, + not_coverage_ratio: float = 0.8, + ondisk_buffer_size: int = 64000000, + read_buffer_size: int = 8192, + threads: int = 1, +) -> Dict[str, Any]: + """ + Extracts records marked as Chimeric or NotCovered from a sequence file + based on an internally generated yacrd report. + + Args: + input_overlap_file: Path to input overlap file (.paf|.m4|.mhap). + Used to generate the internal yacrd report. + output_report_file: Path to the intermediate yacrd report file that will be generated. + This file is used internally by the extract subcommand. + input_sequence_file: Path to the input sequence file (.fasta|.fastq). + output_sequence_file: Path to the output extracted sequence file. + coverage_threshold: If coverage reaches this value, the region is marked as bad. + Default is 0. + ondisk_prefix: yacrd switches to 'ondisk' mode which will reduce memory usage but + increase computation time. The value passed as a parameter is used + as a prefix for the temporary files created by yacrd. If None, + on-disk mode is not used. + not_coverage_ratio: If the ratio of bad region length on total length is lower than + this value, the read is marked as NotCovered. Default is 0.8. + ondisk_buffer_size: With the default value, yacrd in 'ondisk' mode uses around 1 GBytes. + You can increase to reduce runtime but increase memory usage. + Default is 64000000. + read_buffer_size: Control the size of the buffer used to read paf file. Default is 8192. + threads: Number of threads use by yacrd. 0 means all threads available. Default is 1. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if not input_overlap_file.is_file(): + raise FileNotFoundError(f"Input overlap file not found: {input_overlap_file}") + if not input_sequence_file.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {input_sequence_file}") + if not output_report_file.parent.is_dir(): + output_report_file.parent.mkdir(parents=True, exist_ok=True) + if not output_sequence_file.parent.is_dir(): + output_sequence_file.parent.mkdir(parents=True, exist_ok=True) + + base_options = _build_base_options( + coverage_threshold, ondisk_prefix, not_coverage_ratio, + ondisk_buffer_size, read_buffer_size, threads + ) + + command_args = [ + "-i", str(input_overlap_file), + "-o", str(output_report_file), + "extract", + "-i", str(input_sequence_file), + "-o", str(output_sequence_file), + ] + base_options + + result = _run_yacrd_command(command_args, [output_report_file, output_sequence_file], user_ondisk_prefix=ondisk_prefix) + return result + +@mcp.tool() +def yacrd_split( + input_overlap_file: Path, + output_report_file: Path, + input_sequence_file: Path, + output_sequence_file: Path, + coverage_threshold: int = 0, + ondisk_prefix: Optional[str] = None, + not_coverage_ratio: float = 0.8, + ondisk_buffer_size: int = 64000000, + read_buffer_size: int = 8192, + threads: int = 1, +) -> Dict[str, Any]: + """ + Splits a sequence file, removing bad regions in the middle of reads and + removing NotCovered reads, based on an internally generated yacrd report. + + Args: + input_overlap_file: Path to input overlap file (.paf|.m4|.mhap). + Used to generate the internal yacrd report. + output_report_file: Path to the intermediate yacrd report file that will be generated. + This file is used internally by the split subcommand. + input_sequence_file: Path to the input sequence file (.fasta|.fastq). + output_sequence_file: Path to the output split sequence file. + coverage_threshold: If coverage reaches this value, the region is marked as bad. + Default is 0. + ondisk_prefix: yacrd switches to 'ondisk' mode which will reduce memory usage but + increase computation time. The value passed as a parameter is used + as a prefix for the temporary files created by yacrd. If None, + on-disk mode is not used. + not_coverage_ratio: If the ratio of bad region length on total length is lower than + this value, the read is marked as NotCovered. Default is 0.8. + ondisk_buffer_size: With the default value, yacrd in 'ondisk' mode uses around 1 GBytes. + You can increase to reduce runtime but increase memory usage. + Default is 64000000. + read_buffer_size: Control the size of the buffer used to read paf file. Default is 8192. + threads: Number of threads use by yacrd. 0 means all threads available. Default is 1. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if not input_overlap_file.is_file(): + raise FileNotFoundError(f"Input overlap file not found: {input_overlap_file}") + if not input_sequence_file.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {input_sequence_file}") + if not output_report_file.parent.is_dir(): + output_report_file.parent.mkdir(parents=True, exist_ok=True) + if not output_sequence_file.parent.is_dir(): + output_sequence_file.parent.mkdir(parents=True, exist_ok=True) + + base_options = _build_base_options( + coverage_threshold, ondisk_prefix, not_coverage_ratio, + ondisk_buffer_size, read_buffer_size, threads + ) + + command_args = [ + "-i", str(input_overlap_file), + "-o", str(output_report_file), + "split", + "-i", str(input_sequence_file), + "-o", str(output_sequence_file), + ] + base_options + + result = _run_yacrd_command(command_args, [output_report_file, output_sequence_file], user_ondisk_prefix=ondisk_prefix) + return result + +@mcp.tool() +def yacrd_scrubb( + input_overlap_file: Path, + output_report_file: Path, + input_sequence_file: Path, + output_sequence_file: Path, + coverage_threshold: int = 0, + ondisk_prefix: Optional[str] = None, + not_coverage_ratio: float = 0.8, + ondisk_buffer_size: int = 64000000, + read_buffer_size: int = 8192, + threads: int = 1, +) -> Dict[str, Any]: + """ + Removes all bad regions from reads in a sequence file and removes NotCovered reads, + based on an internally generated yacrd report. + + Args: + input_overlap_file: Path to input overlap file (.paf|.m4|.mhap). + Used to generate the internal yacrd report. + output_report_file: Path to the intermediate yacrd report file that will be generated. + This file is used internally by the scrubb subcommand. + input_sequence_file: Path to the input sequence file (.fasta|.fastq). + output_sequence_file: Path to the output scrubbed sequence file. + coverage_threshold: If coverage reaches this value, the region is marked as bad. + Default is 0. + ondisk_prefix: yacrd switches to 'ondisk' mode which will reduce memory usage but + increase computation time. The value passed as a parameter is used + as a prefix for the temporary files created by yacrd. If None, + on-disk mode is not used. + not_coverage_ratio: If the ratio of bad region length on total length is lower than + this value, the read is marked as NotCovered. Default is 0.8. + ondisk_buffer_size: With the default value, yacrd in 'ondisk' mode uses around 1 GBytes. + You can increase to reduce runtime but increase memory usage. + Default is 64000000. + read_buffer_size: Control the size of the buffer used to read paf file. Default is 8192. + threads: Number of threads use by yacrd. 0 means all threads available. Default is 1. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if not input_overlap_file.is_file(): + raise FileNotFoundError(f"Input overlap file not found: {input_overlap_file}") + if not input_sequence_file.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {input_sequence_file}") + if not output_report_file.parent.is_dir(): + output_report_file.parent.mkdir(parents=True, exist_ok=True) + if not output_sequence_file.parent.is_dir(): + output_sequence_file.parent.mkdir(parents=True, exist_ok=True) + + base_options = _build_base_options( + coverage_threshold, ondisk_prefix, not_coverage_ratio, + ondisk_buffer_size, read_buffer_size, threads + ) + + command_args = [ + "-i", str(input_overlap_file), + "-o", str(output_report_file), + "scrubb", + "-i", str(input_sequence_file), + "-o", str(output_sequence_file), + ] + base_options + + result = _run_yacrd_command(command_args, [output_report_file, output_sequence_file], user_ondisk_prefix=ondisk_prefix) + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/yacrd_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/yacrd_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7121c86bb21c1a53721f7749fcb61a11fd83d3ec --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/app/yacrd_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_yacrd/app/yacrd_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_yacrd' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..af8d6bf9b7445d6494ec59e2b7b1fd8e6abe8e20 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-yacrd: + build: . + image: mcp-yacrd:latest + container_name: mcp-yacrd + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=yacrd + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d1e208d90c43e9cae8eb48e91b1e3d6929a2fe76 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - yacrd + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_yacrd/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp