diff --git a/Biomni/mcp_generated/mcp_bioconductor-affyio copy/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-affyio copy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-affyio copy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4749f6b50ebfb67cffb861305a1aa7d0b9f9427e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/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-alabaster.sfe via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-alabaster.sfe -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-alabaster.sfe_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-alabaster.sfe_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-alabaster.sfe_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_server.py b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9d29aef6867dfe7f96e52a77a7ba8cd40da0f7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_server.py @@ -0,0 +1,221 @@ +import subprocess +import logging +from pathlib import Path +from typing import Dict, Any, Optional + +# It is assumed that the mcp decorator is available in the execution environment. +# from mcp import tool + +# Mock decorator for local testing, not to be included in the final deliverable +# if 'mcp' not in globals(): +# class mcp: +# @staticmethod +# def tool(): +# def decorator(func): +# return func +# return decorator + +logger = logging.getLogger(__name__) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_alabaster_sfe' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def stage_sfe_object( + input_rds: Path, + output_dir: Path, + path: str = "sfe", +) -> Dict[str, Any]: + """ + Stages a SpatialFeatureExperiment (SFE) object from an RDS file into the alabaster format. + + This tool wraps the 'stageObject' function from the R package 'alabaster.sfe'. + It reads an SFE object from a specified RDS file and saves it into a structured + directory according to the alabaster specification. This serves as the primary + "save" or "serialize" function for SFE objects in the alabaster framework. + + Args: + input_rds: Path to the input RDS file containing the SpatialFeatureExperiment object. + output_dir: Path to the directory where the staged object assets will be stored. + path: The relative path within 'output_dir' to save the object. Defaults to "sfe". + + Returns: + A dictionary containing the execution details and the path to the main output metadata file. + """ + # 1. Input Validation + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found at: {input_rds}") + + if not path: + raise ValueError("'path' cannot be an empty string.") + + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Failed to create output directory {output_dir}: {e}") + + # 2. R script construction + r_script_content = f""" + suppressPackageStartupMessages(library(alabaster.sfe)) + suppressPackageStartupMessages(library(SpatialFeatureExperiment)) + + tryCatch({{ + sfe_object <- readRDS('{input_rds.resolve()}') + info <- alabaster.base::stageObject(sfe_object, dir = '{output_dir.resolve()}', path = '{path}') + cat(file.path('{output_dir.resolve()}', info$path, "object.json")) + }}, error = function(e) {{ + message("Error during R script execution: ", e$message) + quit(status = 1) + }}) + """ + + # 3. Subprocess Execution + cmd = ["Rscript", "-e", r_script_content] + command_executed = " ".join(map(str, cmd)) + logger.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + stdout = process.stdout.strip() + stderr = process.stderr.strip() + + main_output_file = Path(stdout) + if not main_output_file.is_file(): + raise FileNotFoundError( + f"Expected output file not created: {main_output_file}. R stderr: {stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": { + "staged_object_json": str(main_output_file) + } + } + + except FileNotFoundError: + error_msg = "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH." + logger.error(error_msg) + raise RuntimeError(error_msg) from None + 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 RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"STDOUT: {e.stdout}\n" + f"STDERR: {e.stderr}" + ) from e + +@mcp.tool() +def load_sfe_object( + staged_dir: Path, + output_rds: Path, + path: str = "", +) -> Dict[str, Any]: + """ + Loads a SpatialFeatureExperiment (SFE) object from the alabaster format into an RDS file. + + This tool wraps the 'loadObject' function from the R package 'alabaster.base'. + It reads an SFE object from a staged directory, reconstructs it in memory, and + saves the complete object as a single RDS file. This is the "load" or "deserialize" + counterpart to the staging function. + + Args: + staged_dir: Path to the directory containing the staged object assets. + output_rds: Path for the output RDS file where the loaded SFE object will be saved. + path: The relative path within 'staged_dir' where the object's 'object.json' is located. + If empty, it's assumed to be at the root of 'staged_dir'. + + Returns: + A dictionary containing the execution details and the path to the output RDS file. + """ + # 1. Input Validation + if not staged_dir.is_dir(): + raise NotADirectoryError(f"Staged asset directory not found at: {staged_dir}") + + metadata_json_path = staged_dir.joinpath(path, "object.json") + if not metadata_json_path.is_file(): + raise FileNotFoundError(f"Metadata file 'object.json' not found at: {metadata_json_path}") + + try: + output_rds.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Failed to create output directory {output_rds.parent}: {e}") + + # 2. R script construction + r_script_content = f""" + suppressPackageStartupMessages(library(alabaster.sfe)) + suppressPackageStartupMessages(library(SpatialFeatureExperiment)) + + tryCatch({{ + sfe_object <- alabaster.base::loadObject( + '{metadata_json_path.resolve()}', + project = '{staged_dir.resolve()}' + ) + saveRDS(sfe_object, file = '{output_rds.resolve()}') + cat('{output_rds.resolve()}') + }}, error = function(e) {{ + message("Error during R script execution: ", e$message) + quit(status = 1) + }}) + """ + + # 3. Subprocess Execution + cmd = ["Rscript", "-e", r_script_content] + command_executed = " ".join(map(str, cmd)) + logger.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + stdout = process.stdout.strip() + stderr = process.stderr.strip() + + output_file = Path(stdout) + if not output_file.is_file() or output_file != output_rds.resolve(): + raise FileNotFoundError( + f"Expected output RDS file not created at {output_rds}. R stderr: {stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": { + "output_rds": str(output_file) + } + } + + except FileNotFoundError: + error_msg = "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH." + logger.error(error_msg) + raise RuntimeError(error_msg) from None + 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 RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"STDOUT: {e.stdout}\n" + f"STDERR: {e.stderr}" + ) from e + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8a698ff9af30b6c985aefe1608d84dc83b3acf95 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_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-alabaster.sfe/app/bioconductor-alabaster.sfe_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_alabaster_sfe' + + +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/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3284000038c5dc43daaf9459bdb8b4ce91a55a7b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-alabaster.sfe: + build: . + image: mcp-bioconductor-alabaster.sfe:latest + container_name: mcp-bioconductor-alabaster.sfe + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-alabaster.sfe + 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/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eeed48ad69a70bf01f9b3ae9eb5e5a76284e7159 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-alabaster.sfe + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.sfe/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..40770fc4cf44910bbe4a77f31ad3f18c226c857b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/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-alabaster.spatial via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-alabaster.spatial -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-alabaster.spatial_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-alabaster.spatial_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-alabaster.spatial_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_server.py b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0d22eafe08a15807e8323338f6bb96a7c2e7536c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_server.py @@ -0,0 +1,297 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# No need to import mcp as per instructions. + +def _run_r_script(script_content: str, cwd: Path) -> Dict[str, Any]: + """ + Executes an R script and captures its output. + + Args: + script_content: The R script as a string. + cwd: The current working directory for the R script execution. + + Returns: + A dictionary containing execution details, including command, stdout, stderr, + and an error message if the script fails. + """ + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as r_script_file: + r_script_file.write(script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + + stdout = "" + stderr = "" + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=cwd # Run R script in the specified working directory + ) + stdout = process.stdout + stderr = process.stderr + 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: + os.remove(r_script_path) + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [], # This will be populated by the calling function + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_alabaster_spatial' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def save_spatial_experiment( + input_spatial_experiment_rds: Path, + output_directory: Path, + precomputed: bool = True, + deferred: bool = False, + compression_level: Optional[int] = None, + compression_filter: Optional[str] = None, +) -> Dict[str, Any]: + """ + Saves a SpatialExperiment object and its images into file artifacts. + + This function serializes an R SpatialExperiment object (provided as an RDS file) + into a directory structure of file artifacts, offering a portable alternative + to direct RDS serialization. The `alabaster.spatial` package handles the + conversion and storage of the object and its associated images. + + Args: + input_spatial_experiment_rds: Path to an RDS file containing the SpatialExperiment object. + This file must exist. + output_directory: Path to the directory where the file artifacts will be saved. + This directory will be created if it does not exist. + precomputed: Logical, whether to save precomputed results. Defaults to TRUE. + deferred: Logical, whether to defer saving of certain components. Defaults to FALSE. + compression_level: Integer, compression level for HDF5 files (0-9). + If None, R's default (typically 6) will be used. + compression_filter: String, compression filter for HDF5 files (e.g., "gzip", "lzf"). + If None, no specific filter is applied. + + Returns: + A dictionary containing execution details, including the command executed, + stdout, stderr, and a list of generated output files/directories. + Returns an error if input file is not found, output path is invalid, + compression_level is out of range, or R script execution fails. + """ + # Input validation + if not input_spatial_experiment_rds.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Input RDS file not found at '{input_spatial_experiment_rds}'", + "output_files": [], + } + + if output_directory.exists() and not output_directory.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Output path '{output_directory}' exists but is not a directory.", + "output_files": [], + } + + try: + output_directory.mkdir(parents=True, exist_ok=True) + except OSError as e: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Could not create output directory '{output_directory}': {e}", + "output_files": [], + } + + if compression_level is not None and not (0 <= compression_level <= 9): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: 'compression_level' must be an integer between 0 and 9, got {compression_level}", + "output_files": [], + } + + # Construct R script + r_script_template = """ + suppressPackageStartupMessages({{ + library(alabaster.spatial) + library(SpatialExperiment) + library(S4Vectors) + library(alabaster.base) + library(rhdf5) # Explicitly load for HDF5 operations + }}) + + input_rds_path <- "{input_rds_path}" + output_dir_path <- "{output_dir_path}" + + # Load the SpatialExperiment object + if (!file.exists(input_rds_path)) {{ + stop(paste0("Input RDS file not found: ", input_rds_path)) + }} + se_object <- readRDS(input_rds_path) + + # Ensure it's a SpatialExperiment object + if (!is(se_object, "SpatialExperiment")) {{ + stop("Loaded object is not a SpatialExperiment object.") + }} + + # Prepare additional arguments for saveObject + save_args <- list( + x = se_object, + path = output_dir_path, + precomputed = {precomputed_r}, + deferred = {deferred_r} + ) + {compression_level_r} + {compression_filter_r} + + # Call saveObject + do.call(alabaster.spatial::saveObject, save_args) + + message(paste0("SpatialExperiment object saved to: ", output_dir_path)) + """ + + compression_level_r = f"save_args$compression_level <- {compression_level}" if compression_level is not None else "" + compression_filter_r = f"save_args$compression_filter <- '{compression_filter}'" if compression_filter is not None else "" + + r_script_content = r_script_template.format( + input_rds_path=input_spatial_experiment_rds.resolve(), + output_dir_path=output_directory.resolve(), + precomputed_r=str(precomputed).upper(), + deferred_r=str(deferred).upper(), + compression_level_r=compression_level_r, + compression_filter_r=compression_filter_r, + ) + + # Execute R script + result = _run_r_script(r_script_content, output_directory.parent) # Run in parent dir to allow output_directory creation + if "error" in result: + return result + + result["output_files"] = [str(output_directory.resolve())] + return result + + +@mcp.tool() +def read_spatial_experiment( + input_directory: Path, + output_spatial_experiment_rds: Path, + metadata_only: bool = False, + image_format: Optional[str] = None, +) -> Dict[str, Any]: + """ + Loads a SpatialExperiment object and its images from file artifacts. + + This function reconstructs an R SpatialExperiment object from a directory + of file artifacts previously saved by `save_spatial_experiment`. + + Args: + input_directory: Path to the directory containing the file artifacts. + This directory must exist and be valid. + output_spatial_experiment_rds: Path to the output RDS file where the + reconstructed SpatialExperiment object will be saved. + The parent directory will be created if it does not exist. + metadata_only: Logical, whether to only load metadata and not the full data. + Defaults to FALSE. + image_format: String, desired image format for loading (e.g., "png", "jpeg", "tiff"). + If None, images are loaded in their original format. + + Returns: + A dictionary containing execution details, including the command executed, + stdout, stderr, and a list of generated output files. + Returns an error if input directory is not found, output path is invalid, + or R script execution fails. + """ + # Input validation + if not input_directory.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Input directory not found at '{input_directory}'", + "output_files": [], + } + + if output_spatial_experiment_rds.exists() and not output_spatial_experiment_rds.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Output path '{output_spatial_experiment_rds}' exists but is not a file.", + "output_files": [], + } + + try: + output_spatial_experiment_rds.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Could not create parent directory for output RDS file '{output_spatial_experiment_rds}': {e}", + "output_files": [], + } + + # Construct R script + r_script_template = """ + suppressPackageStartupMessages({{ + library(alabaster.spatial) + library(SpatialExperiment) + library(S4Vectors) + library(alabaster.base) + library(rhdf5) # Explicitly load for HDF5 operations + }}) + + input_dir_path <- "{input_dir_path}" + output_rds_path <- "{output_rds_path}" + + # Prepare additional arguments for readObject + read_args <- list( + path = input_dir_path, + metadata.only = {metadata_only_r} + ) + {image_format_r} + + # Call readObject + se_object <- do.call(alabaster.spatial::readObject, read_args) + + # Save the SpatialExperiment object to RDS + saveRDS(se_object, file = output_rds_path) + + message(paste0("SpatialExperiment object loaded from: ", input_dir_path, " and saved to: ", output_rds_path)) + """ + + image_format_r = f"read_args$image.format <- '{image_format}'" if image_format is not None else "" + + r_script_content = r_script_template.format( + input_dir_path=input_directory.resolve(), + output_rds_path=output_spatial_experiment_rds.resolve(), + metadata_only_r=str(metadata_only).upper(), + image_format_r=image_format_r, + ) + + # Execute R script + result = _run_r_script(r_script_content, output_spatial_experiment_rds.parent) + if "error" in result: + return result + + result["output_files"] = [str(output_spatial_experiment_rds.resolve())] + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d63aaee9992f9d7e2ea8ec9555c0b6fb8f9fdea8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_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-alabaster.spatial/app/bioconductor-alabaster.spatial_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_alabaster_spatial' + + +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/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9077879ad1f81983e4ba6ace465ba860f645b5be --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-alabaster.spatial: + build: . + image: mcp-bioconductor-alabaster.spatial:latest + container_name: mcp-bioconductor-alabaster.spatial + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-alabaster.spatial + 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/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..329b888afd15efdc23d52fc58fe6ff2376c71013 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-alabaster.spatial + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster.spatial/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-alabaster/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..adf3034b80c6daf061e68aa17f25bd39e1e1eb37 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster/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-alabaster via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-alabaster -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-alabaster_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-alabaster_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-alabaster_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py b/Biomni/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py new file mode 100644 index 0000000000000000000000000000000000000000..adb75c86deee5de88a84fd7b75fd2c59e6bb05cd --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py @@ -0,0 +1,66 @@ +import subprocess +import sys +from pathlib import Path +from typing import Optional, List +import tempfile +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) + +# Mock mcp.tool decorator for standalone execution +class mcp: + def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +@mcp.tool +def alabaster_check(): + """ + Verifies the installation of the bioconductor-alabaster umbrella package. + + This tool does not perform any data analysis. Instead, it attempts to load + the 'alabaster' library within an R session to confirm that the Alabaster + framework and all its components are correctly installed and accessible. + A successful execution indicates the environment is ready for tools that + depend on the Alabaster suite. + """ + command = ["Rscript", "-e", "library(alabaster)"] + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + logging.info("bioconductor-alabaster package loaded successfully.") + + except FileNotFoundError: + logging.error("Rscript not found. Please ensure R is installed and in your PATH.") + # Re-raise with a more informative message for the MCP context + raise RuntimeError("Rscript executable not found. R installation is required.") from None + + except subprocess.CalledProcessError as e: + logging.error(f"Error loading bioconductor-alabaster package.") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to load the 'alabaster' R library. It may not be installed correctly.", + "return_code": e.returncode, + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "status": "success" + } diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fefef75e961a8cb656aab3b33c3640c8b91c410d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_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-alabaster/app/bioconductor-alabaster_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_alabaster' + + +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/Biomni/mcp_generated/mcp_bioconductor-alabaster/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-alabaster/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-alabaster/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1e7f78ab1fdc06a0f6527a02824e5ac4283ab2f5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-alabaster: + build: . + image: mcp-bioconductor-alabaster:latest + container_name: mcp-bioconductor-alabaster + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-alabaster + 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/Biomni/mcp_generated/mcp_bioconductor-alabaster/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-alabaster/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..005b89505905813f059b39eff70b16c86b5b6306 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-alabaster + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-alabaster/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-alabaster/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-alabaster/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-ancombc/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-ancombc/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66ba2c07f5ba40e55a52d2cfb656ebaf930c87a3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ancombc/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-ancombc via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ancombc -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-ancombc_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-ancombc_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-ancombc_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ancombc/app/bioconductor-ancombc_server.py b/Biomni/mcp_generated/mcp_bioconductor-ancombc/app/bioconductor-ancombc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4f1ae809aaa666e96b04e26f071abfb81fc2d1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ancombc/app/bioconductor-ancombc_server.py @@ -0,0 +1,251 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Dict, List, Optional + +# @mcp.tool() is a placeholder for the actual decorator. +# The function is written to be compatible with the MCP server environment. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +@mcp_tool_placeholder() +def ancombc2( + otu_table: Path, + sample_metadata: Path, + formula: str, + output_dir: Path, + taxonomy_table: Optional[Path] = None, + p_adj_method: str = "holm", + zero_cut: float = 0.9, + lib_cut: int = 1000, + struc_zero: bool = False, + neg_lb: bool = False, + tol: float = 1e-05, + max_iter: int = 100, + conserve: bool = False, + alpha: float = 0.05, + global_test: bool = False, + group: Optional[str] = None, + mdfdr_dist: str = "normal", + n_cl: int = 1, + verbose: bool = False, + output_prefix: str = "ancombc2_results", +) -> Dict: + """ + Performs differential abundance analysis on microbiome data using ANCOM-BC2. + + ANCOM-BC2 (Analysis of Compositions of Microbiomes with Bias Correction 2) is a + method for identifying differentially abundant taxa between groups while correcting + for sample-specific and taxon-specific biases. + + Args: + otu_table: Path to the feature/OTU count table (CSV format). Rows should be taxa + and columns should be samples. The first column should be taxon IDs. + sample_metadata: Path to the sample metadata file (CSV format). Rows should be + samples and columns should be metadata variables. The first + column should be sample IDs. + formula: An R-style formula string specifying the model, e.g., "age + sex + diagnosis". + Variables must correspond to columns in the sample_metadata file. + output_dir: Path to the directory where output files will be saved. + taxonomy_table: Optional path to the taxonomy table (CSV format). Rows should be + taxa, columns should be taxonomic ranks. The first column must + be taxon IDs matching the OTU table. + p_adj_method: Method for p-value adjustment. + Options: "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none". + zero_cut: A numerical value between 0 and 1. Taxa with a proportion of zeros greater + than this value will be excluded from the analysis. + lib_cut: A numerical value. Samples with library sizes less than this value will be + excluded from the analysis. + struc_zero: Whether to detect structural zeros. + neg_lb: Whether to use the negative binomial distribution for modeling sampling fractions. + If FALSE, a log-linear model is used. + tol: Convergence tolerance for the optimization algorithm. + max_iter: Maximum number of iterations for the optimization algorithm. + conserve: Whether to use a conservative variance estimate for the test statistic. + alpha: Significance level for identifying differentially abundant taxa. + global_test: Whether to perform a global test for the specified group variable. + group: The name of the group variable for the global test. Required if `global_test` is True. + Must be a column name in the sample_metadata file. + mdfdr_dist: The assumed distribution of the E-values in m-DFDR. + Options: "normal", "t". + n_cl: Number of CPU cores to use for parallel computation. + verbose: Whether to display progress messages during execution. + output_prefix: Prefix for the output result files. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of + paths to the generated output files. + """ + # --- 1. Input Validation --- + if not otu_table.is_file(): + raise FileNotFoundError(f"OTU table not found at: {otu_table}") + if not sample_metadata.is_file(): + raise FileNotFoundError(f"Sample metadata not found at: {sample_metadata}") + if taxonomy_table and not taxonomy_table.is_file(): + raise FileNotFoundError(f"Taxonomy table not found at: {taxonomy_table}") + + p_adj_methods = ["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] + if p_adj_method not in p_adj_methods: + raise ValueError(f"Invalid p_adj_method '{p_adj_method}'. Must be one of {p_adj_methods}") + + mdfdr_dists = ["normal", "t"] + if mdfdr_dist not in mdfdr_dists: + raise ValueError(f"Invalid mdfdr_dist '{mdfdr_dist}'. Must be one of {mdfdr_dists}") + + if not 0 <= zero_cut <= 1: + raise ValueError("zero_cut must be between 0 and 1.") + if not 0 < alpha < 1: + raise ValueError("alpha must be between 0 and 1.") + if lib_cut < 0: + raise ValueError("lib_cut must be a non-negative integer.") + if max_iter <= 0: + raise ValueError("max_iter must be a positive integer.") + if n_cl <= 0: + raise ValueError("n_cl must be a positive integer.") + if tol <= 0: + raise ValueError("tol must be a positive float.") + + if global_test and not group: + raise ValueError("The 'group' parameter is required when 'global_test' is True.") + + # --- 2. Prepare for Execution --- + output_dir.mkdir(parents=True, exist_ok=True) + + output_res_path = output_dir / f"{output_prefix}_DA.csv" + output_files = [str(output_res_path)] + + output_global_res_path = output_dir / f"{output_prefix}_global.csv" + if global_test: + output_files.append(str(output_global_res_path)) + + # Convert Python types to R-compatible strings + r_tax_file = f"'{taxonomy_table.resolve()}'" if taxonomy_table else "NULL" + r_group = f"'{group}'" if group else "NULL" + r_struc_zero = "TRUE" if struc_zero else "FALSE" + r_neg_lb = "TRUE" if neg_lb else "FALSE" + r_conserve = "TRUE" if conserve else "FALSE" + r_global_test = "TRUE" if global_test else "FALSE" + r_verbose = "TRUE" if verbose else "FALSE" + + # --- 3. Generate R Script --- + r_script_content = textwrap.dedent(f""" + # Load required libraries + library(ANCOMBC) + library(phyloseq) + + # --- Parameters --- + otu_file <- '{otu_table.resolve()}' + meta_file <- '{sample_metadata.resolve()}' + tax_file <- {r_tax_file} + output_res_path <- '{output_res_path.resolve()}' + output_global_res_path <- '{output_global_res_path.resolve()}' + + # --- Load and prepare data --- + # read.csv with row.names = 1 assumes first column is the index + otu_mat <- as.matrix(read.csv(otu_file, row.names = 1, check.names = FALSE)) + meta_data <- read.csv(meta_file, row.names = 1, check.names = FALSE) + + # Ensure sample names match and are in the same order + samples_in_common <- intersect(rownames(meta_data), colnames(otu_mat)) + if (length(samples_in_common) == 0) {{ + stop("No common sample IDs found between OTU table and metadata.") + }} + otu_mat <- otu_mat[, samples_in_common, drop = FALSE] + meta_data <- meta_data[samples_in_common, , drop = FALSE] + + OTU <- otu_table(otu_mat, taxa_are_rows = TRUE) + META <- sample_data(meta_data) + + # Load taxonomy if provided + if (!is.null(tax_file)) {{ + tax_mat <- as.matrix(read.csv(tax_file, row.names = 1, check.names = FALSE)) + # Ensure taxon names match + taxa_in_common <- intersect(rownames(tax_mat), rownames(otu_mat)) + if (length(taxa_in_common) == 0) {{ + warning("No common taxon IDs found between OTU table and taxonomy table. Proceeding without taxonomy.") + pseq <- phyloseq(OTU, META) + }} else {{ + tax_mat_filtered <- tax_mat[taxa_in_common, , drop = FALSE] + TAX <- tax_table(tax_mat_filtered) + pseq <- phyloseq(OTU, META, TAX) + }} + }} else {{ + pseq <- phyloseq(OTU, META) + }} + + # --- Run ANCOM-BC2 --- + output <- ancombc2( + data = pseq, + formula = "{formula}", + p_adj_method = "{p_adj_method}", + zero_cut = {zero_cut}, + lib_cut = {lib_cut}, + struc_zero = {r_struc_zero}, + neg_lb = {r_neg_lb}, + tol = {tol}, + max_iter = {max_iter}, + conserve = {r_conserve}, + alpha = {alpha}, + global = {r_global_test}, + group = {r_group}, + mdfdr_dist = "{mdfdr_dist}", + n_cl = {n_cl}, + verbose = {r_verbose} + ) + + # --- Save results --- + # Save differential abundance results + res_df <- data.frame(output$res) + write.csv(res_df, file = output_res_path, row.names = TRUE) + + # Save global test results if applicable + if ({r_global_test} && !is.null(output$res_global)) {{ + res_global_df <- data.frame(output$res_global) + write.csv(res_global_df, file = output_global_res_path, row.names = TRUE) + }} + + print("ANCOM-BC2 analysis completed successfully.") + """) + + # --- 4. Execute --- + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + # Clean up the temporary script file on error + Path(r_script_path).unlink() + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [] + } + finally: + # Ensure temporary script is always cleaned up + if Path(r_script_path).exists(): + Path(r_script_path).unlink() + + # --- 5. Return results --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ancombc/app/bioconductor-ancombc_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-ancombc/app/bioconductor-ancombc_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..09b101f43278c600468c2fd6978d549cdd1cf49d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ancombc/app/bioconductor-ancombc_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-ancombc/app/bioconductor-ancombc_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_ancombc' + + +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/Biomni/mcp_generated/mcp_bioconductor-ancombc/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ancombc/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ancombc/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-ancombc/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-ancombc/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..56a3995e609e7415b0dafb7f808bab03c3b49280 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ancombc/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ancombc: + build: . + image: mcp-bioconductor-ancombc:latest + container_name: mcp-bioconductor-ancombc + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ancombc + 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/Biomni/mcp_generated/mcp_bioconductor-ancombc/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-ancombc/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b5c51800f55fd28df265e465d5f20d94684402c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ancombc/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ancombc + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ancombc/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ancombc/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ancombc/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotate/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-annotate/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8df3183e644dd3c5947b4c5585e2c942f6d7c80c --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py b/Biomni/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e8aa22c0b818479e01d8ba4f0ce30f4cb61ba843 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-annotate/app/bioconductor-annotate_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..918995248372ba964c86e8818f1ecdaade4bf02c --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-annotate/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-annotate/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5020838deb35bbae2bcb064ef99231a9f153e504 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-annotate/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-annotate/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca6f7fedcb6d13738028109983815bb7e6c4b8fd --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-annotate/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-annotate/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotate/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..31bb65012357ab749e55a3d2e0a30bbf3fc1c6e2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/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-annotationdbi via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-annotationdbi -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-annotationdbi_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-annotationdbi_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-annotationdbi_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..446bfe78af1157378723d70e343d9887d6351f5b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py @@ -0,0 +1,464 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP decorator is assumed to be defined in the execution environment. +# No import is needed as per the instructions. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_annotationdbi' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def annotationdbi_columns(db_package: str) -> dict: + """ + Lists all available columns for a given Bioconductor annotation package. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + + Returns: + A dictionary containing the command executed and the standard output with the column names. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + result_data <- AnnotationDbi::columns(db) + cat(result_data, sep = "\\n") + }}, error = function(e) {{ + stop(paste("AnnotationDbi::columns failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + 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"R script execution failed with exit code {e.returncode}" + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found" + } + finally: + Path(script_path).unlink() + +@mcp.tool() +def annotationdbi_keytypes(db_package: str) -> dict: + """ + Lists all available keytypes for a given Bioconductor annotation package. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + + Returns: + A dictionary containing the command executed and the standard output with the keytype names. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + result_data <- AnnotationDbi::keytypes(db) + cat(result_data, sep = "\\n") + }}, error = function(e) {{ + stop(paste("AnnotationDbi::keytypes failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + 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"R script execution failed with exit code {e.returncode}" + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found" + } + finally: + Path(script_path).unlink() + +@mcp.tool() +def annotationdbi_keys(db_package: str, keytype: str) -> dict: + """ + Lists all available keys for a given keytype in a Bioconductor annotation package. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + keytype: The keytype for which to retrieve all available keys (e.g., "ENTREZID"). + + Returns: + A dictionary containing the command executed and the standard output with the keys. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + if not keytype: + raise ValueError("keytype must be a non-empty string.") + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + keytype_str <- "{keytype}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + result_data <- AnnotationDbi::keys(db, keytype = keytype_str) + cat(result_data, sep = "\\n") + }}, error = function(e) {{ + stop(paste("AnnotationDbi::keys failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + 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"R script execution failed with exit code {e.returncode}" + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found" + } + finally: + Path(script_path).unlink() + +@mcp.tool() +def annotationdbi_select( + db_package: str, + keys: str, + columns: str, + keytype: str, + output_file: Path, +) -> dict: + """ + Retrieves data from a Bioconductor annotation package using AnnotationDbi::select. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + keys: A comma-separated string of keys to query (e.g., "BRCA1,TP53"). + columns: A comma-separated string of columns to retrieve (e.g., "SYMBOL,GENENAME,ENTREZID"). + keytype: The type of the provided keys (e.g., "SYMBOL"). + output_file: The path to save the results as a TSV file. + + Returns: + A dictionary containing the command executed, logs, and the path to the output file. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + if not keys: + raise ValueError("keys must be a non-empty, comma-separated string.") + if not columns: + raise ValueError("columns must be a non-empty, comma-separated string.") + if not keytype: + raise ValueError("keytype must be a non-empty string.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + keys_vec <- unlist(strsplit("{keys}", ",")) + columns_vec <- unlist(strsplit("{columns}", ",")) + keytype_str <- "{keytype}" + output_file_path <- "{output_file.resolve()}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + results <- AnnotationDbi::select(db, + keys = keys_vec, + columns = columns_vec, + keytype = keytype_str) + + write.table(results, + file = output_file_path, + sep = "\\t", + row.names = FALSE, + col.names = TRUE, + quote = FALSE) + + cat(paste("Successfully wrote", nrow(results), "rows to", basename(output_file_path), "\\n")) + + }}, error = function(e) {{ + stop(paste("AnnotationDbi::select failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + 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.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found", + "output_files": [] + } + finally: + Path(script_path).unlink() + +@mcp.tool() +def annotationdbi_mapids( + db_package: str, + keys: str, + column: str, + keytype: str, + output_file: Path, + multi_vals: str = "first", +) -> dict: + """ + Maps identifiers from one type to another using AnnotationDbi::mapIds. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + keys: A comma-separated string of keys to query (e.g., "BRCA1,TP53"). + column: The single column (identifier type) to map to (e.g., "ENTREZID"). + keytype: The type of the provided keys (e.g., "SYMBOL"). + output_file: The path to save the mapping results as a TSV file. + multi_vals: How to handle multiple matches. One of "first", "list", "filter", "asNA". + + Returns: + A dictionary containing the command executed, logs, and the path to the output file. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + if not keys: + raise ValueError("keys must be a non-empty, comma-separated string.") + if not column: + raise ValueError("column must be a non-empty string.") + if not keytype: + raise ValueError("keytype must be a non-empty string.") + + valid_multi_vals = ["first", "list", "filter", "asNA", "character"] + if multi_vals not in valid_multi_vals: + raise ValueError(f"multi_vals must be one of {valid_multi_vals}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + keys_vec <- unlist(strsplit("{keys}", ",")) + column_str <- "{column}" + keytype_str <- "{keytype}" + multi_vals_str <- "{multi_vals}" + output_file_path <- "{output_file.resolve()}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + results_vec <- AnnotationDbi::mapIds(db, + keys = keys_vec, + column = column_str, + keytype = keytype_str, + multiVals = multi_vals_str) + + # Convert named vector to a data frame for saving + results_df <- data.frame(FROM = names(results_vec), TO = I(results_vec), stringsAsFactors = FALSE) + + write.table(results_df, + file = output_file_path, + sep = "\\t", + row.names = FALSE, + col.names = TRUE, + quote = FALSE) + + cat(paste("Successfully wrote", nrow(results_df), "rows to", basename(output_file_path), "\\n")) + + }}, error = function(e) {{ + stop(paste("AnnotationDbi::mapIds failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + 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.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found", + "output_files": [] + } + finally: + Path(script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6cd6d5e935b0b8c488efdcd09bde2cc54fa351b9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_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-annotationdbi/app/bioconductor-annotationdbi_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_annotationdbi' + + +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/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ffb2fbebfe206e4992e7f807130e3578bf3ea00 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-annotationdbi: + build: . + image: mcp-bioconductor-annotationdbi:latest + container_name: mcp-bioconductor-annotationdbi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-annotationdbi + 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/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..219d52fcbc8c34ff46e974f7676c137182099e8a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-annotationdbi + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationdbi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..baf9c1e2c5a0c01da8fd1ed50638ade5d8afd8a3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/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-annotationfilter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-annotationfilter -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-annotationfilter_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-annotationfilter_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-annotationfilter_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_server.py b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..14fffe3f80781f2af6f60d7cd5eb409a181feb26 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_server.py @@ -0,0 +1,293 @@ +import subprocess +import json +from typing import List, Optional, Union +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_annotationfilter' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def create_individual_filter( + filter_class: str, + value: Union[str, List[str]], + condition: str = "==", +) -> dict: + """ + Create an individual AnnotationFilter object (e.g., GeneIdFilter, SymbolFilter). + + Args: + filter_class: The class of the filter (e.g., 'GeneIdFilter', 'SymbolFilter', 'EntrezFilter', + 'GenenameFilter', 'TxIdFilter', 'ExonIdFilter', 'ProteinIdFilter', 'UniprotFilter', + 'SeqNameFilter', 'SeqStrandFilter', 'SeqStartFilter', 'SeqEndFilter', + 'GeneBiotypeFilter', 'TxBiotypeFilter'). + value: The value(s) to filter by. Can be a single string or a list of strings. + condition: The filter condition. Supported: '==', '!=', 'startsWith', 'endsWith', 'contains', '>', '<', '>=', '<='. + """ + # Validation of filter classes + valid_classes = [ + "CdsEndFilter", "CdsStartFilter", "EntrezFilter", "ExonIdFilter", "ExonRankFilter", + "ExonEndFilter", "ExonStartFilter", "GeneIdFilter", "GeneBiotypeFilter", "GenenameFilter", + "GeneStartFilter", "GeneEndFilter", "ProteinIdFilter", "SeqNameFilter", "SeqStrandFilter", + "SymbolFilter", "TxIdFilter", "TxBiotypeFilter", "TxStartFilter", "TxEndFilter", "UniprotFilter" + ] + if filter_class not in valid_classes: + return {"error": f"Invalid filter_class. Must be one of: {', '.join(valid_classes)}"} + + # Validation of conditions + valid_conditions = ["==", "!=", "startsWith", "endsWith", "contains", ">", "<", ">=", "<="] + if condition not in valid_conditions: + return {"error": f"Invalid condition. Must be one of: {', '.join(valid_conditions)}"} + + # Format value for R + if isinstance(value, list): + r_value = 'c(' + ', '.join([f'"{v}"' for v in value]) + ')' + else: + r_value = f'"{value}"' + + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + f <- {filter_class}({r_value}, condition = "{condition}") + cat(as.character(f), "\\n") + print(f) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "stdout": result.stdout, + "stderr": result.stderr, + "filter_string": result.stdout.splitlines()[0] if result.stdout else "" + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def parse_filter_formula( + formula: str, +) -> dict: + """ + Create an AnnotationFilter object using the R formula syntax. + + Args: + formula: An R formula string representing the filter, e.g., '~ symbol == "ADA"' or '~ gene_id %in% c("1", "2")'. + """ + if not formula.startswith("~"): + formula = "~ " + formula + + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + f <- AnnotationFilter({formula}) + print(f) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to parse formula. Ensure syntax is correct (e.g., '~ symbol == \"ADA\"')", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def create_filter_list( + filters: List[str], + logic_op: str = "&", +) -> dict: + """ + Combine multiple AnnotationFilter objects into an AnnotationFilterList. + + Args: + filters: A list of R filter construction strings, e.g., ['GeneIdFilter("123")', 'SymbolFilter("ADA")']. + logic_op: The logical operator to combine filters. Use '&' for AND, '|' for OR. + """ + if logic_op not in ["&", "|"]: + return {"error": "logic_op must be '&' or '|'"} + + # Construct the R list + filter_list_str = ", ".join(filters) + + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + fl <- AnnotationFilterList({filter_list_str}, logicOp = "{logic_op}") + print(fl) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to create filter list. Ensure individual filter strings are valid R code.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def get_filter_properties( + filter_expression: str, +) -> dict: + """ + Extract properties (field, value, condition) from an AnnotationFilter object. + + Args: + filter_expression: An R string that creates a filter, e.g., 'GeneIdFilter("ENSG0001")'. + """ + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + f <- {filter_expression} + cat("field:", field(f), "\\n") + cat("condition:", condition(f), "\\n") + cat("value:", paste(value(f), collapse=", "), "\\n") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to extract properties. Ensure the filter expression is valid.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def list_supported_filters() -> dict: + """ + List all supported filter classes and conditions in the AnnotationFilter package. + """ + r_script = """ + suppressPackageStartupMessages(library(AnnotationFilter)) + # Get all classes that inherit from AnnotationFilter + # This is a simplified list based on package documentation + filters <- c( + "CdsEndFilter", "CdsStartFilter", "EntrezFilter", "ExonIdFilter", "ExonRankFilter", + "ExonEndFilter", "ExonStartFilter", "GeneIdFilter", "GeneBiotypeFilter", "GenenameFilter", + "GeneStartFilter", "GeneEndFilter", "ProteinIdFilter", "SeqNameFilter", "SeqStrandFilter", + "SymbolFilter", "TxIdFilter", "TxBiotypeFilter", "TxStartFilter", "TxEndFilter", "UniprotFilter" + ) + conditions <- c("==", "!=", "startsWith", "endsWith", "contains", ">", "<", ">=", "<=") + + cat("Supported Filters:\\n") + cat(paste("-", filters, collapse="\\n"), "\\n\\n") + cat("Supported Conditions:\\n") + cat(paste("-", conditions, collapse="\\n"), "\\n") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript -e '...'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to list filters", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def translate_to_sql_where( + filter_expression: str, +) -> dict: + """ + Translate an AnnotationFilter object into a SQL WHERE clause fragment. + Note: This is a conceptual translation as used by packages like ensembldb. + + Args: + filter_expression: An R string that creates a filter, e.g., 'GeneIdFilter("ENSG0001")'. + """ + # In AnnotationFilter, the translation is often handled by the consuming package (like ensembldb) + # but we can simulate the logic here for the user. + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + f <- {filter_expression} + + # Simple translation logic + cond <- condition(f) + val <- value(f) + fld <- field(f) + + if (length(val) > 1) {{ + sql_val <- paste0("('", paste(val, collapse="', '"), "')") + sql_cond <- if (cond == "==") "IN" else "NOT IN" + }} else {{ + sql_val <- paste0("'", val, "'") + sql_cond <- cond + if (cond == "startsWith") {{ sql_cond <- "LIKE"; sql_val <- paste0("'", val, "%'") }} + if (cond == "endsWith") {{ sql_cond <- "LIKE"; sql_val <- paste0("'% ", val, "'") }} + if (cond == "contains") {{ sql_cond <- "LIKE"; sql_val <- paste0("'%", val, "%'") }} + }} + + cat(paste(fld, sql_cond, sql_val)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "sql_fragment": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to translate filter", + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..62ca6bb4aca09fada7c29a56f7891e63b918556b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_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-annotationfilter/app/bioconductor-annotationfilter_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_annotationfilter' + + +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/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3e5c25a320a47cb58d47530969489723508c8036 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-annotationfilter: + build: . + image: mcp-bioconductor-annotationfilter:latest + container_name: mcp-bioconductor-annotationfilter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-annotationfilter + 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/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ed4c145c4fe4f9efb73b977f45a6e005ebe1725 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-annotationfilter + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationfilter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-annotationhub/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-annotationhub/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-annotationhub/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-apeglm/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-apeglm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..57cd40f2416b347da5e546796f7f35bde99211bf --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apeglm/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-apeglm via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-apeglm -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-apeglm_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-apeglm_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-apeglm_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py b/Biomni/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e532794f69d56fd258bf850b3e370bbfcb7f07 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py @@ -0,0 +1,133 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_apeglm' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_r_script( + r_script_file: Optional[Path] = None, + r_expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save_workspace: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore_workspace: bool = False, + vanilla: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script file or R expressions using the Rscript command. + + This tool provides a wrapper for the Rscript command, allowing users to run + R code with various configuration options. It supports executing a specified + R script file or a list of R expressions directly. It also allows passing + arguments to the R script itself and configuring R's startup behavior. + + Args: + r_script_file: Path to an R script file to execute. Mutually exclusive with `r_expressions`. + r_expressions: A list of R expressions (strings) to execute. Mutually exclusive with `r_script_file`. + script_args: A list of arguments to be passed to the R script or expressions. + verbose: If True, print information on progress (corresponds to Rscript's --verbose). + default_packages: A comma-separated list of package names, or 'NULL', + to set the default packages loaded (corresponds to --default-packages). + save_workspace: If True, save the workspace at the end of the session (corresponds to R's --save). + Ignored if `vanilla` is True. + no_environ: If True, don't read the site and user environment files (corresponds to R's --no-environ). + Ignored if `vanilla` is True. + no_site_file: If True, don't read the site-wide Rprofile (corresponds to R's --no-site-file). + Ignored if `vanilla` is True. + no_init_file: If True, don't read the user R profile (corresponds to R's --no-init-file). + Ignored if `vanilla` is True. + restore_workspace: If True, restore previously saved objects at startup (corresponds to R's --restore). + Ignored if `vanilla` is True. + 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. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + In case of an error, it includes error details and the return code. + + Raises: + ValueError: If neither `r_script_file` nor `r_expressions` is provided, or if both are provided. + FileNotFoundError: If `r_script_file` is provided but does not exist. + """ + command: List[str] = ["Rscript"] + output_files: List[Path] = [] + + # Input validation for script source + if r_script_file is None and r_expressions is None: + raise ValueError("Either 'r_script_file' or 'r_expressions' must be provided.") + if r_script_file is not None and r_expressions is not None: + raise ValueError("Cannot provide both 'r_script_file' and 'r_expressions'. Choose one.") + + if r_script_file: + if not r_script_file.is_file(): + raise FileNotFoundError(f"R script file not found: {r_script_file}") + + # Add Rscript specific options + if verbose: + command.append("--verbose") + if default_packages is not None: + command.append(f"--default-packages={default_packages}") + + # Add R options (passed to R, in addition to --no-echo --no-restore by Rscript) + if vanilla: + command.append("--vanilla") + else: + # Only add these if --vanilla is not set, as --vanilla implies them + if save_workspace: + 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_workspace: + command.append("--restore") + + # Add the script source (file or expressions) + if r_script_file: + command.append(str(r_script_file)) + elif r_expressions: + for expr in r_expressions: + command.extend(["-e", expr]) + + # Add arguments to the R script + if script_args: + command.extend(script_args) + + 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(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "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/Biomni/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c0e18d69352f300b80fbc101a43abe584b7931e0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_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-apeglm/app/bioconductor-apeglm_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_apeglm' + + +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/Biomni/mcp_generated/mcp_bioconductor-apeglm/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-apeglm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e15e303cb39aa7756cd707cc87115c9bf685830c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apeglm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-apeglm: + build: . + image: mcp-bioconductor-apeglm:latest + container_name: mcp-bioconductor-apeglm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-apeglm + 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/Biomni/mcp_generated/mcp_bioconductor-apeglm/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-apeglm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ebc2281a594f219239a61a4c8336c9dea78166b1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apeglm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-apeglm + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-apeglm/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-apeglm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apeglm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-apl/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-apl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..12d5dbd56f0614e144adc7e9f202e95644c3a163 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apl/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-apl via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-apl -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-apl_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-apl_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-apl_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_server.py b/Biomni/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ed368d916170fbb25aee6623ff2fe0fad799467d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_server.py @@ -0,0 +1,296 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Note: mcp is not imported as per instructions. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_apl' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_apl_analysis( + input_seurat_object: Path, + output_directory: Path, + cluster_column: str, + selected_cluster: Optional[str] = None, + organism: Optional[str] = None, + min_genes_per_cluster: int = 5, + top_n_genes_for_report: int = 50, + generate_interactive_plots: bool = False, +) -> Dict[str, Any]: + """ + Performs a hypothetical APL (Association Plots) analysis on single-cell transcriptomics data. + + This function serves as a placeholder for integrating the bioconductor-apl R package. + **Crucially, the specific R functions and their parameters from the APL package + are NOT available in the provided documentation.** Therefore, the R script + executed by this tool contains illustrative placeholders for APL package + function calls. + + In a real implementation, the R script would be populated with specific + calls to functions from the APL R package (e.g., `APL::runAPL`, `APL::plotAP`, + `APL::calculateSpecificityScores`) based on its official documentation + (e.g., the APL Reference Manual PDF or vignettes). + + Args: + input_seurat_object: Path to an RDS file containing a Seurat object or + SingleCellExperiment object. This is the primary input + single-cell data. + output_directory: Path to the directory where output files (plots, + specificity scores, summary) will be saved. + The directory will be created if it does not exist. + cluster_column: The name of the column in the Seurat object's metadata + (or SingleCellExperiment's colData) that contains + cell cluster assignments. + selected_cluster: Optional. If provided, the analysis might focus on + this specific cluster for detailed plots or reports. + Defaults to None, meaning analysis might cover all clusters. + organism: Optional. Specifies the organism for gene annotation, + e.g., 'human' or 'mouse'. This influences which `org.db` + package (`org.Hs.eg.db` or `org.Mm.eg.db`) might be loaded + by the R script. Defaults to None. + min_genes_per_cluster: Hypothetical. Minimum number of genes required + for a cluster to be considered in certain analyses. + Defaults to 5. + top_n_genes_for_report: Hypothetical. Number of top cluster-specific genes + to include in summary reports or plots. Defaults to 50. + generate_interactive_plots: Hypothetical. If True, attempts to generate + interactive plots using `plotly` (if APL supports it). + Defaults to False. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not input_seurat_object.is_file(): + raise FileNotFoundError(f"Input Seurat/SingleCellExperiment object not found: {input_seurat_object}") + + output_directory.mkdir(parents=True, exist_ok=True) + + # Determine organism-specific package to load in R + org_db_package_load = "" + if organism: + if organism.lower() == "human": + org_db_package_load = "BiocManager::install('org.Hs.eg.db', update = FALSE, ask = FALSE); library(org.Hs.eg.db)" + elif organism.lower() == "mouse": + org_db_package_load = "BiocManager::install('org.Mm.eg.db', update = FALSE, ask = FALSE); library(org.Mm.eg.db)" + else: + # This is a hypothetical validation, as APL might support more or less organisms + raise ValueError(f"Unsupported organism: {organism}. Only 'human' and 'mouse' are hypothetically supported for gene annotation.") + + # R script template + # This template includes installation of common dependencies and placeholders + # for the actual APL package function calls. + R_SCRIPT_TEMPLATE = f""" + # Ensure BiocManager is installed for package management + if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager") + + # Install APL and its core dependencies (as inferred from conda/bioconductor info) + # update=FALSE and ask=FALSE are used to prevent interactive prompts and unnecessary updates + BiocManager::install("APL", update = FALSE, ask = FALSE) + BiocManager::install("Seurat", update = FALSE, ask = FALSE) + BiocManager::install("SingleCellExperiment", update = FALSE, ask = FALSE) + BiocManager::install("ggplot2", update = FALSE, ask = FALSE) + BiocManager::install("plotly", update = FALSE, ask = FALSE) + BiocManager::install("magrittr", update = FALSE, ask = FALSE) + BiocManager::install("SummarizedExperiment", update = FALSE, ask = FALSE) + BiocManager::install("topGO", update = FALSE, ask = FALSE) + BiocManager::install("methods", update = FALSE, ask = FALSE) + BiocManager::install("stats", update = FALSE, ask = FALSE) + BiocManager::install("utils", update = FALSE, ask = FALSE) + BiocManager::install("rlang", update = FALSE, ask = FALSE) + BiocManager::install("ggrepel", update = FALSE, ask = FALSE) + BiocManager::install("viridisLite", update = FALSE, ask = FALSE) + BiocManager::install("reticulate", update = FALSE, ask = FALSE) # For python dependencies if APL uses them + BiocManager::install("Matrix", update = FALSE, ask = FALSE) # From conda search (r-matrix) + BiocManager::install("RSpectra", update = FALSE, ask = FALSE) # From conda search (r-rspectra) + BiocManager::install("SeuratObject", update = FALSE, ask = FALSE) # From conda search (r-seuratobject) + + # Load organism-specific gene annotation database if specified + {org_db_package_load} + + # Load necessary libraries + library(APL) + library(Seurat) + library(SingleCellExperiment) + library(ggplot2) + library(plotly) + library(magrittr) # For %>% + library(SummarizedExperiment) + library(topGO) + library(methods) + library(stats) + library(utils) + library(rlang) + library(ggrepel) + library(viridisLite) + library(reticulate) # If APL uses python/pytorch/numpy via reticulate + + # Set output directory + output_dir <- "{output_directory}" + dir.create(output_dir, showWarnings = FALSE) + + # Load input data + # Assuming input_seurat_object is a path to an RDS file containing a Seurat object + seurat_obj <- readRDS("{input_seurat_object}") + + # Ensure the object is in a format APL expects, e.g., SingleCellExperiment + # APL's dependencies include both Seurat and SingleCellExperiment, + # so it might accept either or have conversion utilities. + # For robustness, we convert to SingleCellExperiment if it's a Seurat object. + if (inherits(seurat_obj, "Seurat")) {{ + message("Converting Seurat object to SingleCellExperiment for APL analysis.") + sce_obj <- as.SingleCellExperiment(seurat_obj) + }} else if (inherits(seurat_obj, "SingleCellExperiment")) {{ + sce_obj <- seurat_obj + }} else {{ + stop("Input object must be a Seurat or SingleCellExperiment object.") + }} + + # Validate cluster_column presence in colData + if (!("{cluster_column}" %in% names(colData(sce_obj)))) {{ + stop(paste0("Cluster column '", "{cluster_column}", "' not found in colData of the input object.")) + }} + + # --- Placeholder for actual APL function calls --- + # The following R code is illustrative and based on the package description. + # It needs to be replaced with actual function calls from the APL R package + # documentation (e.g., APL::runAPL, APL::plotAP, APL::calculateSpecificityScores). + + tryCatch({{ + message("Starting hypothetical APL analysis...") + + # In a real scenario, you would call APL functions here, for example: + # 1. Run Correspondence Analysis and prepare APL-specific data structure: + # apl_results_obj <- APL::runAPL(sce_obj, group_by = "{cluster_column}", + # min_genes = {min_genes_per_cluster}) + # + # 2. Calculate gene specificity scores: + # specificity_scores_df <- APL::calculateSpecificityScores(apl_results_obj) + # write.csv(specificity_scores_df, file.path(output_dir, "gene_specificity_scores.csv"), row.names = FALSE) + # + # 3. Generate Association Plots: + # if (!is.null("{selected_cluster_r_val}")) {{ + # ap_plot_selected <- APL::plotAssociationPlot(apl_results_obj, cluster = "{selected_cluster}", + # top_n = {top_n_genes_for_report}) + # ggplot2::ggsave(file.path(output_dir, "association_plot_{selected_cluster}.png"), ap_plot_selected, width = 10, height = 8) + # }} else {{ + # ap_plot_all <- APL::plotAssociationPlot(apl_results_obj, top_n = {top_n_genes_for_report}) + # ggplot2::ggsave(file.path(output_dir, "association_plot_all_clusters.png"), ap_plot_all, width = 10, height = 8) + # }} + # + # 4. Generate interactive plots if requested (assuming APL has such a function): + # if ({'TRUE' if generate_interactive_plots else 'FALSE'}) {{ + # interactive_ap_plot <- APL::plotInteractiveAP(apl_results_obj) + # htmlwidgets::saveWidget(interactive_ap_plot, file.path(output_dir, "interactive_association_plot.html")) + # }} + + # --- Dummy output generation for demonstration --- + # Create a dummy output file to simulate a summary report + dummy_output_path <- file.path(output_dir, "apl_analysis_summary.txt") + file_conn <- file(dummy_output_path) + writeLines(c( + "APL Analysis Summary (Hypothetical Output)", + paste("Input object:", "{input_seurat_object}"), + paste("Cluster column:", "{cluster_column}"), + paste("Selected cluster (if any):", "{selected_cluster_r_val}"), + paste("Organism (if specified):", "{organism_r_val}"), + paste("Min genes per cluster (hypothetical):", "{min_genes_per_cluster}"), + paste("Top N genes for report (hypothetical):", "{top_n_genes_for_report}"), + paste("Generate interactive plots (hypothetical):", "{'TRUE' if generate_interactive_plots else 'FALSE'}"), + "", + "This is a placeholder output. In a real scenario, APL functions would generate", + "cluster-specific gene lists, specificity scores (e.g., gene_specificity_scores.csv),", + "and various plots (e.g., Association Plots as PNGs and/or interactive HTMLs)." + ), file_conn) + close(file_conn) + + # Save a dummy plot (PNG) + p_png <- ggplot2::ggplot(data.frame(x=1:10, y=1:10, cluster=factor(rep(1:2, each=5))), ggplot2::aes(x,y, color=cluster)) + + ggplot2::geom_point() + + ggplot2::ggtitle("Dummy APL Plot (PNG)") + + ggplot2::theme_minimal() + ggplot2::ggsave(file.path(output_dir, "dummy_apl_plot.png"), p_png, width = 7, height = 5) + + # Save a dummy interactive plot (HTML) if requested + if ({'TRUE' if generate_interactive_plots else 'FALSE'}) {{ + p_html <- plotly::ggplotly(p_png) + htmlwidgets::saveWidget(p_html, file.path(output_dir, "dummy_apl_interactive_plot.html")) + }} + + message("Hypothetical APL analysis completed. Check output directory for dummy files.") + + }}, error = function(e) {{ + stop(paste("R Error:", e$message)) + }}) + """ + + # Prepare R-compatible values for optional parameters + selected_cluster_r_val = f"'{selected_cluster}'" if selected_cluster is not None else "NULL" + organism_r_val = f"'{organism}'" if organism is not None else "NULL" + + # Replace placeholders in the R script content + r_script_content = R_SCRIPT_TEMPLATE.format( + input_seurat_object=input_seurat_object.as_posix(), + output_directory=output_directory.as_posix(), + cluster_column=cluster_column, + selected_cluster=selected_cluster, # Used for filename, not R value + selected_cluster_r_val=selected_cluster_r_val, # Used for R code + organism=organism, # Used for filename/summary, not R value + organism_r_val=organism_r_val, # Used for R code + min_genes_per_cluster=min_genes_per_cluster, + top_n_genes_for_report=top_n_genes_for_report, + generate_interactive_plots=generate_interactive_plots, + ) + + # Create a temporary R script file + 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", temp_r_script_path.as_posix()] + command_executed = " ".join(command) + + stdout = "" + stderr = "" + 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 temporary R script on error + temp_r_script_path.unlink(missing_ok=True) + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}. " + f"See stderr for R-specific error messages.", + "output_files": [], + } + finally: + # Always clean up the temporary R script + temp_r_script_path.unlink(missing_ok=True) + + # Collect all generated files in the output directory + output_files = [str(f) for f in output_directory.rglob("*") if f.is_file()] + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..efd5cdecc96c621c650f4d5d3fb013dcca34ea34 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_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-apl/app/bioconductor-apl_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_apl' + + +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/Biomni/mcp_generated/mcp_bioconductor-apl/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-apl/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apl/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-apl/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-apl/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..683057b32a92cff6c48a6b412fe553e6110b0697 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apl/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-apl: + build: . + image: mcp-bioconductor-apl:latest + container_name: mcp-bioconductor-apl + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-apl + 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/Biomni/mcp_generated/mcp_bioconductor-apl/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-apl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4bbe91da143156538097572747ac1998fc242e59 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apl/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-apl + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-apl/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-apl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-apl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-awaggregator/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..53b52deea05f9bf6f66ad8a3024b5e2a18923bb4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/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-awaggregator via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-awaggregator -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-awaggregator_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-awaggregator_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-awaggregator_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_server.py b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d7481f36fc3a27cadd94ff6bca62631362feecaa --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_server.py @@ -0,0 +1,222 @@ +import subprocess +from pathlib import Path +from typing import Dict, List + +# MCP decorator is assumed to be available in the execution environment. +# No import is needed as per the instructions. +# class mcp: +# @staticmethod +# def tool(): +# def decorator(func): +# return func +# return decorator + + +def _run_awaggregator_cli(cmd: List[str], output_map: Dict[str, Path]) -> Dict: + """ + A private helper function to execute the awaggregator wrapper script, + handle subprocess execution, and format the output. + """ + command_executed = " ".join(map(str, cmd)) + 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": {key: str(path) for key, path in output_map.items()}, + } + except FileNotFoundError: + # This error is raised if 'Rscript' or the wrapper is not in PATH + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' or the wrapper script 'run_awaggregator.R' not found. " + "Please ensure R and the tool's wrapper script are in the system's PATH.", + "output_files": {}, + "error": "Executable not found." + } + except subprocess.CalledProcessError as e: + # This error is raised for non-zero exit codes from the tool + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {}, + "error": f"Tool execution failed with exit code {e.returncode}", + } + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_awaggregator' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def aw_weight( + expression_matrix: Path, + design_matrix: Path, + output_weights_file: Path, +): + """ + Computes adaptive weights for gene expression data meta-analysis. + + This tool wraps the `aw.weight` function from the Bioconductor `awaggregator` package. + It takes an expression data matrix and a design matrix to compute weights for each study. + The resulting weights matrix can be used with the `aw_mean` or `aw_median` tools. + + Args: + expression_matrix: Path to the input expression data matrix file (e.g., CSV, TSV). + Rows should represent genes and columns should represent samples. + design_matrix: Path to the input design matrix file (e.g., CSV, TSV). + This matrix describes the experimental design. + output_weights_file: Path to save the computed weights matrix. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + path to the output weights file. + """ + # --- Input Validation --- + if not expression_matrix.is_file(): + raise FileNotFoundError(f"Input expression matrix file not found: {expression_matrix}") + if not design_matrix.is_file(): + raise FileNotFoundError(f"Input design matrix file not found: {design_matrix}") + + output_dir = output_weights_file.parent + if not output_dir.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_dir}") + + # --- Command Construction --- + # Assumes a wrapper script 'run_awaggregator.R' is available that handles CLI parsing. + cmd = [ + "Rscript", + "run_awaggregator.R", + "--method", + "weight", + "--expression", + expression_matrix, + "--design", + design_matrix, + "--output", + output_weights_file, + ] + + return _run_awaggregator_cli(cmd, {"weights_matrix": output_weights_file}) + + +@mcp.tool() +def aw_mean( + data_matrix: Path, + weights_matrix: Path, + output_file: Path, + na_rm: bool = False, +): + """ + Performs adaptive-weighted mean aggregation on gene expression data. + + This tool wraps the `aw.mean` function from the Bioconductor `awaggregator` package. + It takes a data matrix and a corresponding weights matrix to compute the weighted mean + for each gene (row) across studies (columns). + + Args: + data_matrix: Path to the input data matrix file (e.g., CSV, TSV). + Rows should represent genes and columns should represent studies. + weights_matrix: Path to the input weights matrix file (e.g., CSV, TSV). + Must have the same dimensions as the data matrix. + output_file: Path to save the aggregated results. + na_rm: If True, NA values will be removed before computation. Defaults to False. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + path to the output file. + """ + # --- Input Validation --- + if not data_matrix.is_file(): + raise FileNotFoundError(f"Input data matrix file not found: {data_matrix}") + if not weights_matrix.is_file(): + raise FileNotFoundError(f"Input weights matrix file not found: {weights_matrix}") + + output_dir = output_file.parent + if not output_dir.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_dir}") + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_awaggregator.R", + "--method", + "mean", + "--data", + data_matrix, + "--weights", + weights_matrix, + "--output", + output_file, + ] + if na_rm: + cmd.append("--na-rm") + + return _run_awaggregator_cli(cmd, {"aggregated_data": output_file}) + + +@mcp.tool() +def aw_median( + data_matrix: Path, + weights_matrix: Path, + output_file: Path, + na_rm: bool = False, +): + """ + Performs adaptive-weighted median aggregation on gene expression data. + + This tool wraps the `aw.median` function from the Bioconductor `awaggregator` package. + It takes a data matrix and a corresponding weights matrix to compute the weighted median + for each gene (row) across studies (columns). + + Args: + data_matrix: Path to the input data matrix file (e.g., CSV, TSV). + Rows should represent genes and columns should represent studies. + weights_matrix: Path to the input weights matrix file (e.g., CSV, TSV). + Must have the same dimensions as the data matrix. + output_file: Path to save the aggregated results. + na_rm: If True, NA values will be removed before computation. Defaults to False. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + path to the output file. + """ + # --- Input Validation --- + if not data_matrix.is_file(): + raise FileNotFoundError(f"Input data matrix file not found: {data_matrix}") + if not weights_matrix.is_file(): + raise FileNotFoundError(f"Input weights matrix file not found: {weights_matrix}") + + output_dir = output_file.parent + if not output_dir.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_dir}") + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_awaggregator.R", + "--method", + "median", + "--data", + data_matrix, + "--weights", + weights_matrix, + "--output", + output_file, + ] + if na_rm: + cmd.append("--na-rm") + + return _run_awaggregator_cli(cmd, {"aggregated_data": output_file}) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..275d7035b9d5f97fe9e8b61651c01915dc4b0273 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_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-awaggregator/app/bioconductor-awaggregator_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_awaggregator' + + +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/Biomni/mcp_generated/mcp_bioconductor-awaggregator/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-awaggregator/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ff0371023c533e11773174f48bd51a6d9216bff9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-awaggregator: + build: . + image: mcp-bioconductor-awaggregator:latest + container_name: mcp-bioconductor-awaggregator + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-awaggregator + 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/Biomni/mcp_generated/mcp_bioconductor-awaggregator/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4a35b9239801536a5473e94323a22b826418478d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-awaggregator + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-awaggregator/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-awaggregator/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-banksy/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-banksy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1bfc36fcdba582407198bff96211ec04fd0c3b4 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_server.py b/Biomni/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..abf9e0c8546a4f944ade77f3c371613f842c5032 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-banksy/app/bioconductor-banksy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..443a3dbaa17b252927fcc6750ea19d64dcd0aa4d --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-banksy/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-banksy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-banksy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-banksy/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-banksy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5745dcb463d5d3a4a0240bea07df9ef2cafba776 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-banksy/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-banksy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..508d5e0076bfb9bafa1307f48692fa5c85f624eb --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-banksy/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-banksy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-banksy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-beachmat/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-beachmat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e2d1ddf443e6b5ba969dbb4c0bd4f54e64efe2ee --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-beachmat/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-beachmat via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-beachmat -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-beachmat_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-beachmat_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-beachmat_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py b/Biomni/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18ac9eb5a570aadfe3747f1bdf3dd791c51a3dcd --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py @@ -0,0 +1,226 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_beachmat' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def rscript_run_script( + script_path: str, + args: List[str] = [], + vanilla: bool = True, + save: bool = False, + restore: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + verbose: bool = False, + default_packages: Optional[str] = None, +) -> Dict[str, Any]: + """ + Execute an R script file using Rscript, typically used for Bioconductor/beachmat workflows. + + Args: + script_path: Path to the R script file (.R). + args: Additional command line arguments passed to the script. + vanilla: Combine --no-save, --no-restore, --no-site-file, --no-init-file and --no-environ. + save: Do save workspace at the end of the session. + restore: Do restore previously saved objects at startup. + no_environ: Don't read the site and user environment files. + no_site_file: Don't read the site-wide Rprofile. + no_init_file: Don't read the user R profile. + verbose: Print information on progress. + default_packages: Comma-separated set of package names, or 'NULL'. + """ + script_file = Path(script_path) + if not script_file.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["Rscript"] + + # Add options + if vanilla: + cmd.append("--vanilla") + if save: + cmd.append("--save") + if restore: + cmd.append("--restore") + 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 verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--default-packages={default_packages}") + + cmd.append(str(script_file)) + + if args: + cmd.extend(args) + + 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 rscript_run_expression( + expressions: List[str], + vanilla: bool = True, + save: bool = False, + restore: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + verbose: bool = False, + default_packages: Optional[str] = None, +) -> Dict[str, Any]: + """ + Execute one or more R expressions directly from the command line. + Useful for quick beachmat matrix manipulations or checks. + + Args: + expressions: A list of R code strings to execute (each corresponds to a -e flag). + vanilla: Combine --no-save, --no-restore, --no-site-file, --no-init-file and --no-environ. + save: Do save workspace at the end of the session. + restore: Do restore previously saved objects at startup. + no_environ: Don't read the site and user environment files. + no_site_file: Don't read the site-wide Rprofile. + no_init_file: Don't read the user R profile. + verbose: Print information on progress. + default_packages: Comma-separated set of package names, or 'NULL'. + """ + if not expressions: + return {"error": "No expressions provided."} + + cmd = ["Rscript"] + + # Add options + if vanilla: + cmd.append("--vanilla") + if save: + cmd.append("--save") + if restore: + cmd.append("--restore") + 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 verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--default-packages={default_packages}") + + for expr in expressions: + cmd.extend(["-e", expr]) + + 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 beachmat_inspect_matrix( + rds_path: str, +) -> Dict[str, Any]: + """ + Specific utility to inspect an R matrix object (RDS file) using the beachmat package logic. + Identifies matrix class, dimensions, and storage mode. + + Args: + rds_path: Path to an RDS file containing a matrix-like object. + """ + input_path = Path(rds_path) + if not input_path.exists(): + return {"error": f"RDS file not found: {rds_path}"} + + # R code to inspect the matrix using beachmat-compatible logic + r_code = ( + "suppressPackageStartupMessages(library(beachmat)); " + f"mat <- readRDS('{str(input_path)}'); " + "cat('--- Matrix Metadata ---\\n'); " + "cat('Class:', paste(class(mat), collapse=', '), '\\n'); " + "cat('Dimensions:', paste(dim(mat), collapse=' x '), '\\n'); " + "if(is(mat, 'dgCMatrix')) { cat('Type: Sparse (dgCMatrix)\\n') } " + "else if(is(mat, 'HDF5Matrix')) { cat('Type: HDF5-backed\\n') } " + "else { cat('Type: Dense/Other\\n') }; " + "cat('Storage Mode:', storage.mode(mat), '\\n')" + ) + + cmd = ["Rscript", "--vanilla", "-e", r_code] + + 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": "Ensure 'beachmat' and 'DelayedArray' are installed in the R environment.", + "status": "error" + } + +@mcp.tool() +def rscript_get_version() -> Dict[str, Any]: + """ + Get the version information for Rscript and the R environment. + """ + cmd = ["Rscript", "--version"] + try: + # Rscript --version often outputs to stderr + 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" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6bea6437b8fda4e30f7fbc5555813bf1f5332f33 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_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-beachmat/app/bioconductor-beachmat_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_beachmat' + + +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/Biomni/mcp_generated/mcp_bioconductor-beachmat/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-beachmat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1a3717e241b2cd27a16a8f9aa28e280a06f484e4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-beachmat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-beachmat: + build: . + image: mcp-bioconductor-beachmat:latest + container_name: mcp-bioconductor-beachmat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-beachmat + 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/Biomni/mcp_generated/mcp_bioconductor-beachmat/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-beachmat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..02751f5276ca8f7f7c000952c3eb4b28cd1a78a6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-beachmat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-beachmat + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-beachmat/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-beachmat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-beachmat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-benchdamic/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-benchdamic/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..049a35d085b83f15bc149115150cd24367530eef --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_server.py b/Biomni/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a6ed675c4d398642f704254b729325432807bab0 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..81c55f4d646eb595c0b00feb64ae68cf28d60fcd --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-benchdamic/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-benchdamic/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..65f8f9f6c1b78e6c31e9ba07e6510d513ea8cfaf --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-benchdamic/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-benchdamic/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..69f3813eec164585774531f51cba29fd74c0d74a --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-benchdamic/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-benchdamic/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-benchdamic/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biobase/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biobase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..036e2d732972382824401066de86773db43de86c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biobase/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-biobase via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biobase -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-biobase_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-biobase_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-biobase_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biobase/app/bioconductor-biobase_server.py b/Biomni/mcp_generated/mcp_bioconductor-biobase/app/bioconductor-biobase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0760642f437e0b62049e09c1e0be4cd3c4628e7c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biobase/app/bioconductor-biobase_server.py @@ -0,0 +1,159 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Optional + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# MCP decorator is assumed to be available in the execution environment. +# No need to define or import it. + +@mcp.tool +def rscript_run( + 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: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool is a wrapper for Rscript, allowing the execution of R code from a + file or directly as string expressions. It is commonly used for running + bioinformatics scripts that rely on R and Bioconductor packages. + + Args: + script_file: Path to the R script file to be executed. + expressions: A list of R expressions to execute. Use this or script_file, not both. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, enables verbose output, printing progress information. + default_packages: A comma-separated string of package names to be loaded by default. + save: If True, the R workspace is saved at the end of the session (--save). + no_environ: If True, site and user environment files are not read (--no-environ). + no_site_file: If True, the site-wide Rprofile is not read (--no-site-file). + no_init_file: If True, the user's R profile is not read (--no-init-file). + restore: If True, previously saved objects are restored at startup (--restore). + vanilla: If True, combines --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ. Overrides the individual flags. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if (script_file is None and not expressions) or (script_file is not None and expressions): + raise ValueError("You must provide either 'script_file' or 'expressions', but not both.") + + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + cmd = ["Rscript"] + + 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.append(f"--default-packages={default_packages}") + + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + if script_file: + cmd.append(str(script_file)) + + if script_args: + cmd.extend(script_args) + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + # 3. 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": [] + } + except FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in your PATH.") + raise + except subprocess.CalledProcessError as e: + logger.error(f"Rscript execution failed with return code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Rscript execution failed.", + "return_code": e.returncode, + "output_files": [] + } + +@mcp.tool +def rscript_version() -> dict: + """ + Retrieves the version of the Rscript interpreter. + + Returns: + A dictionary containing the executed command and the version information. + """ + cmd = ["Rscript", "--version"] + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + try: + # Rscript --version prints to stderr and exits with code 0. + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in your PATH.") + raise + except subprocess.CalledProcessError as e: + # This case is unlikely for Rscript --version but is good practice. + logger.error(f"Failed to get Rscript version. Return code: {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve Rscript version.", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biobase/app/bioconductor-biobase_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biobase/app/bioconductor-biobase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c2f8b7156c2fbdc586c04cdbd78171206382be3b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biobase/app/bioconductor-biobase_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-biobase/app/bioconductor-biobase_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biobase' + + +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/Biomni/mcp_generated/mcp_bioconductor-biobase/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biobase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7ab99455c1d5cc2a66cd0672bb717e7e20964491 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biobase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biobase: + build: . + image: mcp-bioconductor-biobase:latest + container_name: mcp-bioconductor-biobase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biobase + 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/Biomni/mcp_generated/mcp_bioconductor-biobase/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biobase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..46fbc1523a52b2bd27837fce805cdd46303e15f1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biobase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biobase + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biobase/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biobase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biobase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ced3fd0e263cd5d1e0e91262cbe9717fba099bb9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/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-biocbaseutils via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocbaseutils -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-biocbaseutils_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-biocbaseutils_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-biocbaseutils_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dced4c771dd091eed198e02b504ae98c9843a05f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_server.py @@ -0,0 +1,102 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List, Any + +# Note: The 'mcp' import is not needed as it's assumed to be in the execution environment. +# from mcp import tool + +# This is a mock decorator for local testing, it should be removed in the MCP environment. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def execute_r_script( + r_script_content: str, + output_filename: Optional[str] = None +) -> Dict[str, Any]: + """ + Executes a user-provided R script in an environment with the bioconductor-biocbaseutils package. + + BiocBaseUtils is an R library that provides utility functions for Bioconductor package development. + It does not have a direct command-line interface. This tool allows you to run custom R code + that leverages the functions within BiocBaseUtils. Your script should load the library + using `library(BiocBaseUtils)` to access its functions. + + Args: + r_script_content: A string containing the complete R code to be executed. + output_filename: Optional. If your R script generates a file, specify its name here. + The script should save the file to the current working directory. + This file will be captured and returned as an output. + + Returns: + A dictionary containing the execution details, including the command, stdout, stderr, + and a list of output file paths. + """ + if not r_script_content or not r_script_content.strip(): + raise ValueError("The 'r_script_content' parameter cannot be empty.") + + # In a real MCP environment, the output directory would be managed by the platform. + # Here, we use a temporary directory to simulate this. + with tempfile.TemporaryDirectory() as temp_dir: + working_dir = Path(temp_dir) + script_path = working_dir / "script.R" + + # Write the user's R code to a temporary script file + with open(script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(script_path)] + command_str = " ".join(command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=working_dir # Execute from the temp directory + ) + + output_files = [] + if output_filename: + expected_output_path = working_dir / output_filename + if expected_output_path.is_file(): + # In a real MCP server, this path would be a persistent output path. + output_files.append(str(expected_output_path)) + else: + # Log a warning if the expected output file is not found + warning_msg = ( + f"Warning: Specified output file '{output_filename}' " + "was not found in the working directory after script execution." + ) + # Append warning to stderr for user visibility + process_stderr = f"{process.stderr}\n{warning_msg}" + else: + process_stderr = process.stderr + + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process_stderr, + "output_files": output_files + } + + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + raise RuntimeError( + "Error: 'Rscript' command not found. Please ensure R is installed " + "and accessible in the execution environment's PATH." + ) from None + except subprocess.CalledProcessError as e: + # This handles cases where the R script itself fails (non-zero exit code) + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"R script execution failed with exit code {e.returncode}." + } diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..34d0cae3d236f786059a220422aaf84272683652 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_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-biocbaseutils/app/bioconductor-biocbaseutils_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biocbaseutils' + + +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/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..37d591a09ca588141719b435a204d26b72c2d08a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocbaseutils: + build: . + image: mcp-bioconductor-biocbaseutils:latest + container_name: mcp-bioconductor-biocbaseutils + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocbaseutils + 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/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4181ef30167d5cae30f272f9b0ddf98485a23cce --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocbaseutils + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocbaseutils/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..baadb8653861e5789a279f826093986fef432e4b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/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-biocfilecache via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocfilecache -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-biocfilecache_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-biocfilecache_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-biocfilecache_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a2fe6f829352c70a067d029777080bbdb6ae2838 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_server.py @@ -0,0 +1,314 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Literal, Optional, Dict + +# This is a placeholder for the actual MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +def _validate_cache_path(cache_path: Path, check_exists: bool = True) -> None: + """Helper function to validate the cache path.""" + if check_exists and not cache_path.is_dir(): + raise FileNotFoundError(f"BiocFileCache directory not found at '{cache_path}'") + +def _r_string_vector(items: List[str]) -> str: + """Converts a Python list of strings to an R character vector string.""" + if not items: + return "c()" + # Escape single quotes for R: ' -> \' + escaped_items = [item.replace("'", "\\'") for item in items] + quoted_items = [f"'{item}'" for item in escaped_items] + return f"c({', '.join(quoted_items)})" + +def _run_r_command(r_command: str) -> Dict: + """Executes an R command and returns a structured response.""" + command = ["Rscript", "-e", r_command] + command_str = " ".join(command) + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + return { + "command_executed": command_str, + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + } + except FileNotFoundError: + logging.error("Rscript not found. R must be installed and in the system's PATH.") + raise RuntimeError("Rscript not found. R must be installed and in the system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"R script execution failed.\nStderr: {e.stderr}\nStdout: {e.stdout}") + return { + "command_executed": command_str, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": "R script execution failed." + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_biocfilecache' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def biocfilecache_new(cache_path: Path) -> Dict: + """ + Creates a new, empty BiocFileCache at the specified location. + + Args: + cache_path: The directory path where the cache will be created. + The parent directory must exist, and the target path must not. + + Returns: + A dictionary containing the command executed, stdout (the cache path), + stderr, and the path to the created cache directory. + """ + if cache_path.exists(): + raise ValueError(f"Cache path '{cache_path}' already exists. Cannot create a new cache here.") + if not cache_path.parent.is_dir(): + raise FileNotFoundError(f"Parent directory '{cache_path.parent}' does not exist.") + + # Use forward slashes for R path compatibility + safe_cache_path = str(cache_path).replace('\\', '/') + r_command = ( + f"library(BiocFileCache); " + f"bfc <- bfcnew('{safe_cache_path}', ask=FALSE); " + f"cat(bfcpath(bfc))" + ) + + response = _run_r_command(r_command) + if "error" not in response: + response["output_files"] = {"cache_directory": str(cache_path)} + return response + +@mcp.tool() +def biocfilecache_add( + cache_path: Path, + rname: str, + fpath: str, + action: Literal["copy", "move", "asis"] = "copy", + rtype: Literal["web", "local"] = "web" +) -> Dict: + """ + Adds a resource to the BiocFileCache. + + Args: + cache_path: Path to the BiocFileCache directory. + rname: A user-friendly name for the resource. + fpath: The path to the resource, either a URL or a local file path. + action: How to handle the file. 'copy' (default), 'move', or 'asis' (for remote files). + rtype: The type of resource, 'web' (default) or 'local'. + + Returns: + A dictionary containing the command executed, stdout (the new resource ID), and stderr. + """ + _validate_cache_path(cache_path) + if rtype == "local" and not Path(fpath).exists(): + raise FileNotFoundError(f"Local file '{fpath}' not found for adding to cache.") + + safe_cache_path = str(cache_path).replace('\\', '/') + # Escape single quotes and normalize path for R + safe_rname = rname.replace("'", "\\'") + safe_fpath = fpath.replace('\\', '/').replace("'", "\\'") + + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"rid <- bfcadd(bfc, rname='{safe_rname}', fpath='{safe_fpath}', action='{action}', rtype='{rtype}'); " + f"cat(rid)" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_rpath(cache_path: Path, rids: List[str]) -> Dict: + """ + Retrieves the local file paths of resources from the cache using their resource IDs (rids). + + Args: + cache_path: Path to the BiocFileCache directory. + rids: A list of resource IDs (e.g., ['BFC1', 'BFC2']) to look up. + + Returns: + A dictionary containing the command executed, stdout (newline-separated file paths), and stderr. + """ + _validate_cache_path(cache_path) + if not rids: + raise ValueError("The 'rids' list cannot be empty.") + + safe_cache_path = str(cache_path).replace('\\', '/') + rids_vector = _r_string_vector(rids) + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"paths <- bfcrpath(bfc, rids={rids_vector}); " + f"cat(paths, sep='\\n')" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_query(cache_path: Path, query: str, field: Optional[str] = None) -> Dict: + """ + Queries the cache metadata using an SQL-like expression. + + Args: + cache_path: Path to the BiocFileCache directory. + query: The SQL 'WHERE' clause for filtering resources (e.g., "rname == 'my_file'"). + field: Optional. The specific column/field to return from the query results. + + Returns: + A dictionary containing the command executed, stdout (query results as a table), and stderr. + """ + _validate_cache_path(cache_path) + safe_cache_path = str(cache_path).replace('\\', '/') + safe_query = query.replace("'", "\\'") + + field_arg = "" + if field: + safe_field = field.replace("'", "\\'") + field_arg = f", field='{safe_field}'" + + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"res <- bfcquery(bfc, query='{safe_query}'{field_arg}); " + f"print(res)" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_remove(cache_path: Path, rids: List[str]) -> Dict: + """ + Removes resources and their associated files from the cache. + + Args: + cache_path: Path to the BiocFileCache directory. + rids: A list of resource IDs to remove. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + _validate_cache_path(cache_path) + if not rids: + raise ValueError("The 'rids' list cannot be empty.") + + safe_cache_path = str(cache_path).replace('\\', '/') + rids_vector = _r_string_vector(rids) + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"bfcremove(bfc, rids={rids_vector}); " + f"cat('Specified resources removed.')" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_ls(cache_path: Path, pattern: Optional[str] = None) -> Dict: + """ + Lists resources in the cache, optionally filtering by a regular expression. + + Args: + cache_path: Path to the BiocFileCache directory. + pattern: An optional regular expression to filter resource names (rname). + + Returns: + A dictionary containing the command executed, stdout (a table of resources), and stderr. + """ + _validate_cache_path(cache_path) + safe_cache_path = str(cache_path).replace('\\', '/') + + pattern_arg = "" + if pattern: + safe_pattern = pattern.replace("'", "\\'") + pattern_arg = f", pattern='{safe_pattern}'" + + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"res <- bfcls(bfc{pattern_arg}); " + f"print(res)" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_update(cache_path: Path, rids: List[str]) -> Dict: + """ + Updates resources in the cache by re-downloading them. + + Args: + cache_path: Path to the BiocFileCache directory. + rids: A list of resource IDs to update. + + Returns: + A dictionary containing the command executed, stdout (updated resource info), and stderr. + """ + _validate_cache_path(cache_path) + if not rids: + raise ValueError("The 'rids' list cannot be empty.") + + safe_cache_path = str(cache_path).replace('\\', '/') + rids_vector = _r_string_vector(rids) + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"res <- bfcupdate(bfc, rids={rids_vector}); " + f"print(res)" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_clean(cache_path: Path) -> Dict: + """ + Cleans the cache by removing files that are no longer tracked in the database. + + Args: + cache_path: Path to the BiocFileCache directory. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + _validate_cache_path(cache_path) + safe_cache_path = str(cache_path).replace('\\', '/') + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"bfcclean(bfc, ask=FALSE); " + f"cat('Cache cleaned.')" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_info(cache_path: Path, rids: Optional[List[str]] = None) -> Dict: + """ + Retrieves detailed metadata for all or specified resources in the cache. + + Args: + cache_path: Path to the BiocFileCache directory. + rids: Optional list of resource IDs to get information for. If None, info for all resources is returned. + + Returns: + A dictionary containing the command executed, stdout (a table of resource info), and stderr. + """ + _validate_cache_path(cache_path) + safe_cache_path = str(cache_path).replace('\\', '/') + rids_arg = f", rids={_r_string_vector(rids)}" if rids else "" + + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"res <- bfcinfo(bfc{rids_arg}); " + f"print(res)" + ) + return _run_r_command(r_command) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5301b33ffa102bdbae33a4faf4f7cade3dbc10 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_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-biocfilecache/app/bioconductor-biocfilecache_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biocfilecache' + + +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/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfaeb2fc1b7bb666760166c994ac11641ccea05c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocfilecache: + build: . + image: mcp-bioconductor-biocfilecache:latest + container_name: mcp-bioconductor-biocfilecache + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocfilecache + 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/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fadedb1ae2ed0930e924af8fb048742ab8741ed4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocfilecache + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocfilecache/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7a2b64e38b21f9a17c0eed662d17a9ffec398d69 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/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-biocgenerics via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocgenerics -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-biocgenerics_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-biocgenerics_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-biocgenerics_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1e11d8460d5c1480e98207fcc450ce32e781875f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_server.py @@ -0,0 +1,148 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported from the MCP library. +def tool(func): + """A dummy decorator to mimic @mcp.tool() for standalone execution.""" + return func + +@tool +def rscript( + file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + version: bool = False, + 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. + + Rscript is the standard command-line interface for R, a core dependency for + Bioconductor packages. This tool allows for running R scripts or evaluating + R code directly. + + Args: + file: Path to an R script file to be executed. + expressions: A list of R expressions to evaluate. Use this instead of 'file'. + script_args: A list of arguments to be passed to the R script itself. + version: If True, print the R version and exit, ignoring other options. + verbose: If True, print information on progress. + default_packages: A comma-separated 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, 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. + """ + # --- Command Construction --- + cmd = ["Rscript"] + + # If --version is requested, it's a special case. + # We run it and return immediately, ignoring all other parameters. + if version: + cmd.append("--version") + 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("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript failed with exit code {e.returncode}", + "output_files": [] + } + + # --- Input Validation for standard execution --- + # Either 'file' or 'expressions' must be provided, but not both. + file_provided = file is not None + expressions_provided = expressions is not None and len(expressions) > 0 + + if not (file_provided ^ expressions_provided): + raise ValueError("You must provide either the 'file' parameter or the 'expressions' parameter, but not both.") + + if file_provided: + if not file.is_file(): + raise FileNotFoundError(f"The specified R script file does not exist: {file}") + + # --- Build the full command --- + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--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_provided: + for expr in expressions: + cmd.extend(["-e", expr]) + + if file_provided: + cmd.append(str(file)) + + if script_args: + cmd.extend(script_args) + + # --- Subprocess Execution --- + command_str = " ".join(cmd) + 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": [] # Rscript itself doesn't define output files; the script might. + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error message for failed executions + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [] + } diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7c76df863a139f993d591cc736d56905e1130b1b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_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-biocgenerics/app/bioconductor-biocgenerics_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biocgenerics' + + +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/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..70411f1e7d442cee4491e9153313717c04073c2a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocgenerics: + build: . + image: mcp-bioconductor-biocgenerics:latest + container_name: mcp-bioconductor-biocgenerics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocgenerics + 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/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..787c5a33b775733411e744e8efa96b3656b0a63c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocgenerics + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocgenerics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocio/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biocio/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6985b38e799424429cc20852d53049a1c6108713 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocio/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-biocio via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocio -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-biocio_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-biocio_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-biocio_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocio/app/bioconductor-biocio_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocio/app/bioconductor-biocio_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5f795aa2bbded90543e93cc79969d57023745fda --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocio/app/bioconductor-biocio_server.py @@ -0,0 +1,209 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Optional + +# @mcp.tool() decorator is assumed to be available in the environment. +# For local testing, you can define a dummy decorator: +# def tool(*args, **kwargs): +# def decorator(f): +# return f +# return decorator +# mcp = type("mcp", (), {"tool": tool}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_biocio' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def biocio_import( + input_file: Path, + output_rds: Path, + additional_args: Optional[str] = None, +) -> Dict: + """ + Imports data using the BiocIO::import() generic function. + + This tool wraps the R BiocIO package's `import()` function. It reads a + biological data file and saves the resulting R object to a file in RDS + (R Data Serialization) format. The execution requires an R environment + with BiocIO and any necessary backend packages (e.g., rtracklayer for + BAM/BED/GFF, rhdf5 for HDF5) installed. + + Args: + input_file (Path): Path to the input data file to be imported. + output_rds (Path): Path for the output RDS file, which will store the + imported R object. + additional_args (Optional[str]): A string of additional arguments to be + passed to the R `import()` function. + Arguments should be in R syntax, + e.g., "format = 'gff3'". + + Returns: + Dict: A dictionary containing the execution command, stdout, stderr, + and a list of output files. + """ + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Prepare arguments for the R function call + r_args = [f"'{input_file}'"] + if additional_args: + r_args.append(additional_args) + + r_function_call = f"BiocIO::import({', '.join(r_args)})" + + # Construct the R script + r_script_content = f""" + # It is crucial that the R environment has the necessary package + # to handle the specific file format (e.g., rtracklayer for BED/BAM). + library(BiocIO) + + try {{ + data_object <- {r_function_call} + saveRDS(data_object, file = '{output_rds}') + cat("Import successful. Object saved to {output_rds}\\n") + }} catch (e) {{ + stop(e) + }} + """ + + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + # Clean up the temporary script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + +@mcp.tool() +def biocio_export( + input_rds: Path, + output_file: Path, + format: Optional[str] = None, + additional_args: Optional[str] = None, +) -> Dict: + """ + Exports an R object using the BiocIO::export() generic function. + + This tool wraps the R BiocIO package's `export()` function. It reads an R + object from an RDS file and exports it to a specified biological data format. + The execution requires an R environment with BiocIO and any necessary backend + packages (e.g., rtracklayer for BAM/BED/GFF) installed. + + Args: + input_rds (Path): Path to the input RDS file containing the R object + to be exported. + output_file (Path): Path for the output data file. The file extension + often determines the format. + format (Optional[str]): Explicitly specify the output format (e.g., "gff3"). + If not provided, it's often inferred from the + output file extension. + additional_args (Optional[str]): A string of additional arguments to be + passed to the R `export()` function. + Arguments should be in R syntax. + + Returns: + Dict: A dictionary containing the execution command, stdout, stderr, + and a list of output files. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + + # Prepare arguments for the R function call + r_args = ["data_object", f"'{output_file}'"] + if format: + r_args.append(f"format = '{format}'") + if additional_args: + r_args.append(additional_args) + + r_function_call = f"BiocIO::export({', '.join(r_args)})" + + # Construct the R script + r_script_content = f""" + # It is crucial that the R environment has the necessary package + # to handle the specific file format (e.g., rtracklayer for BED/BAM). + library(BiocIO) + + try {{ + data_object <- readRDS('{input_rds}') + {r_function_call} + cat("Export successful. Object saved to {output_file}\\n") + }} catch (e) {{ + stop(e) + }} + """ + + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + # Clean up the temporary script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocio/app/bioconductor-biocio_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocio/app/bioconductor-biocio_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdc41b53c03a61035071891a331288c870a1faf --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocio/app/bioconductor-biocio_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-biocio/app/bioconductor-biocio_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biocio' + + +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/Biomni/mcp_generated/mcp_bioconductor-biocio/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocio/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocio/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocio/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biocio/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..639c0c707fd92900cbd7d5b4ec93167bda8bc2b0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocio/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocio: + build: . + image: mcp-bioconductor-biocio:latest + container_name: mcp-bioconductor-biocio + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocio + 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/Biomni/mcp_generated/mcp_bioconductor-biocio/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biocio/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f80685f1ad4043c5b78b5798a9100413f2fb54c0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocio/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocio + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocio/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocio/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocio/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4cdc8c7e26e0a235c8ccaaa029b1ea7b48426fe9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/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-biocneighbors via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocneighbors -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-biocneighbors_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-biocneighbors_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-biocneighbors_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_server.py new file mode 100644 index 0000000000000000000000000000000000000000..62d77d5fa5e03a237bdd2af37ed20d7f9a793d08 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_server.py @@ -0,0 +1,163 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_biocneighbors' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_rscript( + r_script_file: Optional[Path] = None, + r_expressions: Optional[List[str]] = None, + additional_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save_workspace: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore_workspace: bool = False, + vanilla: bool = False, + print_help: bool = False, + print_version: bool = False, +) -> dict: + """ + Executes an R script file or R expressions using the Rscript command-line utility. + + This tool provides a comprehensive interface to the Rscript utility, enabling users + to run R code directly from the command line. It supports two primary modes of + operation: executing a specified R script file or running one or more R expressions + passed as strings. Additionally, it allows for the configuration of various R session + options, such as default package loading, workspace saving/restoring behavior, + and environment file handling. + + Args: + r_script_file: Path to an R script file (.R file) to be executed. This parameter + is mutually exclusive with `r_expressions`. If provided, the file + must exist. + r_expressions: A list of R code strings, where each string represents an + expression to be executed. Each expression will be passed to + Rscript using a separate '-e' flag. This parameter is mutually + exclusive with `r_script_file`. + additional_args: A list of strings representing extra arguments to be passed + to the R script or expressions being executed. These arguments + are typically accessible within the R script via `commandArgs()`. + verbose: If True, Rscript will print information on its progress during execution. + default_packages: A comma-separated string of R package names (e.g., "stats,utils") + that R should load by default. Alternatively, "NULL" can be + specified to prevent any default packages from loading. + save_workspace: If True, the R workspace will be saved at the end of the session. + no_environ: If True, R will not read the site-wide and user-specific environment + files (.Renviron). + no_site_file: If True, R will not read the site-wide R profile file (Rprofile.site). + no_init_file: If True, R will not read the user's R profile file (.Rprofile). + restore_workspace: If True, R will attempt to restore previously saved objects + from a workspace file (.RData) at startup. + vanilla: If True, Rscript will combine the effects of --no-save, --no-restore, + --no-site-file, --no-init-file, and --no-environ, providing a clean + R session. + print_help: If True, Rscript will print its usage information and exit. When this + is True, other execution options are typically ignored by Rscript. + print_version: If True, Rscript will print its version information and exit. When + this is True, other execution options are typically ignored by Rscript. + + Returns: + A dictionary containing the command executed, standard output, standard error, + and a list of any output files generated (typically empty for Rscript itself, + as output files are usually created by the R script being run). + Returns structured error information if the Rscript command fails or encounters + an execution error. + """ + command: List[str] = ["Rscript"] + output_files: List[Path] = [] + + # Handle --help and --version flags first, as they typically cause Rscript to exit immediately. + if print_help: + command.append("--help") + elif print_version: + command.append("--version") + else: + # Validate mutually exclusive input modes: r_script_file vs. r_expressions + if r_script_file and r_expressions: + raise ValueError("Cannot specify both 'r_script_file' and 'r_expressions'. Please choose one mode of execution.") + if not r_script_file and not r_expressions: + raise ValueError("Either 'r_script_file' or 'r_expressions' must be provided to execute R code.") + + # Add the R script file or expressions to the command + if r_script_file: + if not r_script_file.is_file(): + raise FileNotFoundError(f"R script file not found at the specified path: {r_script_file}") + command.append(str(r_script_file)) + elif r_expressions: + for expr in r_expressions: + command.extend(["-e", expr]) + + # Add general Rscript options + if verbose: + command.append("--verbose") + if default_packages is not None: + command.append(f"--default-packages={default_packages}") + + # Add R session options + if save_workspace: + 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_workspace: + command.append("--restore") + if vanilla: + command.append("--vanilla") + + # Add any additional arguments to be passed to the R script + if additional_args: + command.extend(additional_args) + + try: + # Execute the Rscript command + process = subprocess.run( + command, + check=True, # Raise CalledProcessError for non-zero exit codes + capture_output=True, # Capture stdout and stderr + text=True, # Decode stdout and stderr as text + encoding='utf-8' # Specify encoding for consistent text handling + ) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except FileNotFoundError: + # Handle case where 'Rscript' command itself is not found in PATH + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and accessible in your system's PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + # Handle errors reported by Rscript (non-zero exit code) + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except Exception as e: + # Catch any other unexpected errors during execution + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"An unexpected error occurred during Rscript execution: {str(e)}", + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fbdf3888c6c30d785e3094f452dbb2c06ed75c9c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_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-biocneighbors/app/bioconductor-biocneighbors_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biocneighbors' + + +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/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2a76ad0e73e8868ef81968583d407d15c3dcf99c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocneighbors: + build: . + image: mcp-bioconductor-biocneighbors:latest + container_name: mcp-bioconductor-biocneighbors + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocneighbors + 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/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca4a426d4d1955490a5931118107ef1e6defbf17 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocneighbors + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocneighbors/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocparallel/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3889c91481bf1407e096bbf1fe1a4c95a424ee92 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/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-biocparallel via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocparallel -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-biocparallel_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-biocparallel_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-biocparallel_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8bee5cddc0dac7e55b2258f4dd225dc90b195ae0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_server.py @@ -0,0 +1,273 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Literal, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_biocparallel' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def bplapply( + x_expr: str, + fun_expr: str, + workers: int = 2, + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam", + tasks: int = 0, + stop_on_error: bool = True, + input_rds: Optional[str] = None, + output_rds: Optional[str] = None, +): + """ + Parallel version of lapply using BiocParallel. + + Args: + x_expr: R expression representing the list or vector to iterate over (e.g., '1:100'). + fun_expr: R expression for the function to apply (e.g., 'function(i) { Sys.sleep(0.1); i^2 }'). + workers: Number of parallel workers. + backend_type: The BiocParallel backend to use. + tasks: Number of tasks (0 for default). + stop_on_error: Whether to stop execution if an error occurs in a worker. + input_rds: Optional path to an RDS file containing the input data. If provided, x_expr is ignored. + output_rds: Optional path to save the result as an RDS file. + """ + if workers < 1: + workers = 1 + + # Construct R script + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers}, tasks = {tasks}, stop.on.error = {str(stop_on_error).upper()})" + ] + + if input_rds: + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input RDS file not found: {input_rds}"} + r_script.append(f"X <- readRDS('{input_path.absolute()}')") + else: + r_script.append(f"X <- {x_expr}") + + r_script.append(f"FUN <- {fun_expr}") + r_script.append("res <- bplapply(X, FUN, BPPARAM = param)") + + if output_rds: + output_path = Path(output_rds) + r_script.append(f"saveRDS(res, '{output_path.absolute()}')") + else: + r_script.append("print(res)") + + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpmapply( + fun_expr: str, + dots_expr: str, + workers: int = 2, + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam", + more_args_expr: str = "list()", + input_rds: Optional[str] = None, +): + """ + Parallel version of mapply (multivariate apply) using BiocParallel. + + Args: + fun_expr: R expression for the function to apply. + dots_expr: R expression for the arguments to pass to FUN (e.g., 'list(1:3, 4:6)'). + workers: Number of parallel workers. + backend_type: The BiocParallel backend to use. + more_args_expr: R expression for additional arguments to FUN. + input_rds: Optional path to an RDS file containing a list of arguments. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers})" + ] + + if input_rds: + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input RDS file not found: {input_rds}"} + r_script.append(f"args_list <- readRDS('{input_path.absolute()}')") + r_script.append(f"res <- do.call(bpmapply, c(list(FUN = {fun_expr}, MoreArgs = {more_args_expr}, BPPARAM = param), args_list))") + else: + r_script.append(f"res <- bpmapply({fun_expr}, {dots_expr}, MoreArgs = {more_args_expr}, BPPARAM = param)") + + r_script.append("print(res)") + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpvec( + x_expr: str, + fun_expr: str, + workers: int = 2, + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam", + input_rds: Optional[str] = None, +): + """ + Parallel version of vec (vectorized apply) using BiocParallel. + Useful when the function can handle chunks of the vector at once. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers})" + ] + + if input_rds: + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input RDS file not found: {input_rds}"} + r_script.append(f"X <- readRDS('{input_path.absolute()}')") + else: + r_script.append(f"X <- {x_expr}") + + r_script.append(f"res <- bpvec(X, {fun_expr}, BPPARAM = param)") + r_script.append("print(res)") + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpaggregate( + x_expr: str, + by_expr: str, + fun_expr: str, + workers: int = 2, + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam", +): + """ + Parallel version of aggregate using BiocParallel. + + Args: + x_expr: R expression for the data object. + by_expr: R expression for the grouping elements. + fun_expr: R expression for the function to apply. + workers: Number of workers. + backend_type: Parallel backend. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers})", + f"res <- bpaggregate({x_expr}, {by_expr}, {fun_expr}, BPPARAM = param)", + "print(res)" + ] + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpiterate( + iter_expr: str, + fun_expr: str, + workers: int = 2, + backend_type: Literal["SnowParam", "MulticoreParam"] = "SnowParam", + reduce_expr: Optional[str] = None, + init_expr: Optional[str] = None, +): + """ + Parallel iteration over an indeterminate number of elements using an iterator. + + Args: + iter_expr: R expression for the iterator function (should return NULL when finished). + fun_expr: R expression for the function to apply to each element. + workers: Number of workers. + backend_type: Parallel backend. + reduce_expr: Optional R expression for a reduction function. + init_expr: Optional R expression for the initial value for reduction. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers})", + f"ITER <- {iter_expr}", + f"FUN <- {fun_expr}" + ] + + cmd = "res <- bpiterate(ITER, FUN" + if reduce_expr: + cmd += f", REDUCE = {reduce_expr}" + if init_expr: + cmd += f", init = {init_expr}" + cmd += ", BPPARAM = param)" + + r_script.append(cmd) + r_script.append("print(res)") + + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpworkers( + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam" +): + """ + Query the number of available workers for a specific BiocParallel backend. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}()", + "cat(bpworkers(param))" + ] + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpvalidate( + code_snippet: str +): + """ + Validates if a specific R code snippet can be parallelized without errors. + Checks for global variable availability and serialization issues. + """ + r_script = [ + "library(BiocParallel)", + "tryCatch({", + f" expr <- quote({{ {code_snippet} }})", + " bpvalidate(expr)", + " cat('Validation successful')", + "}, error = function(e) {", + " cat('Validation failed:', e$message)", + "})" + ] + return _run_r_command("\n".join(r_script)) + +def _run_r_command(r_code: str): + """ + Helper function to execute R code via Rscript. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + try: + # Check if Rscript is available + subprocess.run(["Rscript", "--version"], capture_output=True, check=True) + + # Execute the script + 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_message": str(e) + } + except FileNotFoundError: + return { + "status": "error", + "error_message": "Rscript not found. Please ensure R is installed and in your PATH." + } + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d307c73d53d718196b2987df1fefb946dfcbc87a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_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-biocparallel/app/bioconductor-biocparallel_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biocparallel' + + +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/Biomni/mcp_generated/mcp_bioconductor-biocparallel/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c703a49304f38194f6f715e8d6331b09c68f0efe --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocparallel: + build: . + image: mcp-bioconductor-biocparallel:latest + container_name: mcp-bioconductor-biocparallel + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocparallel + 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/Biomni/mcp_generated/mcp_bioconductor-biocparallel/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9eff9f9d36cb8cda31d024a072cd5d4682ce6c01 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocparallel + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocparallel/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocparallel/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocsingular/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dc043c8fcb94e3e8d18677417f0b4e0922ffc3f6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/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-biocsingular via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocsingular -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-biocsingular_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-biocsingular_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-biocsingular_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0fac1ae20f7bcc546b140231f57be2e5defaf11f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_server.py @@ -0,0 +1,224 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_biocsingular' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def biocsingular_run_svd( + input_path: str, + output_prefix: str, + k: int = 5, + nu: int = 5, + nv: int = 5, + algorithm: str = "Irlba", + center: bool = True, + scale: bool = False, + deferred: bool = False, +) -> Dict[str, Any]: + """ + Perform Singular Value Decomposition (SVD) on a matrix using BiocSingular. + Supports various algorithms including Exact, Irlba, and Random SVD. + + Args: + input_path: Path to the input matrix file (CSV, TSV, or RDS format). + output_prefix: Prefix for the output files (will create .rds and .csv files). + k: Number of singular values to compute. + nu: Number of left singular vectors to compute. + nv: Number of right singular vectors to compute. + algorithm: SVD algorithm to use ('Exact', 'Irlba', 'Random', 'FastDot'). + center: Whether to center the columns of the matrix. + scale: Whether to scale the columns of the matrix. + deferred: Whether to use deferred centering and scaling (memory efficient). + """ + input_file = Path(input_path) + if not input_file.exists(): + return {"error": f"Input file not found: {input_path}"} + + # Validate algorithm + valid_algos = ["Exact", "Irlba", "Random", "FastDot"] + if algorithm not in valid_algos: + return {"error": f"Invalid algorithm. Must be one of: {', '.join(valid_algos)}"} + + # Construct R script + r_script = f""" + library(BiocSingular) + + # Load data + ext <- tolower(tools::file_ext("{input_path}")) + if (ext == "rds") {{ + mat <- readRDS("{input_path}") + }} else if (ext == "csv") {{ + mat <- as.matrix(read.csv("{input_path}", row.names=1)) + }} else {{ + mat <- as.matrix(read.table("{input_path}", sep="\\t", header=TRUE, row.names=1)) + }} + + # Set parameter object + param <- {algorithm}Param(deferred = {"TRUE" if deferred else "FALSE"}) + + # Run SVD + res <- runSVD( + mat, + k = {k}, + nu = {nu}, + nv = {nv}, + BSPARAM = param, + center = {"TRUE" if center else "FALSE"}, + scale = {"TRUE" if scale else "FALSE"} + ) + + # Save results + saveRDS(res, "{output_prefix}_svd.rds") + write.csv(res$u, "{output_prefix}_u.csv") + write.csv(res$v, "{output_prefix}_v.csv") + write.csv(data.frame(d=res$d), "{output_prefix}_d.csv") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + + output_files = [ + f"{output_prefix}_svd.rds", + f"{output_prefix}_u.csv", + f"{output_prefix}_v.csv", + f"{output_prefix}_d.csv" + ] + + return { + "command_executed": f"BiocSingular::runSVD via Rscript", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f).absolute()) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def biocsingular_run_pca( + input_path: str, + output_prefix: str, + rank: int = 5, + algorithm: str = "Irlba", + center: bool = True, + scale: bool = False, + deferred: bool = False, +) -> Dict[str, Any]: + """ + Perform Principal Component Analysis (PCA) on a matrix using BiocSingular. + Optimized for large-scale genomic data. + + Args: + input_path: Path to the input matrix file (CSV, TSV, or RDS format). + output_prefix: Prefix for the output files. + rank: Number of principal components to compute. + algorithm: PCA algorithm to use ('Exact', 'Irlba', 'Random', 'FastDot'). + center: Whether to center the columns. + scale: Whether to scale the columns. + deferred: Whether to use deferred centering and scaling. + """ + input_file = Path(input_path) + if not input_file.exists(): + return {"error": f"Input file not found: {input_path}"} + + valid_algos = ["Exact", "Irlba", "Random", "FastDot"] + if algorithm not in valid_algos: + return {"error": f"Invalid algorithm. Must be one of: {', '.join(valid_algos)}"} + + r_script = f""" + library(BiocSingular) + + # Load data + ext <- tolower(tools::file_ext("{input_path}")) + if (ext == "rds") {{ + mat <- readRDS("{input_path}") + }} else if (ext == "csv") {{ + mat <- as.matrix(read.csv("{input_path}", row.names=1)) + }} else {{ + mat <- as.matrix(read.table("{input_path}", sep="\\t", header=TRUE, row.names=1)) + }} + + # Set parameter object + param <- {algorithm}Param(deferred = {"TRUE" if deferred else "FALSE"}) + + # Run PCA + res <- runPCA( + mat, + rank = {rank}, + BSPARAM = param, + center = {"TRUE" if center else "FALSE"}, + scale = {"TRUE" if scale else "FALSE"} + ) + + # Save results + saveRDS(res, "{output_prefix}_pca.rds") + write.csv(res$x, "{output_prefix}_pcs.csv") + write.csv(res$rotation, "{output_prefix}_loadings.csv") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + + output_files = [ + f"{output_prefix}_pca.rds", + f"{output_prefix}_pcs.csv", + f"{output_prefix}_loadings.csv" + ] + + return { + "command_executed": f"BiocSingular::runPCA via Rscript", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f).absolute()) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def biocsingular_get_info() -> Dict[str, Any]: + """ + Check if BiocSingular is installed and return version information. + """ + r_script = "library(BiocSingular); cat(as.character(packageVersion('BiocSingular')))" + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "biocsingular_version": result.stdout.strip(), + "status": "installed" + } + except subprocess.CalledProcessError: + return { + "status": "not_found", + "error": "BiocSingular is not installed in the R environment." + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6f45bd0554decc355babe812b955f4ece00bda --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_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-biocsingular/app/bioconductor-biocsingular_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biocsingular' + + +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/Biomni/mcp_generated/mcp_bioconductor-biocsingular/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..291654c99584d5dc3b38c51c7ad55775aac18c3a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocsingular: + build: . + image: mcp-bioconductor-biocsingular:latest + container_name: mcp-bioconductor-biocsingular + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocsingular + 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/Biomni/mcp_generated/mcp_bioconductor-biocsingular/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0df4768f7fb4bd8ff66c5c7dee9e78602b0872f0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocsingular + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biocsingular/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biocsingular/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biomart/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biomart/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..79ad411e2a2130f33623e2ac97b8853e27d93630 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomart/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-biomart via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biomart -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-biomart_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-biomart_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-biomart_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biomart/app/bioconductor-biomart_server.py b/Biomni/mcp_generated/mcp_bioconductor-biomart/app/bioconductor-biomart_server.py new file mode 100644 index 0000000000000000000000000000000000000000..686e64779d67d30d78d5b22860f5341e05aebc5b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomart/app/bioconductor-biomart_server.py @@ -0,0 +1,165 @@ +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}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_biomart' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_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: + """ + Executes an R script or R expressions using Rscript. + + This tool serves as a wrapper around the Rscript command-line utility, + allowing for the execution of R code from a file or directly as expressions. + It provides control over the R session's environment and startup behavior. + + Args: + script_file: Path to the R script file to be executed. + expressions: A list of R expressions to execute. Use this or 'script_file', but not both. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, prints more information on progress. + default_packages: A comma-separated list 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. + If set to True, the individual flags (save, no_environ, etc.) are ignored. + save: If True, saves the workspace at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, does not read site and user environment files. Ignored if 'vanilla' is True. + no_site_file: If True, does not read the site-wide Rprofile. Ignored if 'vanilla' is True. + no_init_file: If True, does not read the user R profile. Ignored if 'vanilla' is True. + restore: If True, restores previously saved objects at startup. Ignored if 'vanilla' is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 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("Provide either 'script_file' or 'expressions', but not both.") + if script_file and not script_file.exists(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + command = ["Rscript"] + + # Add Rscript-specific options + if verbose: + command.append("--verbose") + if default_packages: + command.extend(["--default-packages", default_packages]) + + # Add R session options + 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") + + # 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 for the script itself + if script_args: + command.extend(script_args) + + command_str = " ".join(command) + + 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": [], # Rscript itself doesn't define output files; the script might. + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def get_rscript_version() -> dict: + """ + Retrieves the version of the Rscript interpreter. + + This function executes 'Rscript --version' to get version information + about the R installation. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + command = ["Rscript", "--version"] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript version check failed with return code {e.returncode}", + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-biomart/app/bioconductor-biomart_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biomart/app/bioconductor-biomart_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e8f7ec7cda21238451efe8e705e33d430ce6163d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomart/app/bioconductor-biomart_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-biomart/app/bioconductor-biomart_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biomart' + + +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/Biomni/mcp_generated/mcp_bioconductor-biomart/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biomart/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..28b0d67e45352a76a21edffbb689ba52089af958 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomart/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biomart: + build: . + image: mcp-bioconductor-biomart:latest + container_name: mcp-bioconductor-biomart + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biomart + 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/Biomni/mcp_generated/mcp_bioconductor-biomart/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biomart/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..91792aaa37ed9b8c73981f4630c068f11ca0c2c2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomart/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biomart + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biomart/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biomart/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomart/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biomformat/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biomformat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9421f7ac6a878b4b1b6b7db6f6b3aee6be5ab144 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomformat/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-biomformat via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biomformat -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-biomformat_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-biomformat_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-biomformat_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py b/Biomni/mcp_generated/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c39936f4ba931c23281850080ca7562d6c6cc4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py @@ -0,0 +1,189 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, Any, List + +# --- Internal R Script Definitions --- +# These R scripts act as command-line wrappers for the biomformat R package functions. +# In a real-world scenario, these might be pre-existing R scripts or part of a larger R package. + +_READ_BIOM_R_SCRIPT = """ +# R script to read a BIOM file and save the R object as an RDS file. +suppressPackageStartupMessages(library(biomformat)) + +args <- commandArgs(trailingOnly = TRUE) + +if (length(args) < 2) { + stop("Usage: read_biom_wrapper.R ") +} + +input_file <- args[1] +output_rds_file <- args[2] + +tryCatch({ + biom_obj <- read_biom(input_file) + saveRDS(biom_obj, file = output_rds_file) + cat(paste("Successfully read BIOM file '", input_file, "' and saved R object to '", output_rds_file, "'\\n", sep="")) +}, error = function(e) { + stop(paste("Error reading BIOM file '", input_file, "': ", e$message, sep="")) +}) +""" + +_WRITE_BIOM_R_SCRIPT = """ +# R script to read an R object from an RDS file and write it to a BIOM file. +suppressPackageStartupMessages(library(biomformat)) + +args <- commandArgs(trailingOnly = TRUE) + +if (length(args) < 2) { + stop("Usage: write_biom_wrapper.R ") +} + +input_rds_file <- args[1] +output_biom_file <- args[2] + +tryCatch({ + biom_obj <- readRDS(input_rds_file) + write_biom(biom_obj, output_biom_file) + cat(paste("Successfully wrote R object from '", input_rds_file, "' to BIOM file '", output_biom_file, "'\\n", sep="")) +}, error = function(e) { + stop(paste("Error writing BIOM file '", output_biom_file, "': ", e$message, sep="")) +}) +""" + +# --- Helper Function for R Script Execution --- + +def _execute_r_script(script_content: str, args: List[str]) -> Dict[str, Any]: + """ + Helper function to execute an R script with given arguments. + Writes the R script content to a temporary file and executes it using Rscript. + """ + 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(script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + args + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] # This will be populated by the calling MCP tool function + } + 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": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command) if 'command' in locals() else "Rscript not found", + "stdout": "", + "stderr": "Error: Rscript command not found. Please ensure R is installed and Rscript is in your PATH.", + "error": "Rscript not found", + "output_files": [] + } + finally: + # Clean up the temporary R script file + if temp_r_script_path and temp_r_script_path.exists(): + temp_r_script_path.unlink() + + +# --- MCP Tool Definitions --- + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_biomformat' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def read_biom_file( + input_biom_path: Path, + output_rds_path: Path, +) -> Dict[str, Any]: + """ + Reads a BIOM format file and converts it into an R object saved as an RDS file. + + This tool wraps the `read_biom` function from the `biomformat` R package. + NOTE: This implementation is based on a hypothetical R wrapper script + due to the lack of direct command-line documentation for the R package. + + Args: + input_biom_path: Path to the input BIOM format file. + output_rds_path: Path where the R object (RDS format) will be saved. + + Returns: + A dictionary containing execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_biom_path.is_file(): + raise FileNotFoundError(f"Input BIOM file not found: {input_biom_path}") + + # Ensure parent directory for output exists + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # Prepare arguments for the R script + r_args = [str(input_biom_path), str(output_rds_path)] + + # Execute the R script + result = _execute_r_script(_READ_BIOM_R_SCRIPT, r_args) + + # Add output file to the result if successful and no error occurred + if "error" not in result and output_rds_path.is_file(): + result["output_files"].append(str(output_rds_path)) + + return result + + +@mcp.tool() +def write_biom_file( + input_rds_path: Path, + output_biom_path: Path, +) -> Dict[str, Any]: + """ + Writes an R object (from an RDS file) into a BIOM format file. + + This tool wraps the `write_biom` function from the `biomformat` R package. + NOTE: This implementation is based on a hypothetical R wrapper script + due to the lack of direct command-line documentation for the R package. + + Args: + input_rds_path: Path to the input R object (RDS format) file. + output_biom_path: Path where the BIOM format file will be saved. + + Returns: + A dictionary containing execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_rds_path.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds_path}") + + # Ensure parent directory for output exists + output_biom_path.parent.mkdir(parents=True, exist_ok=True) + + # Prepare arguments for the R script + r_args = [str(input_rds_path), str(output_biom_path)] + + # Execute the R script + result = _execute_r_script(_WRITE_BIOM_R_SCRIPT, r_args) + + # Add output file to the result if successful and no error occurred + if "error" not in result and output_biom_path.is_file(): + result["output_files"].append(str(output_biom_path)) + + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-biomformat/app/bioconductor-biomformat_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biomformat/app/bioconductor-biomformat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cafc15f7d3c98cdc7f462b55215566ab2e3cb60c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomformat/app/bioconductor-biomformat_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-biomformat/app/bioconductor-biomformat_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biomformat' + + +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/Biomni/mcp_generated/mcp_bioconductor-biomformat/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biomformat/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomformat/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-biomformat/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biomformat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..86cabcccd9eb81b29a1a10145f27a8e36bbd6602 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomformat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biomformat: + build: . + image: mcp-bioconductor-biomformat:latest + container_name: mcp-bioconductor-biomformat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biomformat + 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/Biomni/mcp_generated/mcp_bioconductor-biomformat/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biomformat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4ec0abb2d3fc1c760f68917798e92c1f2f3e5bd7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomformat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biomformat + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biomformat/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biomformat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biomformat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biostrings/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biostrings/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..04502dc2af170c29e07379c364d485a2b0cea7b8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biostrings/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-biostrings via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biostrings -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-biostrings_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-biostrings_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-biostrings_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biostrings/app/bioconductor-biostrings_server.py b/Biomni/mcp_generated/mcp_bioconductor-biostrings/app/bioconductor-biostrings_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e10df7f977293903d22e6ed2ef6ca77064b0a04d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biostrings/app/bioconductor-biostrings_server.py @@ -0,0 +1,144 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Mock the decorator for standalone execution +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_biostrings' +mcp = FastMCP(SERVER_NAME) + +@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 Rscript, allowing for the execution of R code + from a file or directly from string expressions. It mirrors the functionality + provided by `Rscript --help`. + + Args: + script_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 '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. + If set, it overrides the individual flags (save, restore, etc.). + save: If True, the workspace is saved at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, site and user environment files are not read. Ignored if 'vanilla' is True. + no_site_file: If True, the site-wide Rprofile is not read. Ignored if 'vanilla' is True. + no_init_file: If True, the user's R profile is not read. Ignored if 'vanilla' is True. + restore: If True, previously saved objects are restored at startup. Ignored if 'vanilla' is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files (always empty). + """ + # 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 and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + if expressions and not expressions: + raise ValueError("'expressions' list cannot be empty if provided.") + + # 2. Command Construction + cmd = ["Rscript"] + + if verbose: + cmd.append("--verbose") + + if default_packages: + cmd.extend(["--default-packages", default_packages]) + + if vanilla: + cmd.append("--vanilla") + else: + # These options are combined and handled by the --vanilla flag in Rscript + 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 expressions or script file to the command + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + elif script_file: + cmd.append(str(script_file)) + + # Add arguments for the R script itself + if script_args: + cmd.extend(script_args) + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + 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 accessible in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the R script itself fails (non-zero exit code) + logging.error(f"Rscript execution failed with return code {e.returncode}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 4. Structured Result Return + # Rscript itself does not have a dedicated output file parameter. Any files + # created are determined by the R code within the script. + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-biostrings/app/bioconductor-biostrings_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biostrings/app/bioconductor-biostrings_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..68e8a6d69fc1468fa0e629197f8d96d8ac7d74d5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biostrings/app/bioconductor-biostrings_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-biostrings/app/bioconductor-biostrings_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biostrings' + + +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/Biomni/mcp_generated/mcp_bioconductor-biostrings/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biostrings/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..04cc0ec4df0b6b32962f9077038c73df1dbbfe47 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biostrings/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biostrings: + build: . + image: mcp-bioconductor-biostrings:latest + container_name: mcp-bioconductor-biostrings + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biostrings + 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/Biomni/mcp_generated/mcp_bioconductor-biostrings/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biostrings/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..45c3e252d78ba0fbedb6d8c87e58e82896f73d44 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biostrings/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biostrings + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biostrings/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biostrings/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biostrings/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-biovizbase/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..900cfadbfef72b2bc8831b962e9c8bde993aaf6f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/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-biovizbase via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biovizbase -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-biovizbase_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-biovizbase_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-biovizbase_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_server.py b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4f071f5ca471156e8fb1d97d681b0bb528acf8c7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_server.py @@ -0,0 +1,445 @@ +import subprocess +from pathlib import Path +from typing import Optional, List +import tempfile +import json +import re + +# NOTE: The @mcp.tool decorator is a placeholder for the actual MCP decorator. +# This code is designed to be used within an MCP environment where `mcp` is defined. + +class mcp: + """Placeholder for MCP decorator for standalone validation.""" + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_biovizbase' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def biovizbase_get_ideogram( + genome: str, + cytoband: bool = True, + sub_set: Optional[str] = None, + output_csv: Optional[str] = None +) -> dict: + """ + Fetches chromosome ideogram data for a specified genome build from UCSC. + + Args: + genome: Genome build name (e.g., 'hg19', 'mm10'). Must be a valid UCSC genome. + cytoband: If True, includes cytoband information in the ideogram. + sub_set: Optional comma-separated list of chromosomes to include (e.g., 'chr1,chr2'). + output_csv: Optional path to save the ideogram data as a CSV file. If not provided, a temporary file will be used. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not genome: + raise ValueError("The 'genome' parameter cannot be empty.") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + subset_code = "sub_set = NULL" + if sub_set: + # Format the subset string for R: 'chr1,chr2' -> 'c("chr1", "chr2")' + formatted_sub_set = ','.join([f'"{s.strip()}"' for s in sub_set.split(',')]) + subset_code = f"sub_set = c({formatted_sub_set})" + + r_script = f""" + library(biovizBase) + {subset_code} + ideogram <- getIdeogram(genome = "{genome}", cytoband = {str(cytoband).upper()}, sub_set = sub_set) + write.csv(as.data.frame(ideogram), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_crunch( + input_file: str, + file_format: str, + which_range: Optional[str] = None, + output_csv: Optional[str] = None +) -> dict: + """ + Transforms genomic data (e.g., BAM, BED, GTF) into a format suitable for visualization by summarizing ranges. + + Args: + input_file: Path to the input genomic data file. + file_format: Format of the input file (e.g., 'bam', 'bed', 'gtf', 'gff'). + which_range: Genomic range to process, in 'chr:start-end' format (e.g., 'chr1:1000-2000'). + output_csv: Optional path to save the crunched data as a CSV file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if which_range and not re.match(r'^\w+:\d+-\d+$', which_range): + raise ValueError("The 'which_range' parameter must be in the format 'chr:start-end'.") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + range_code = "" + if which_range: + chrom, coords = which_range.split(':') + start, end = coords.split('-') + range_code = f', which = GRanges("{chrom}", IRanges({start}, {end}))' + + r_script = f""" + library(biovizBase) + library(GenomicRanges) + library(rtracklayer) + + if ("{file_format.lower()}" == "bam") {{ + library(Rsamtools) + data <- readGAlignments("{input_path}") + }} else {{ + data <- import("{input_path}", format = "{file_format.lower()}") + }} + + res <- crunch(data{range_code}) + write.csv(as.data.frame(res), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_get_bio_color( + color_type: str = "DNA" +) -> dict: + """ + Retrieves standard biological color schemes as a JSON object. + + Args: + color_type: The category of color scheme. Can be 'DNA', 'RNA', 'AMINO_ACID', 'STRAND', 'CYTOBAND', or a UCSC genome build (e.g., 'hg19'). + + Returns: + A dictionary containing the command executed, stdout (with JSON color data), and stderr. + """ + if not color_type: + raise ValueError("The 'color_type' parameter cannot be empty.") + + r_script = f""" + library(biovizBase) + library(jsonlite) + cols <- getBioColor(type = "{color_type}") + cat(jsonlite::toJSON(cols, auto_unbox = TRUE)) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + 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 + } + +@mcp.tool() +def biovizbase_calculate_islands( + input_file: str, + output_csv: Optional[str] = None +) -> dict: + """ + Identifies genomic 'islands' (regions of high density/coverage) in alignment or feature data. + + Args: + input_file: Path to the input file (e.g., BAM, BED). + output_csv: Optional path to save the island coordinates as a CSV file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + r_script = f""" + library(biovizBase) + library(GenomicRanges) + library(rtracklayer) + + if (grepl("\\\\.bam$", "{input_path}", ignore.case = TRUE)) {{ + library(Rsamtools) + data <- readGAlignments("{input_path}") + }} else {{ + data <- import("{input_path}") + }} + + res <- islands(data) + write.csv(as.data.frame(res), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_add_stepping( + input_file: str, + group_name: Optional[str] = None, + extend: int = 0, + output_csv: Optional[str] = None +) -> dict: + """ + Calculates 'stepping' levels for genomic ranges to avoid overlaps in visualization. + + Args: + input_file: Path to input BED, GFF, or other range-based file. + group_name: Optional column name in the data to group by for stepping calculation. + extend: Number of base pairs to extend ranges on each side for overlap calculation. Must be non-negative. + output_csv: Optional path to save the data with the new 'stepping' column. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if extend < 0: + raise ValueError("The 'extend' parameter must be a non-negative integer.") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + group_code = f', group.name = "{group_name}"' if group_name else "" + + r_script = f""" + library(biovizBase) + library(rtracklayer) + data <- import("{input_path}") + res <- addStepping(data{group_code}, extend = {extend}) + write.csv(as.data.frame(res), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_rescale_ranges( + input_file: str, + to_start: int = 0, + to_end: int = 1000, + output_csv: Optional[str] = None +) -> dict: + """ + Rescales genomic coordinates from their original range to a new numeric range. + + Args: + input_file: Path to input BED, GFF, or other range-based file. + to_start: Start of the target numeric range. + to_end: End of the target numeric range. + output_csv: Optional path to save the rescaled data. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if to_start >= to_end: + raise ValueError("The 'to_start' parameter must be less than 'to_end'.") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + r_script = f""" + library(biovizBase) + library(rtracklayer) + data <- import("{input_path}") + res <- rescale(data, to = c({to_start}, {to_end})) + write.csv(as.data.frame(res), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_shrink_introns( + input_file: str, + output_csv: Optional[str] = None +) -> dict: + """ + Shrinks intron regions in transcript data to emphasize exons in visualization. + + Args: + input_file: Path to input GTF/GFF file containing transcript models. + output_csv: Optional path to save the data with shrunk introns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + r_script = f""" + library(biovizBase) + library(GenomicFeatures) + library(rtracklayer) + + # Create a TxDb object for transcript grouping, which is required for shrink + txdb <- makeTxDbFromGFF("{input_path}") + exons <- exonsBy(txdb, by = "tx", use.names = TRUE) + + res <- shrink(exons) + # The result is a GRangesList, we flatten it for CSV output + res_df <- as.data.frame(unlist(res)) + write.csv(res_df, file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..55690b2a09b62942c9606a19b60649ff94f4c1dc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_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-biovizbase/app/bioconductor-biovizbase_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_biovizbase' + + +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/Biomni/mcp_generated/mcp_bioconductor-biovizbase/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-biovizbase/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ec98af79d2afcd4da2168365a6d769cca60b2788 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biovizbase: + build: . + image: mcp-bioconductor-biovizbase:latest + container_name: mcp-bioconductor-biovizbase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biovizbase + 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/Biomni/mcp_generated/mcp_bioconductor-biovizbase/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..015aa551125ca59333db8d3256a12bf658161fbf --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biovizbase + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-biovizbase/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-biovizbase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-blase/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-blase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..130d0cb09407199e02934e5328c96ea05926be5b --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_server.py b/Biomni/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b81d5232adb6c0b67ee95e04b724d805658e9686 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-blase/app/bioconductor-blase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7c22627f7f0173e3d34cda25bb943ceeef526f87 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-blase/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-blase/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-blase/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-blase/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-blase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eccd488237878c7b9413ba58d98e98df504b8bd1 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-blase/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-blase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a2b798ba05a05a1d718a06c7af2ed86cdfa2774 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-blase/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-blase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-blase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-bluster/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-bluster/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..868253a8d30934e342b1f2143bac162c0ab1eba1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bluster/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-bluster via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-bluster -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-bluster_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-bluster_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-bluster_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py b/Biomni/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2935b5ce2a4bf310718ff9792ee045ea02f0e2cb --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py @@ -0,0 +1,618 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Note: bioconductor-bluster is an R package and does not have a direct command-line interface +# that can be executed via `subprocess.run` in the traditional sense (like `samtools` or `bwa`). +# To wrap its functionality, we need to generate and execute R scripts using `Rscript`. +# This approach effectively creates a "command-line interface" for specific R functions. +# +# The following functions demonstrate how to wrap key functionalities of the 'bluster' R package +# by generating an R script on the fly and executing it. +# +# Prerequisites: +# 1. An R environment must be installed and accessible in the system's PATH. +# 2. The 'bluster' Bioconductor package (and its dependencies) must be installed in the R environment. +# This can typically be done in R with: +# if (!requireNamespace("BiocManager", quietly = TRUE)) +# install.packages("BiocManager") +# BiocManager::install("bluster") +# install.packages("utils") # For read.csv/write.csv + +def _run_r_script(r_script_content: str, output_dir: Path) -> Dict[str, Any]: + """ + Helper function to execute an R script. + """ + with tempfile.TemporaryDirectory() as tmpdir: + script_path = Path(tmpdir) / "bluster_script.R" + with open(script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=output_dir # Run Rscript in the output directory to simplify file paths + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] # Specific tools will add their 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": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: Rscript command not found. Please ensure R is installed and in your PATH.", + "error": "Rscript not found", + "output_files": [] + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_bluster' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cluster_rows_kmeans( + input_matrix_file: Path, + k: int, + output_clusters_file: Path, + input_format: str = "csv", + row_names_col: Optional[int] = 1, + seed: Optional[int] = None, + iterations: int = 10, + nstart: int = 1, + min_size: int = 1, + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs k-means clustering on rows of a matrix using bluster::clusterRows with KmeansParam. + + Args: + input_matrix_file: Path to the input matrix file (e.g., CSV or TSV). + The matrix should have features as columns and samples as rows, + or vice-versa, depending on how 'bluster' interprets it. + Typically, rows are items to be clustered. + k: The number of clusters (k) for k-means. Must be a positive integer. + output_clusters_file: Path to save the output cluster assignments (CSV file). + This file will contain a single column 'cluster' with integer assignments. + input_format: Format of the input matrix file. Can be "csv" or "tsv". + row_names_col: Column index (1-based) to use as row names when reading the input matrix. + Set to None if no row names column is present. + seed: Random seed for reproducibility. If None, no seed is set. + iterations: Maximum number of iterations for k-means. + nstart: Number of random starts for k-means. + min_size: Minimum number of cells in a cluster. Clusters smaller than this are merged. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_matrix_file.exists(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix_file}") + if not input_matrix_file.is_file(): + raise ValueError(f"Input matrix file is not a regular file: {input_matrix_file}") + + if k <= 0: + raise ValueError("k (number of clusters) must be a positive integer.") + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if row_names_col is not None and row_names_col <= 0: + raise ValueError("row_names_col must be a positive integer or None.") + if iterations <= 0: + raise ValueError("iterations must be a positive integer.") + if nstart <= 0: + raise ValueError("nstart must be a positive integer.") + if min_size <= 0: + raise ValueError("min_size must be a positive integer.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + # Ensure output_clusters_file is just a filename if output_dir is specified + output_clusters_filename = output_clusters_file.name + full_output_clusters_path = output_dir / output_clusters_filename + + # Generate R script content + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + seed_line = f"set.seed({seed})\n" if seed is not None else "" + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + # Set working directory to output_dir for relative paths + setwd("{output_dir.resolve()}") + + {seed_line} + + # Load input matrix + # Using 'tryCatch' for robust error handling within R + data_matrix <- tryCatch({{ + as.matrix({read_data_func}("{input_matrix_file.resolve()}", {row_names_arg})) + }}, error = function(e) {{ + stop(paste("Error reading input matrix file: ", e$message)) + }}) + + # Perform k-means clustering + blus_param <- KmeansParam( + centers = {k}, + iter.max = {iterations}, + nstart = {nstart}, + min.size = {min_size} + ) + + clusters <- tryCatch({{ + clusterRows(data_matrix, blus_param) + }}, error = function(e) {{ + stop(paste("Error during clustering: ", e$message)) + }}) + + # Save cluster assignments + output_df <- data.frame(cluster = clusters) + if (!is.null(rownames(data_matrix))) {{ + rownames(output_df) <- rownames(data_matrix) + }} + write.csv(output_df, "{output_clusters_filename}", row.names = TRUE) + + message("Clustering complete. Results saved to {output_clusters_filename}") + """ + + # Execute R script + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_clusters_path)) + + return result + +@mcp.tool() +def cluster_rows_hclust( + input_matrix_file: Path, + k: Optional[int] = None, + method: str = "ward.D2", + metric: str = "euclidean", + output_clusters_file: Path = Path("hclust_clusters.csv"), + input_format: str = "csv", + row_names_col: Optional[int] = 1, + seed: Optional[int] = None, + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs hierarchical clustering on rows of a matrix using bluster::clusterRows with HclustParam. + + Args: + input_matrix_file: Path to the input matrix file (e.g., CSV or TSV). + k: The number of clusters to cut the dendrogram into. If None, the full dendrogram is returned + (though for `clusterRows` it will still attempt to cut, so it's usually required). + If not provided, `bluster` might default to a single cluster or error. + It's recommended to provide `k`. + method: The agglomeration method to be used. See `hclust` documentation for options + (e.g., "ward.D2", "single", "complete", "average"). + metric: The distance metric to be used. See `dist` documentation for options + (e.g., "euclidean", "maximum", "manhattan"). + output_clusters_file: Path to save the output cluster assignments (CSV file). + input_format: Format of the input matrix file. Can be "csv" or "tsv". + row_names_col: Column index (1-based) to use as row names when reading the input matrix. + Set to None if no row names column is present. + seed: Random seed for reproducibility. If None, no seed is set. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_matrix_file.exists(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix_file}") + if not input_matrix_file.is_file(): + raise ValueError(f"Input matrix file is not a regular file: {input_matrix_file}") + + if k is not None and k <= 0: + raise ValueError("k (number of clusters) must be a positive integer or None.") + if method not in ["ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median", "centroid"]: + raise ValueError(f"Invalid hclust method: {method}. See `hclust` documentation.") + if metric not in ["euclidean", "maximum", "manhattan", "canberra", "binary", "minkowski"]: + raise ValueError(f"Invalid distance metric: {metric}. See `dist` documentation.") + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if row_names_col is not None and row_names_col <= 0: + raise ValueError("row_names_col must be a positive integer or None.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_clusters_filename = output_clusters_file.name + full_output_clusters_path = output_dir / output_clusters_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + seed_line = f"set.seed({seed})\n" if seed is not None else "" + k_arg = f"cut.k = {k}" if k is not None else "" # bluster::HclustParam uses cut.k + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + setwd("{output_dir.resolve()}") + + {seed_line} + + data_matrix <- tryCatch({{ + as.matrix({read_data_func}("{input_matrix_file.resolve()}", {row_names_arg})) + }}, error = function(e) {{ + stop(paste("Error reading input matrix file: ", e$message)) + }}) + + blus_param <- HclustParam( + method = "{method}", + metric = "{metric}" + {f", {k_arg}" if k_arg else ""} + ) + + clusters <- tryCatch({{ + clusterRows(data_matrix, blus_param) + }}, error = function(e) {{ + stop(paste("Error during clustering: ", e$message)) + }}) + + output_df <- data.frame(cluster = clusters) + if (!is.null(rownames(data_matrix))) {{ + rownames(output_df) <- rownames(data_matrix) + }} + write.csv(output_df, "{output_clusters_filename}", row.names = TRUE) + + message("Hierarchical clustering complete. Results saved to {output_clusters_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_clusters_path)) + + return result + +@mcp.tool() +def cluster_rows_snn_graph( + input_matrix_file: Path, + k_neighbors: int, + output_clusters_file: Path = Path("snn_clusters.csv"), + input_format: str = "csv", + row_names_col: Optional[int] = 1, + type: str = "rank", + method: str = "walktrap", + steps: int = 4, + seed: Optional[int] = None, + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs Shared Nearest Neighbor (SNN) graph-based clustering using bluster::clusterRows with SNNGraphParam. + + Args: + input_matrix_file: Path to the input matrix file (e.g., CSV or TSV). + k_neighbors: Number of nearest neighbors to consider for SNN graph construction. Must be a positive integer. + output_clusters_file: Path to save the output cluster assignments (CSV file). + input_format: Format of the input matrix file. Can be "csv" or "tsv". + row_names_col: Column index (1-based) to use as row names when reading the input matrix. + Set to None if no row names column is present. + type: Type of SNN graph to construct. "rank" (default) or "number". + method: Community detection method for the SNN graph. See `igraph::cluster_walktrap`, `cluster_louvain`, etc. + (e.g., "walktrap", "louvain", "fast_greedy", "leiden"). + steps: Number of random walk steps for "walktrap" method. + seed: Random seed for reproducibility. If None, no seed is set. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_matrix_file.exists(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix_file}") + if not input_matrix_file.is_file(): + raise ValueError(f"Input matrix file is not a regular file: {input_matrix_file}") + + if k_neighbors <= 0: + raise ValueError("k_neighbors must be a positive integer.") + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if row_names_col is not None and row_names_col <= 0: + raise ValueError("row_names_col must be a positive integer or None.") + if type not in ["rank", "number"]: + raise ValueError("type must be 'rank' or 'number'.") + if method not in ["walktrap", "louvain", "fast_greedy", "leiden", "infomap", "label_prop", "edge_betweenness"]: + raise ValueError(f"Invalid SNN graph community detection method: {method}. See `igraph` documentation.") + if steps <= 0: + raise ValueError("steps must be a positive integer for 'walktrap' method.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_clusters_filename = output_clusters_file.name + full_output_clusters_path = output_dir / output_clusters_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + seed_line = f"set.seed({seed})\n" if seed is not None else "" + + # Additional arguments for SNNGraphParam based on method + method_args = "" + if method == "walktrap": + method_args = f", steps = {steps}" + # Other methods might have specific args, but for simplicity, we'll keep it general. + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + library(igraph) # For community detection methods + + setwd("{output_dir.resolve()}") + + {seed_line} + + data_matrix <- tryCatch({{ + as.matrix({read_data_func}("{input_matrix_file.resolve()}", {row_names_arg})) + }}, error = function(e) {{ + stop(paste("Error reading input matrix file: ", e$message)) + }}) + + blus_param <- SNNGraphParam( + k = {k_neighbors}, + type = "{type}", + cluster.fun = "{method}" {method_args} + ) + + clusters <- tryCatch({{ + clusterRows(data_matrix, blus_param) + }}, error = function(e) {{ + stop(paste("Error during clustering: ", e$message)) + }}) + + output_df <- data.frame(cluster = clusters) + if (!is.null(rownames(data_matrix))) {{ + rownames(output_df) <- rownames(data_matrix) + }} + write.csv(output_df, "{output_clusters_filename}", row.names = TRUE) + + message("SNN graph clustering complete. Results saved to {output_clusters_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_clusters_path)) + + return result + +@mcp.tool() +def pairwise_rand_index( + clusters1_file: Path, + clusters2_file: Path, + output_rand_index_file: Path = Path("pairwise_rand_index.csv"), + input_format: str = "csv", + cluster_col_name: str = "cluster", + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Calculates the pairwise Rand index between two sets of cluster assignments using bluster::pairwiseRand. + + Args: + clusters1_file: Path to the first cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + clusters2_file: Path to the second cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + output_rand_index_file: Path to save the output Rand index results (CSV file). + This file will contain the Rand index, adjusted Rand index, etc. + input_format: Format of the input cluster files. Can be "csv" or "tsv". + cluster_col_name: The name of the column containing cluster assignments in the input files. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not clusters1_file.exists(): + raise FileNotFoundError(f"First cluster file not found: {clusters1_file}") + if not clusters1_file.is_file(): + raise ValueError(f"First cluster file is not a regular file: {clusters1_file}") + if not clusters2_file.exists(): + raise FileNotFoundError(f"Second cluster file not found: {clusters2_file}") + if not clusters2_file.is_file(): + raise ValueError(f"Second cluster file is not a regular file: {clusters2_file}") + + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if not cluster_col_name: + raise ValueError("cluster_col_name cannot be empty.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_filename = output_rand_index_file.name + full_output_path = output_dir / output_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + setwd("{output_dir.resolve()}") + + clusters1_df <- tryCatch({{ + {read_data_func}("{clusters1_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading first cluster file: ", e$message)) + }}) + + clusters2_df <- tryCatch({{ + {read_data_func}("{clusters2_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading second cluster file: ", e$message)) + }}) + + if (!("{cluster_col_name}" %in% colnames(clusters1_df))) {{ + stop("Column '{cluster_col_name}' not found in first cluster file.") + }} + if (!("{cluster_col_name}" %in% colnames(clusters2_df))) {{ + stop("Column '{cluster_col_name}' not found in second cluster file.") + }} + + clusters1 <- clusters1_df[["{cluster_col_name}"]] + clusters2 <- clusters2_df[["{cluster_col_name}"]] + + # Ensure cluster assignments have the same length + if (length(clusters1) != length(clusters2)) {{ + stop("Cluster assignment vectors have different lengths.") + }} + + rand_results <- tryCatch({{ + pairwiseRand(clusters1, clusters2, adjusted=TRUE) + }}, error = function(e) {{ + stop(paste("Error calculating pairwise Rand index: ", e$message)) + }}) + + # pairwiseRand returns a numeric vector or matrix. + # For two vectors, it's a single value (adjusted Rand index by default). + # We'll create a data frame to save it. + output_df <- data.frame( + AdjustedRandIndex = rand_results + ) + write.csv(output_df, "{output_filename}", row.names = FALSE) + + message("Pairwise Rand index calculation complete. Results saved to {output_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_path)) + + return result + +@mcp.tool() +def pairwise_jaccard_index( + clusters1_file: Path, + clusters2_file: Path, + output_jaccard_index_file: Path = Path("pairwise_jaccard_index.csv"), + input_format: str = "csv", + cluster_col_name: str = "cluster", + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Calculates the pairwise Jaccard index between two sets of cluster assignments using bluster::pairwiseJaccard. + + Args: + clusters1_file: Path to the first cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + clusters2_file: Path to the second cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + output_jaccard_index_file: Path to save the output Jaccard index results (CSV file). + This file will contain the Jaccard index. + input_format: Format of the input cluster files. Can be "csv" or "tsv". + cluster_col_name: The name of the column containing cluster assignments in the input files. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not clusters1_file.exists(): + raise FileNotFoundError(f"First cluster file not found: {clusters1_file}") + if not clusters1_file.is_file(): + raise ValueError(f"First cluster file is not a regular file: {clusters1_file}") + if not clusters2_file.exists(): + raise FileNotFoundError(f"Second cluster file not found: {clusters2_file}") + if not clusters2_file.is_file(): + raise ValueError(f"Second cluster file is not a regular file: {clusters2_file}") + + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if not cluster_col_name: + raise ValueError("cluster_col_name cannot be empty.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_filename = output_jaccard_index_file.name + full_output_path = output_dir / output_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + setwd("{output_dir.resolve()}") + + clusters1_df <- tryCatch({{ + {read_data_func}("{clusters1_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading first cluster file: ", e$message)) + }}) + + clusters2_df <- tryCatch({{ + {read_data_func}("{clusters2_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading second cluster file: ", e$message)) + }}) + + if (!("{cluster_col_name}" %in% colnames(clusters1_df))) {{ + stop("Column '{cluster_col_name}' not found in first cluster file.") + }} + if (!("{cluster_col_name}" %in% colnames(clusters2_df))) {{ + stop("Column '{cluster_col_name}' not found in second cluster file.") + }} + + clusters1 <- clusters1_df[["{cluster_col_name}"]] + clusters2 <- clusters2_df[["{cluster_col_name}"]] + + # Ensure cluster assignments have the same length + if (length(clusters1) != length(clusters2)) {{ + stop("Cluster assignment vectors have different lengths.") + }} + + jaccard_results <- tryCatch({{ + pairwiseJaccard(clusters1, clusters2) + }}, error = function(e) {{ + stop(paste("Error calculating pairwise Jaccard index: ", e$message)) + }}) + + output_df <- data.frame( + JaccardIndex = jaccard_results + ) + write.csv(output_df, "{output_filename}", row.names = FALSE) + + message("Pairwise Jaccard index calculation complete. Results saved to {output_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_path)) + + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..17c2cf585075776f3f7d0bcf5f4b8955f18bda5e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_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-bluster/app/bioconductor-bluster_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_bluster' + + +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/Biomni/mcp_generated/mcp_bioconductor-bluster/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-bluster/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bluster/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-bluster/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-bluster/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4e3f8a72fa973fcb6f43d8405c4e5376620ed3e0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bluster/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-bluster: + build: . + image: mcp-bioconductor-bluster:latest + container_name: mcp-bioconductor-bluster + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-bluster + 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/Biomni/mcp_generated/mcp_bioconductor-bluster/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-bluster/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f740803f8f3e3ef426d32f4dc6b54cffcdc8160a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bluster/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-bluster + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-bluster/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-bluster/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bluster/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-bsgenome/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e92d90bc32975c5c742f867f85094b60f17d393d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/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-bsgenome via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-bsgenome -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-bsgenome_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-bsgenome_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-bsgenome_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py new file mode 100644 index 0000000000000000000000000000000000000000..588b7a281f58ec1138351f0da97d519f7db6badf --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py @@ -0,0 +1,204 @@ +import subprocess +import tempfile +import shutil +import re +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the actual decorator. +# In a real MCP environment, you would use `@mcp.tool()`. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +@mcp_tool_placeholder() +def forge_bsgenome_data_pkg( + organism: str, + common_name: str, + organism_abbreviation: str, + provider: str, + provider_version: str, + release_date: str, + package_version: str, + author: str, + maintainer: str, + seqs_srcdir: Path, + output_pkg_path: Path, + circ_seqs: Optional[List[str]] = None, + seqfiles_prefix: Optional[str] = None, + seqfiles_suffix: Optional[str] = None, + license_str: str = "Artistic-2.0", + title: Optional[str] = None, + description: Optional[str] = None, + organism_biocview: Optional[str] = None, +) -> dict: + """ + Creates a Bioconductor BSgenome data package from a set of FASTA files. + + This tool wraps the `forgeBSgenomeDataPkg` function from the R/Bioconductor + BSgenome package. It automates the creation of the necessary seed file and + executes an R script to build the package source directory, which is then + returned as a gzipped tarball. + + Args: + organism: Full organism name (e.g., "Homo sapiens"). + common_name: Common name for the organism (e.g., "Human"). + organism_abbreviation: Abbreviation for the organism, used in package naming (e.g., "Hsapiens"). + provider: Source of the genome data (e.g., "UCSC"). + provider_version: Version or build of the genome from the provider (e.g., "hg38"). + release_date: Release date of the genome build (e.g., "Dec. 2013"). + package_version: Version for the new BSgenome package, in X.Y.Z format (e.g., "1.0.0"). + author: The author of this BSgenome package. + maintainer: The maintainer of the package, including email (e.g., "Your Name "). + seqs_srcdir: Input directory containing the genome sequence files (e.g., FASTA files). + output_pkg_path: Path to save the final gzipped tarball of the package source (e.g., 'MyPackage.tar.gz'). + circ_seqs: Optional list of sequence names that are circular (e.g., ["chrM"]). + seqfiles_prefix: Optional prefix for the sequence files within `seqs_srcdir`. + seqfiles_suffix: Optional suffix for the sequence files (e.g., ".fa", ".fasta"). + license_str: The license for the generated package. + title: Optional title for the package. A default will be generated if not provided. + description: Optional description for the package. A default will be generated if not provided. + organism_biocview: Optional Bioconductor view term for the organism (e.g., "Homo_sapiens"). + + Returns: + A dictionary containing the execution details and path to the output file. + """ + # 1. Input Validation + if not seqs_srcdir.is_dir(): + raise ValueError(f"Input directory '{seqs_srcdir}' does not exist or is not a directory.") + if not re.match(r"^\d+\.\d+\.\d+$", package_version): + raise ValueError(f"Package version '{package_version}' is not in X.Y.Z format.") + for name_part in [organism_abbreviation, provider]: + if not name_part.isalnum(): + raise ValueError(f"Package name component '{name_part}' contains invalid characters. Use only alphanumerics.") + if not output_pkg_path.parent.exists(): + output_pkg_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate derived values + sanitized_provider_version = re.sub(r'[^a-zA-Z0-9.]', '', provider_version) + package_name = f"BSgenome.{organism_abbreviation}.{provider}.{sanitized_provider_version}" + bsgenome_objname = organism_abbreviation + + if title is None: + title = f"Full genome sequences for {organism} ({provider} version {provider_version})" + if description is None: + description = ( + f"Full genome sequences for {organism} ({common_name}) as provided by " + f"{provider} ({provider_version}, {release_date}) and stored in Biostrings objects." + ) + + organism_biocview_val = organism_biocview if organism_biocview else organism.replace(" ", "_") + + # 3. Create seed file content + seed_content = [ + f"Package: {package_name}", + f"Title: {title}", + f"Description: {description}", + f"Version: {package_version}", + f"Author: {author}", + f"Maintainer: {maintainer}", + f"License: {license_str}", + f"organism: {organism}", + f"common_name: {common_name}", + f"provider: {provider}", + f"provider_version: {provider_version}", + f"release_date: {release_date}", + f"BSgenomeObjname: {bsgenome_objname}", + f"organism_biocview: {organism_biocview_val}", + f"seqs_srcdir: {seqs_srcdir.resolve()}", + ] + + if circ_seqs: + r_vector = ', '.join(f'"{seq}"' for seq in circ_seqs) + seed_content.append(f"circ_seqs: c({r_vector})") + if seqfiles_prefix: + seed_content.append(f"seqfiles_prefix: {seqfiles_prefix}") + if seqfiles_suffix: + seed_content.append(f"seqfiles_suffix: {seqfiles_suffix}") + + seed_file_text = "\n".join(seed_content) + + # 4. Create R script + r_script_text = f""" + # Ensure BiocManager and BSgenome are installed + if (!requireNamespace("BiocManager", quietly = TRUE)) {{ + install.packages("BiocManager", repos="http://cran.us.r-project.org") + }} + if (!requireNamespace("BSgenome", quietly = TRUE)) {{ + BiocManager::install("BSgenome", update=FALSE, ask=FALSE) + }} + + library(BSgenome) + + # Forge the package + tryCatch({{ + forgeBSgenomeDataPkg(seed_file="seed.txt", destdir=".") + cat("BSgenome package '{package_name}' successfully forged.\\n") + }}, error = function(e) {{ + cat("Error during package forging:\\n") + cat(conditionMessage(e), "\\n") + quit(status = 1) + }}) + """ + + # 5. Execute in a temporary directory + with tempfile.TemporaryDirectory() as tmpdir: + work_dir = Path(tmpdir) + seed_file_path = work_dir / "seed.txt" + r_script_path = work_dir / "run_forge.R" + + seed_file_path.write_text(seed_file_text) + r_script_path.write_text(r_script_text) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + process = subprocess.run( + cmd, + cwd=work_dir, + check=True, + capture_output=True, + text=True, + encoding='utf-8', + ) + + # 6. Package the result + created_pkg_dir = work_dir / package_name + if not created_pkg_dir.is_dir(): + raise FileNotFoundError( + f"BSgenome package directory '{package_name}' was not created. " + f"Check R script output for errors.\nStderr: {process.stderr}" + ) + + archive_base_name = str(output_pkg_path.with_suffix('')) + archive_path_str = shutil.make_archive( + base_name=archive_base_name, + format='gztar', + root_dir=work_dir, + base_dir=package_name + ) + + final_archive_path = Path(archive_path_str) + if final_archive_path != output_pkg_path: + final_archive_path.rename(output_pkg_path) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"bsgenome_package_archive": str(output_pkg_path)} + } + + except subprocess.CalledProcessError as e: + # Using .decode() in case the output is not valid utf-8 on error + stdout = e.stdout if isinstance(e.stdout, str) else e.stdout.decode('utf-8', errors='replace') + stderr = e.stderr if isinstance(e.stderr, str) else e.stderr.decode('utf-8', errors='replace') + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb720b2784dd003f7e56b21b72339d441c2c9fe --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_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-bsgenome/app/bioconductor-bsgenome_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_bsgenome' + + +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/Biomni/mcp_generated/mcp_bioconductor-bsgenome/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-bsgenome/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a16172fc9d353b1fa84f3f1c445702f0bc06751b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-bsgenome: + build: . + image: mcp-bioconductor-bsgenome:latest + container_name: mcp-bioconductor-bsgenome + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-bsgenome + 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/Biomni/mcp_generated/mcp_bioconductor-bsgenome/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d3824d6847258fcb5b0a063d4a0c1268b07dfd8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-bsgenome + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-bsgenome/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bsgenome/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3107847f2dfbb429afa7fc70ade5d99d13d901f4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/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-bulksignalr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-bulksignalr -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-bulksignalr_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-bulksignalr_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-bulksignalr_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_server.py b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be9a53af15c95c8eafd16b42e08c9381adc407e9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_server.py @@ -0,0 +1,473 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# This is a placeholder for the MCP decorator. +# The actual MCP environment will provide this. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +# --- R Script Templates --- + +R_SCRIPT_BULK_DE = """ +# Load libraries +suppressPackageStartupMessages(library(argparse)) +suppressPackageStartupMessages(library(bulksignalr)) +suppressPackageStartupMessages(library(SingleCellExperiment)) +suppressPackageStartupMessages(library(Matrix)) + +# Create a parser +parser <- ArgumentParser(description = "Run bulksignalr bulk_de") + +# Add arguments +parser$add_argument("--counts", type = "character", required = TRUE, help = "Path to the counts matrix file (TSV format)") +parser$add_argument("--metadata", type = "character", required = TRUE, help = "Path to the metadata file (TSV format)") +parser$add_argument("--output", type = "character", required = TRUE, help = "Path to the output DE results file (TSV format)") +parser$add_argument("--design", type = "character", required = TRUE, help = "Design formula for the model (e.g., '~ 0 + group')") +parser$add_argument("--sample_col", type = "character", default = "sample", help = "Column name for samples in metadata") +parser$add_argument("--group_col", type = "character", default = "group", help = "Column name for groups in metadata") +parser$add_argument("--lfc_threshold", type = "double", default = 0, help = "Log-fold change threshold") +parser$add_argument("--fdr_threshold", type = "double", default = 0.05, help = "FDR threshold") +parser$add_argument("--min_cells", type = "integer", default = 3, help = "Minimum number of cells expressing a gene") +parser$add_argument("--min_samples", type = "integer", default = 2, help = "Minimum number of samples in a group") +parser$add_argument("--n_cores", type = "integer", default = 1, help = "Number of cores to use") + +# Parse arguments +args <- parser$parse_args() + +# Read data +counts <- read.csv(args$counts, sep = "\\t", row.names = 1, check.names = FALSE) +counts_matrix <- as.matrix(counts) +metadata <- read.csv(args$metadata, sep = "\\t", row.names = 1, check.names = FALSE) + +# Ensure metadata rows match counts columns +if (!all(colnames(counts_matrix) %in% rownames(metadata))) { + stop("Not all column names in the counts matrix are present as row names in the metadata.") +} +metadata <- metadata[colnames(counts_matrix), , drop = FALSE] + +# Create SingleCellExperiment object +sce <- SingleCellExperiment(assays = list(counts = counts_matrix), + colData = metadata) + +# Run bulk_de +de_results <- bulk_de( + object = sce, + design = as.formula(args$design), + sample_col = args$sample_col, + group_col = args$group_col, + lfc_threshold = args$lfc_threshold, + fdr_threshold = args$fdr_threshold, + min_cells = args$min_cells, + min_samples = args$min_samples, + n_cores = args$n_cores +) + +# Save results +write.table(de_results, file = args$output, sep = "\\t", row.names = FALSE, quote = FALSE) + +cat("bulk_de analysis completed successfully.\\n") +""" + +R_SCRIPT_BULK_WALK = """ +# Load libraries +suppressPackageStartupMessages(library(argparse)) +suppressPackageStartupMessages(library(bulksignalr)) +suppressPackageStartupMessages(library(SingleCellExperiment)) +suppressPackageStartupMessages(library(Matrix)) + +# Create a parser +parser <- ArgumentParser(description = "Run bulksignalr bulk_walk") + +# Add arguments +parser$add_argument("--counts", type = "character", required = TRUE, help = "Path to the counts matrix file (TSV format)") +parser$add_argument("--metadata", type = "character", required = TRUE, help = "Path to the metadata file (TSV format)") +parser$add_argument("--de_results", type = "character", required = TRUE, help = "Path to the DE results file from bulk_de (TSV format)") +parser$add_argument("--output", type = "character", required = TRUE, help = "Path to the output co-regulation results file (TSV format)") +parser$add_argument("--sample_col", type = "character", default = "sample", help = "Column name for samples in metadata") +parser$add_argument("--group_col", type = "character", default = "group", help = "Column name for groups in metadata") +parser$add_argument("--cor_method", type = "character", choices = c("spearman", "pearson"), default = "spearman", help = "Correlation method") +parser$add_argument("--cor_threshold", type = "double", default = 0.4, help = "Correlation threshold") +parser$add_argument("--n_cores", type = "integer", default = 1, help = "Number of cores to use") + +# Parse arguments +args <- parser$parse_args() + +# Read data +counts <- read.csv(args$counts, sep = "\\t", row.names = 1, check.names = FALSE) +counts_matrix <- as.matrix(counts) +metadata <- read.csv(args$metadata, sep = "\\t", row.names = 1, check.names = FALSE) +de_results <- read.csv(args$de_results, sep = "\\t", check.names = FALSE) + +# Ensure metadata rows match counts columns +if (!all(colnames(counts_matrix) %in% rownames(metadata))) { + stop("Not all column names in the counts matrix are present as row names in the metadata.") +} +metadata <- metadata[colnames(counts_matrix), , drop = FALSE] + +# Create SingleCellExperiment object +sce <- SingleCellExperiment(assays = list(counts = counts_matrix), + colData = metadata) +colData(sce)[[args$sample_col]] <- colData(sce)[[args$sample_col]] +colData(sce)[[args$group_col]] <- colData(sce)[[args$group_col]] + +# Run bulk_walk +walk_results <- bulk_walk( + object = sce, + de_results = de_results, + sample_col = args$sample_col, + group_col = args$group_col, + cor_method = args$cor_method, + cor_threshold = args$cor_threshold, + n_cores = args$n_cores +) + +# Save results +write.table(walk_results, file = args$output, sep = "\\t", row.names = FALSE, quote = FALSE) + +cat("bulk_walk analysis completed successfully.\\n") +""" + +R_SCRIPT_SIGNAL_WALK = """ +# Load libraries +suppressPackageStartupMessages(library(argparse)) +suppressPackageStartupMessages(library(bulksignalr)) +suppressPackageStartupMessages(library(SingleCellExperiment)) +suppressPackageStartupMessages(library(Matrix)) + +# Create a parser +parser <- ArgumentParser(description = "Run bulksignalr signal_walk") + +# Add arguments +parser$add_argument("--counts", type = "character", required = TRUE, help = "Path to the counts matrix file (TSV format)") +parser$add_argument("--metadata", type = "character", required = TRUE, help = "Path to the metadata file (TSV format)") +parser$add_argument("--bulk_walk_results", type = "character", required = TRUE, help = "Path to the bulk_walk results file (TSV format)") +parser$add_argument("--output", type = "character", required = TRUE, help = "Path to the output signaling results file (TSV format)") +parser$add_argument("--sample_col", type = "character", default = "sample", help = "Column name for samples in metadata") +parser$add_argument("--group_col", type = "character", default = "group", help = "Column name for groups in metadata") +parser$add_argument("--lr_db", type = "character", default = NULL, help = "Optional path to a custom ligand-receptor database file (TSV format)") +parser$add_argument("--n_perms", type = "integer", default = 1000, help = "Number of permutations for significance testing") +parser$add_argument("--n_cores", type = "integer", default = 1, help = "Number of cores to use") + +# Parse arguments +args <- parser$parse_args() + +# Read data +counts <- read.csv(args$counts, sep = "\\t", row.names = 1, check.names = FALSE) +counts_matrix <- as.matrix(counts) +metadata <- read.csv(args$metadata, sep = "\\t", row.names = 1, check.names = FALSE) +bulk_walk_results <- read.csv(args$bulk_walk_results, sep = "\\t", check.names = FALSE) + +# Load ligand-receptor database +if (!is.null(args$lr_db)) { + lr_db <- read.csv(args$lr_db, sep = "\\t", check.names = FALSE) +} else { + lr_db <- bulksignalr::lr_db +} + +# Ensure metadata rows match counts columns +if (!all(colnames(counts_matrix) %in% rownames(metadata))) { + stop("Not all column names in the counts matrix are present as row names in the metadata.") +} +metadata <- metadata[colnames(counts_matrix), , drop = FALSE] + +# Create SingleCellExperiment object +sce <- SingleCellExperiment(assays = list(counts = counts_matrix), + colData = metadata) +colData(sce)[[args$sample_col]] <- colData(sce)[[args$sample_col]] +colData(sce)[[args$group_col]] <- colData(sce)[[args$group_col]] + +# Run signal_walk +signal_results <- signal_walk( + object = sce, + bulk_walk_results = bulk_walk_results, + ligand_receptor_db = lr_db, + sample_col = args$sample_col, + group_col = args$group_col, + n_perms = args$n_perms, + n_cores = args$n_cores +) + +# Save results +write.table(signal_results, file = args$output, sep = "\\t", row.names = FALSE, quote = FALSE) + +cat("signal_walk analysis completed successfully.\\n") +""" + +# --- MCP Tools --- + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_bulksignalr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def bulk_de( + counts_file: Path, + metadata_file: Path, + design: str, + output_file: Path, + sample_col: str = "sample", + group_col: str = "group", + lfc_threshold: float = 0.0, + fdr_threshold: float = 0.05, + min_cells: int = 3, + min_samples: int = 2, + n_cores: int = 1, +): + """ + Performs differential expression analysis using bulksignalr::bulk_de. + + This tool requires an R environment with the 'bulksignalr', 'SingleCellExperiment', + 'Matrix', and 'argparse' packages installed. + + Args: + counts_file: Path to the counts matrix file (TSV format, genes as rows, cells/samples as columns). + metadata_file: Path to the metadata file (TSV format, cells/samples as rows). + design: Design formula for the model (e.g., '~ 0 + group'). + output_file: Path to save the differential expression results (TSV format). + sample_col: Column name for samples in the metadata file. + group_col: Column name for groups in the metadata file. + lfc_threshold: Log-fold change threshold for differential expression. + fdr_threshold: False discovery rate (FDR) threshold. + min_cells: Minimum number of cells a gene must be expressed in to be included. + min_samples: Minimum number of samples required within a group for comparison. + n_cores: Number of CPU cores to use for parallel processing. + """ + # Input validation + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not design.strip(): + raise ValueError("Design formula cannot be empty.") + if not (0 <= fdr_threshold <= 1): + raise ValueError("fdr_threshold must be between 0 and 1.") + if lfc_threshold < 0: + raise ValueError("lfc_threshold must be non-negative.") + if min_cells < 0: + raise ValueError("min_cells must be non-negative.") + if min_samples < 1: + raise ValueError("min_samples must be at least 1.") + if n_cores < 1: + raise ValueError("n_cores must be at least 1.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(R_SCRIPT_BULK_DE) + r_script_path = r_script_file.name + + cmd = [ + "Rscript", r_script_path, + "--counts", str(counts_file), + "--metadata", str(metadata_file), + "--output", str(output_file), + "--design", design, + "--sample_col", sample_col, + "--group_col", group_col, + "--lfc_threshold", str(lfc_threshold), + "--fdr_threshold", str(fdr_threshold), + "--min_cells", str(min_cells), + "--min_samples", str(min_samples), + "--n_cores", str(n_cores), + ] + + process = subprocess.run(cmd, check=True, capture_output=True, text=True) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + +@mcp.tool() +def bulk_walk( + counts_file: Path, + metadata_file: Path, + de_results_file: Path, + output_file: Path, + sample_col: str = "sample", + group_col: str = "group", + cor_method: str = "spearman", + cor_threshold: float = 0.4, + n_cores: int = 1, +): + """ + Identifies co-regulated gene clusters using bulksignalr::bulk_walk. + + This tool requires an R environment with the 'bulksignalr', 'SingleCellExperiment', + 'Matrix', and 'argparse' packages installed. + + Args: + counts_file: Path to the counts matrix file (TSV format). + metadata_file: Path to the metadata file (TSV format). + de_results_file: Path to the differential expression results file from `bulk_de`. + output_file: Path to save the co-regulation cluster results (TSV format). + sample_col: Column name for samples in the metadata file. + group_col: Column name for groups in the metadata file. + cor_method: Correlation method to use ('spearman' or 'pearson'). + cor_threshold: Correlation threshold for defining co-regulation. + n_cores: Number of CPU cores to use for parallel processing. + """ + # Input validation + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not de_results_file.is_file(): + raise FileNotFoundError(f"DE results file not found: {de_results_file}") + if cor_method not in ["spearman", "pearson"]: + raise ValueError("cor_method must be either 'spearman' or 'pearson'.") + if not (0 <= cor_threshold <= 1): + raise ValueError("cor_threshold must be between 0 and 1.") + if n_cores < 1: + raise ValueError("n_cores must be at least 1.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(R_SCRIPT_BULK_WALK) + r_script_path = r_script_file.name + + cmd = [ + "Rscript", r_script_path, + "--counts", str(counts_file), + "--metadata", str(metadata_file), + "--de_results", str(de_results_file), + "--output", str(output_file), + "--sample_col", sample_col, + "--group_col", group_col, + "--cor_method", cor_method, + "--cor_threshold", str(cor_threshold), + "--n_cores", str(n_cores), + ] + + process = subprocess.run(cmd, check=True, capture_output=True, text=True) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + +@mcp.tool() +def signal_walk( + counts_file: Path, + metadata_file: Path, + bulk_walk_results_file: Path, + output_file: Path, + sample_col: str = "sample", + group_col: str = "group", + ligand_receptor_db_file: Optional[Path] = None, + n_perms: int = 1000, + n_cores: int = 1, +): + """ + Identifies potential signaling genes using bulksignalr::signal_walk. + + This tool requires an R environment with the 'bulksignalr', 'SingleCellExperiment', + 'Matrix', and 'argparse' packages installed. + + Args: + counts_file: Path to the counts matrix file (TSV format). + metadata_file: Path to the metadata file (TSV format). + bulk_walk_results_file: Path to the co-regulation results from `bulk_walk`. + output_file: Path to save the signaling analysis results (TSV format). + sample_col: Column name for samples in the metadata file. + group_col: Column name for groups in the metadata file. + ligand_receptor_db_file: Optional path to a custom ligand-receptor database (TSV). + If not provided, the built-in database is used. + n_perms: Number of permutations for significance testing. + n_cores: Number of CPU cores to use for parallel processing. + """ + # Input validation + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not bulk_walk_results_file.is_file(): + raise FileNotFoundError(f"bulk_walk results file not found: {bulk_walk_results_file}") + if ligand_receptor_db_file and not ligand_receptor_db_file.is_file(): + raise FileNotFoundError(f"Ligand-receptor DB file not found: {ligand_receptor_db_file}") + if n_perms < 1: + raise ValueError("n_perms must be at least 1.") + if n_cores < 1: + raise ValueError("n_cores must be at least 1.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(R_SCRIPT_SIGNAL_WALK) + r_script_path = r_script_file.name + + cmd = [ + "Rscript", r_script_path, + "--counts", str(counts_file), + "--metadata", str(metadata_file), + "--bulk_walk_results", str(bulk_walk_results_file), + "--output", str(output_file), + "--sample_col", sample_col, + "--group_col", group_col, + "--n_perms", str(n_perms), + "--n_cores", str(n_cores), + ] + if ligand_receptor_db_file: + cmd.extend(["--lr_db", str(ligand_receptor_db_file)]) + + process = subprocess.run(cmd, check=True, capture_output=True, text=True) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + 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/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eb346c05ef287da88b942b3071ce0a4e71319ebc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_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-bulksignalr/app/bioconductor-bulksignalr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_bulksignalr' + + +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/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d72a6246e2b76a0ccf6c71ebb53a4fa56f20c47d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-bulksignalr: + build: . + image: mcp-bioconductor-bulksignalr:latest + container_name: mcp-bioconductor-bulksignalr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-bulksignalr + 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/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b52b1c33a3dec4f61c346282f61bc93331020d24 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-bulksignalr + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-bulksignalr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-cardspa/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-cardspa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..53a99bf8cbf88e922ebdad2fbfe1ce6dd59da719 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cardspa/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-cardspa via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cardspa -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-cardspa_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-cardspa_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-cardspa_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cardspa/app/bioconductor-cardspa_server.py b/Biomni/mcp_generated/mcp_bioconductor-cardspa/app/bioconductor-cardspa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..90c0f13ea1cf94688a5ffb7d36f2230cb81fb38b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cardspa/app/bioconductor-cardspa_server.py @@ -0,0 +1,189 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Literal, Union + +# This is a placeholder for the MCP framework's decorator. +# The user's environment will provide the actual mcp.tool implementation. +class Mcp: + def tool(self): + def decorator(f): + return f + return decorator +mcp = Mcp() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_cardspa' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cardspa( + sce_object: Path, + output_path: Path, + phenotype_col: str, + location_col_1: str = "row", + location_col_2: str = "col", + method: Literal["Giotto", "SpaGCN", "BayesSpace"] = "Giotto", + num_results: int = 10, + num_core: int = 1, + min_cells: int = 10, + min_pairs: int = 10, +) -> Dict[str, Union[str, List[str], int]]: + """ + Performs spatial analysis on single-cell data using the cardspa R package. + + This tool wraps the main `cardspa` function, which can utilize different + backend methods like Giotto, SpaGCN, or BayesSpace to identify significant + co-enrichment of cell types in spatial transcriptomics data. + + Args: + sce_object: Path to the input SingleCellExperiment object in RDS format. + output_path: Path to save the output results object in RDS format. + phenotype_col: The column name in the SCE object's colData that contains cell type annotations. + location_col_1: The column name for the first spatial coordinate (e.g., 'row', 'x'). + location_col_2: The column name for the second spatial coordinate (e.g., 'col', 'y'). + method: The computational method to use for the analysis. + num_results: The number of top co-enriched cell type pairs to return. + num_core: The number of CPU cores to use for parallel processing. + min_cells: The minimum number of cells required for a cell type to be included in the analysis. + min_pairs: The minimum number of interacting pairs for a result to be considered significant. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + In case of an error, it includes an error message and return code. + """ + # --- Input Validation --- + if not sce_object.is_file(): + raise FileNotFoundError(f"Input file not found: {sce_object}") + + if not output_path.parent.is_dir(): + try: + output_path.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise NotADirectoryError( + f"Output directory does not exist and could not be created: {output_path.parent}" + ) from e + + if num_results <= 0: + raise ValueError("num_results must be a positive integer.") + if num_core <= 0: + raise ValueError("num_core must be a positive integer.") + if min_cells <= 0: + raise ValueError("min_cells must be a positive integer.") + if min_pairs <= 0: + raise ValueError("min_pairs must be a positive integer.") + + # R script to be executed. It includes package installation for portability. + r_script_content = """ + # run_cardspa.R + options(warn=-1) + suppressPackageStartupMessages({ + if (!requireNamespace("argparser", quietly = TRUE)) { + install.packages("argparser", repos = "http://cran.us.r-project.org", quiet = TRUE) + } + if (!requireNamespace("BiocManager", quietly = TRUE)) { + install.packages("BiocManager", repos = "http://cran.us.r-project.org", quiet = TRUE) + } + if (!requireNamespace("cardspa", quietly = TRUE)) { + BiocManager::install("cardspa", update=FALSE, ask=FALSE, quiet = TRUE) + } + if (!requireNamespace("SingleCellExperiment", quietly = TRUE)) { + BiocManager::install("SingleCellExperiment", update=FALSE, ask=FALSE, quiet = TRUE) + } + library(argparser) + library(cardspa) + library(SingleCellExperiment) + }) + + p <- arg_parser("Run cardspa analysis") + p <- add_argument(p, "--sce_object", help="Path to the input SingleCellExperiment RDS file", type="character") + p <- add_argument(p, "--output_path", help="Path to save the output RDS file", type="character") + p <- add_argument(p, "--phenotype_col", help="Column name for cell types", type="character") + p <- add_argument(p, "--location_col_1", help="First column name for spatial coordinates", default="row", type="character") + p <- add_argument(p, "--location_col_2", help="Second column name for spatial coordinates", default="col", type="character") + p <- add_argument(p, "--method", help="Method for spatial analysis (Giotto, SpaGCN, BayesSpace)", default="Giotto", type="character") + p <- add_argument(p, "--num_results", help="Number of top results to return", default=10, type="integer") + p <- add_argument(p, "--num_core", help="Number of cores for parallel processing", default=1, type="integer") + p <- add_argument(p, "--min_cells", help="Minimum number of cells for a cell type", default=10, type="integer") + p <- add_argument(p, "--min_pairs", help="Minimum number of interacting pairs", default=10, type="integer") + + argv <- parse_args(p) + + if (is.na(argv$sce_object) || is.na(argv$output_path) || is.na(argv$phenotype_col)) { + stop("Missing required arguments: --sce_object, --output_path, or --phenotype_col", call. = FALSE) + } + + cat("Reading input SCE object from:", argv$sce_object, "\\n") + sce <- readRDS(argv$sce_object) + + cat("Running cardspa analysis with method:", argv$method, "\\n") + results <- cardspa( + sce_object = sce, + location_col = c(argv$location_col_1, argv$location_col_2), + phenotype_col = argv$phenotype_col, + method = argv$method, + num_results = argv$num_results, + num_core = argv$num_core, + min_cells = argv$min_cells, + min_pairs = argv$min_pairs + ) + + cat("Saving results to:", argv$output_path, "\\n") + saveRDS(results, file = argv$output_path) + cat("cardspa analysis complete. Results saved to:", argv$output_path, "\\n") + """ + + # --- Subprocess Execution --- + 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) + + cmd = [ + "Rscript", str(r_script_path), + "--sce_object", str(sce_object.resolve()), + "--output_path", str(output_path.resolve()), + "--phenotype_col", phenotype_col, + "--location_col_1", location_col_1, + "--location_col_2", location_col_2, + "--method", method, + "--num_results", str(num_results), + "--num_core", str(num_core), + "--min_cells", str(min_cells), + "--min_pairs", str(min_pairs), + ] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.resolve())] + } + except FileNotFoundError: + raise RuntimeError("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": "cardspa execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + # Ensure temporary script is always removed + if r_script_path.exists(): + r_script_path.unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-cardspa/app/bioconductor-cardspa_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-cardspa/app/bioconductor-cardspa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..25c23e07c509922070c4f2044a858ef525f0713f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cardspa/app/bioconductor-cardspa_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-cardspa/app/bioconductor-cardspa_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_cardspa' + + +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/Biomni/mcp_generated/mcp_bioconductor-cardspa/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cardspa/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cardspa/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-cardspa/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-cardspa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c97f759a1c64d8bf5d0c061ab68e38a779fc9afd --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cardspa/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cardspa: + build: . + image: mcp-bioconductor-cardspa:latest + container_name: mcp-bioconductor-cardspa + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cardspa + 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/Biomni/mcp_generated/mcp_bioconductor-cardspa/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-cardspa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ea224b0da926f170bcd200087a22fdb529c04e4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cardspa/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cardspa + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cardspa/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cardspa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cardspa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-catscradle/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-catscradle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d4d8e2ec0016e59226eb9e474ee2211b6eda3866 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_server.py b/Biomni/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9c4bdfb1741a2a019aa1e13eb3df700381e079 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-catscradle/app/bioconductor-catscradle_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c604bab269e08d1147d431d0970acc6a49f34d81 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-catscradle/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-catscradle/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-catscradle/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-catscradle/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-catscradle/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d730384b0f7f5e35a4f9c96890d4ba2612be1eaa --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-catscradle/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-catscradle/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c46cd1636494f83da0ae619d694ce46850c60680 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-catscradle/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-catscradle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-catscradle/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-cdi/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-cdi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f03c7ddd953af303b50ef962b89004ab4ab409b6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cdi/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-cdi via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cdi -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-cdi_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-cdi_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-cdi_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cdi/app/bioconductor-cdi_server.py b/Biomni/mcp_generated/mcp_bioconductor-cdi/app/bioconductor-cdi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2220998e75b36c2f9e35a79ee90815769f306f8c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cdi/app/bioconductor-cdi_server.py @@ -0,0 +1,363 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Literal, Optional + +# NOTE: The mcp import is commented out as per the instructions, +# but would be required in a real-world MCP environment. +# import mcp + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_cdi' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cdi_calculate( + data: Path, + cl: Path, + ncore: int = 1, + stat: Literal["sum", "ks"] = "sum", + output_filename: str = "cdi_results.json", +) -> Dict: + """ + Calculates the Clustering Deviation Index (CDI) from a count matrix and cluster labels. + + This function takes a gene expression matrix (genes as rows, cells as columns) and a + corresponding file of cell cluster assignments to compute the CDI and an associated p-value. + + Args: + data: Path to the input single-cell expression matrix. + Expected format is a CSV/TSV file where rows are genes and columns are cells. + The first column should contain gene names. + cl: Path to a file containing cell cluster labels. + Expected format is a single-column text file with one cluster label per line, + corresponding to the cells in the data matrix. + ncore: Number of cores to use for parallel processing. + stat: The statistic to evaluate the deviation. Can be 'sum' (default) or 'ks'. + output_filename: The name for the output JSON file containing the results. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output JSON file. + """ + # --- Input Validation --- + if not data.is_file(): + raise FileNotFoundError(f"Input data file not found: {data}") + if not cl.is_file(): + raise FileNotFoundError(f"Input cluster labels file not found: {cl}") + if ncore <= 0: + raise ValueError("ncore must be a positive integer.") + + output_path = Path(output_filename) + + r_script_content = f""" + # Load necessary libraries + library(CDI) + library(jsonlite) + + # --- Read Inputs --- + # Assuming data is CSV with a header and gene names in the first column + data_matrix <- as.matrix(read.csv("{data.resolve()}", row.names=1, header=TRUE, check.names=FALSE)) + + # Assuming cl is a single-column text file without a header + cl_vector <- read.table("{cl.resolve()}", header=FALSE)$V1 + + # --- Run CDI Calculation --- + result <- CDI( + data = data_matrix, + cl = cl_vector, + ncore = {ncore}, + stat = "{stat}" + ) + + # --- Save Results --- + # Convert the list to a JSON object and write to file + write_json(result, "{output_path.resolve()}", auto_unbox = TRUE) + """ + + 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 + + command = ["Rscript", r_script_path] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results_json": str(output_path.resolve())}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CDI execution failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def cdi_calculate_from_seurat( + seurat_object: Path, + ncore: int = 1, + stat: Literal["sum", "ks"] = "sum", + output_filename: str = "cdi_seurat_results.json", +) -> Dict: + """ + Calculates CDI directly from a Seurat object. + + This function uses a pre-processed Seurat object (saved as an .rds file) to compute + the CDI and an associated p-value. It extracts the count data and cluster + identities directly from the object. + + Args: + seurat_object: Path to the input Seurat object, saved in .rds format. + ncore: Number of cores to use for parallel processing. + stat: The statistic to evaluate the deviation. Can be 'sum' (default) or 'ks'. + output_filename: The name for the output JSON file containing the results. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output JSON file. + """ + # --- Input Validation --- + if not seurat_object.is_file(): + raise FileNotFoundError(f"Input Seurat object file not found: {seurat_object}") + if ncore <= 0: + raise ValueError("ncore must be a positive integer.") + + output_path = Path(output_filename) + + r_script_content = f""" + # Load necessary libraries + library(CDI) + library(Seurat) + library(jsonlite) + + # --- Read Input Object --- + seurat_obj <- readRDS("{seurat_object.resolve()}") + + # --- Run CDI Calculation --- + result <- CDI_seurat( + data = seurat_obj, + ncore = {ncore}, + stat = "{stat}" + ) + + # --- Save Results --- + write_json(result, "{output_path.resolve()}", auto_unbox = TRUE) + """ + + 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 + + command = ["Rscript", r_script_path] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results_json": str(output_path.resolve())}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CDI Seurat execution failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def cdi_calculate_from_sce( + sce_object: Path, + ncore: int = 1, + stat: Literal["sum", "ks"] = "sum", + output_filename: str = "cdi_sce_results.json", +) -> Dict: + """ + Calculates CDI directly from a SingleCellExperiment object. + + This function uses a pre-processed SingleCellExperiment object (saved as an .rds file) + to compute the CDI and an associated p-value. + + Args: + sce_object: Path to the input SingleCellExperiment object, saved in .rds format. + ncore: Number of cores to use for parallel processing. + stat: The statistic to evaluate the deviation. Can be 'sum' (default) or 'ks'. + output_filename: The name for the output JSON file containing the results. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output JSON file. + """ + # --- Input Validation --- + if not sce_object.is_file(): + raise FileNotFoundError(f"Input SingleCellExperiment object file not found: {sce_object}") + if ncore <= 0: + raise ValueError("ncore must be a positive integer.") + + output_path = Path(output_filename) + + r_script_content = f""" + # Load necessary libraries + library(CDI) + library(SingleCellExperiment) + library(jsonlite) + + # --- Read Input Object --- + sce_obj <- readRDS("{sce_object.resolve()}") + + # --- Run CDI Calculation --- + result <- CDI_sce( + data = sce_obj, + ncore = {ncore}, + stat = "{stat}" + ) + + # --- Save Results --- + write_json(result, "{output_path.resolve()}", auto_unbox = TRUE) + """ + + 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 + + command = ["Rscript", r_script_path] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results_json": str(output_path.resolve())}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CDI SingleCellExperiment execution failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def cdi_plot( + data: Path, + cl: Path, + ncore: int = 1, + stat: Literal["sum", "ks"] = "sum", + output_plot: str = "cdi_plot.pdf", +) -> Dict: + """ + Generates a ggplot object visualizing the CDI calculation. + + This function produces a plot showing the deviation of gene expression within clusters + compared to the expected distribution, which is the basis for the CDI metric. + + Args: + data: Path to the input single-cell expression matrix (genes as rows, cells as columns). + cl: Path to a file containing cell cluster labels. + ncore: Number of cores to use for parallel processing. + stat: The statistic to evaluate the deviation. Can be 'sum' (default) or 'ks'. + output_plot: The filename for the output plot (e.g., 'cdi_plot.pdf', 'cdi_plot.png'). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output plot file. + """ + # --- Input Validation --- + if not data.is_file(): + raise FileNotFoundError(f"Input data file not found: {data}") + if not cl.is_file(): + raise FileNotFoundError(f"Input cluster labels file not found: {cl}") + if ncore <= 0: + raise ValueError("ncore must be a positive integer.") + + output_path = Path(output_plot) + + r_script_content = f""" + # Load necessary libraries + library(CDI) + library(ggplot2) + + # --- Read Inputs --- + data_matrix <- as.matrix(read.csv("{data.resolve()}", row.names=1, header=TRUE, check.names=FALSE)) + cl_vector <- read.table("{cl.resolve()}", header=FALSE)$V1 + + # --- Generate Plot Object --- + cdi_plot_object <- plot_CDI( + data = data_matrix, + cl = cl_vector, + ncore = {ncore}, + stat = "{stat}" + ) + + # --- Save Plot --- + ggsave("{output_path.resolve()}", plot = cdi_plot_object) + """ + + 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 + + command = ["Rscript", r_script_path] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"plot": str(output_path.resolve())}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CDI plot generation failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-cdi/app/bioconductor-cdi_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-cdi/app/bioconductor-cdi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2e004263cf533fd31125500c164070705dcf136a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cdi/app/bioconductor-cdi_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-cdi/app/bioconductor-cdi_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_cdi' + + +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/Biomni/mcp_generated/mcp_bioconductor-cdi/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cdi/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cdi/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-cdi/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-cdi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f5159743db8d68c1c4d6f5cb619166901051f302 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cdi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cdi: + build: . + image: mcp-bioconductor-cdi:latest + container_name: mcp-bioconductor-cdi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cdi + 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/Biomni/mcp_generated/mcp_bioconductor-cdi/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-cdi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb7ddb0b1e2b0d28305e544ca5c6bd0398dae9b8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cdi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cdi + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cdi/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cdi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cdi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellhashr/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..15b333b3d4fcf707b628791bbe0019901a9b4213 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/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-cellhashr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cellhashr -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-cellhashr_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-cellhashr_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-cellhashr_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_server.py b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d4560228bbc8781e409495d2543b1d08924cc4df --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_server.py @@ -0,0 +1,456 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_cellhashr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def process_count_matrix( + raw_count_data: Path, + output_rds_path: Path, + min_count_per_cell: int = 5, + barcode_whitelist: Optional[List[str]] = None, +): + """ + Parses CITE-seq-Count output and filters cells by total counts. + + This function wraps the cellhashR::ProcessCountMatrix function. It reads a raw + count matrix (typically from CITE-seq-Count), filters out cells with fewer + than min_count_per_cell reads, and saves the resulting data object as an + RDS file for use in downstream cellhashR functions. + + Args: + raw_count_data: Path to the raw count data directory (e.g., 'myCountDir/umi_count'). + output_rds_path: Path to save the output R data object (.rds file). + min_count_per_cell: The minimum total hashing counts for a cell to be retained. + barcode_whitelist: An optional list of HTO barcodes to include. If provided, + all other barcodes will be discarded. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output RDS file. + """ + if not raw_count_data.is_dir(): + raise FileNotFoundError(f"Input directory not found: {raw_count_data}") + if min_count_per_cell < 0: + raise ValueError("min_count_per_cell must be a non-negative integer.") + + r_script_parts = [ + "library(cellhashR)", + f"barcodeData <- ProcessCountMatrix(rawCountData = '{raw_count_data.resolve()}', minCountPerCell = {min_count_per_cell}", + ] + + if barcode_whitelist: + r_vector = 'c(' + ', '.join(f'"{b}"' for b in barcode_whitelist) + ')' + r_script_parts.append(f", barcodeWhitelist = {r_vector}") + + r_script_parts.append(")") + r_script_parts.append(f"saveRDS(barcodeData, file = '{output_rds_path.resolve()}')") + + r_script = "\n".join(r_script_parts) + command = ["Rscript", "-"] + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script) + r_script_file.flush() + + # The command is Rscript + # We use input= to pass the script content via stdin + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +@mcp.tool() +def plot_normalization_qc( + barcode_data_rds: Path, + output_plot_path: Path, +): + """ + Generates QC plots for barcode normalization from a cellhashR data object. + + This function wraps cellhashR::PlotNormalizationQC. It reads an RDS file + generated by process_count_matrix and creates a set of QC plots, saving + them to a specified file (e.g., PDF or PNG). + + Args: + barcode_data_rds: Path to the input RDS file from process_count_matrix. + output_plot_path: Path to save the output plot file (e.g., 'qc_plot.pdf'). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output plot file. + """ + if not barcode_data_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {barcode_data_rds}") + + r_script = f""" + library(cellhashR) + library(ggplot2) + barcodeData <- readRDS('{barcode_data_rds.resolve()}') + p <- PlotNormalizationQC(barcodeData) + ggsave('{output_plot_path.resolve()}', plot = p, width = 10, height = 8) + """ + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_plot_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +@mcp.tool() +def generate_cell_hashing_calls( + barcode_matrix_rds: Path, + output_calls_path: Path, + methods: Optional[List[str]] = None, + raw_feature_matrix_h5: Optional[Path] = None, + methods_for_consensus: Optional[List[str]] = None, + majority_consensus_threshold: Optional[float] = None, + caller_disagreement_threshold: Optional[float] = None, +): + """ + Generates cell hashing calls using one or more demultiplexing algorithms. + + This function wraps cellhashR::GenerateCellHashingCalls. It runs various + demultiplexing methods and produces a unified table with the results of + each caller and a consensus call. + + Args: + barcode_matrix_rds: Path to the input RDS file from process_count_matrix. + output_calls_path: Path to save the output calls as a TSV file. + methods: A list of demultiplexing algorithms to run. Available methods include: + 'bff_raw', 'bff_cluster', 'gmm_demux', 'demuxem', 'demuxmix', + 'multiseq', 'htodemux', 'hasheddrops'. + Defaults to ['bff_cluster', 'htodemux']. + raw_feature_matrix_h5: Path to the 10x h5 gene expression counts file. + Required if using 'demuxem' or 'demuxmix'. + methods_for_consensus: A subset of 'methods' to use for the consensus call. + If None, all methods are used. + majority_consensus_threshold: If not None, a call is made if the fraction of + callers agreeing on the top call exceeds this value. + caller_disagreement_threshold: If provided, any caller with a disagreement rate + above this threshold will be dropped and the + consensus re-calculated. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output calls file. + """ + if not barcode_matrix_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {barcode_matrix_rds}") + + if methods is None: + methods = ['bff_cluster', 'htodemux'] + + demux_methods_req_h5 = {'demuxem', 'demuxmix'} + if any(m in demux_methods_req_h5 for m in methods): + if raw_feature_matrix_h5 is None: + raise ValueError("raw_feature_matrix_h5 is required for 'demuxem' or 'demuxmix' methods.") + if not raw_feature_matrix_h5.is_file(): + raise FileNotFoundError(f"H5 file not found: {raw_feature_matrix_h5}") + + r_methods_vector = 'c(' + ', '.join(f'"{m}"' for m in methods) + ')' + + r_script_parts = [ + "library(cellhashR)", + f"barcodeMatrix <- readRDS('{barcode_matrix_rds.resolve()}')", + f"calls <- GenerateCellHashingCalls(barcodeMatrix = barcodeMatrix, methods = {r_methods_vector}", + ] + + if raw_feature_matrix_h5: + r_script_parts.append(f", rawFeatureMatrixH5 = '{raw_feature_matrix_h5.resolve()}'") + if methods_for_consensus: + r_consensus_vector = 'c(' + ', '.join(f'"{m}"' for m in methods_for_consensus) + ')' + r_script_parts.append(f", methodsForConsensus = {r_consensus_vector}") + if majority_consensus_threshold is not None: + r_script_parts.append(f", majorityConsensusThreshold = {majority_consensus_threshold}") + if caller_disagreement_threshold is not None: + r_script_parts.append(f", callerDisagreementThreshold = {caller_disagreement_threshold}") + + r_script_parts.append(")") + r_script_parts.append(f"write.table(calls, file = '{output_calls_path.resolve()}', sep = '\\t', quote = FALSE, row.names = FALSE)") + + r_script = "\n".join(r_script_parts) + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_calls_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +@mcp.tool() +def summarize_cells_by_classification( + calls_file: Path, + barcode_matrix_rds: Path, + output_summary_path: Path, +): + """ + Generates a text summary of cell classifications. + + This function wraps cellhashR::SummarizeCellsByClassification. It reads the + calls file and the original barcode matrix to produce a summary, which is + saved to a text file. + + Args: + calls_file: Path to the TSV file of cell hashing calls from generate_cell_hashing_calls. + barcode_matrix_rds: Path to the input RDS file from process_count_matrix. + output_summary_path: Path to save the output summary text file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output summary file. + """ + if not calls_file.is_file(): + raise FileNotFoundError(f"Calls file not found: {calls_file}") + if not barcode_matrix_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {barcode_matrix_rds}") + + r_script = f""" + library(cellhashR) + calls <- read.table('{calls_file.resolve()}', header = TRUE, sep = '\\t', check.names = FALSE) + barcodeMatrix <- readRDS('{barcode_matrix_rds.resolve()}') + summary_output <- capture.output(SummarizeCellsByClassification(calls = calls, barcodeMatrix = barcodeMatrix)) + writeLines(summary_output, '{output_summary_path.resolve()}') + """ + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_summary_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +@mcp.tool() +def get_example_markdown( + output_rmd_path: Path, +): + """ + Exports a template RMarkdown file outlining the default cellhashR workflow. + + This function wraps cellhashR::GetExampleMarkdown. The resulting Rmd file can be + run interactively or headlessly as part of a pipeline. + + Args: + output_rmd_path: The destination path for the template RMarkdown file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output Rmd file. + """ + r_script = f""" + library(cellhashR) + GetExampleMarkdown(dest = '{output_rmd_path.resolve()}') + """ + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rmd_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +@mcp.tool() +def call_and_generate_report( + raw_count_data: Path, + report_file: Path, + call_file: Path, + title: Optional[str] = None, + barcode_whitelist: Optional[List[str]] = None, + min_count_per_cell: int = 5, + methods: Optional[List[str]] = None, + raw_feature_matrix_h5: Optional[Path] = None, + methods_for_consensus: Optional[List[str]] = None, + majority_consensus_threshold: Optional[float] = None, + caller_disagreement_threshold: Optional[float] = None, +): + """ + Runs the complete cellhashR workflow and generates an HTML QC report. + + This function is a high-level wrapper around the entire cellhashR pipeline, + producing a TSV of calls and a comprehensive HTML report. It combines the + functionality of several other tools into a single step. + + Args: + raw_count_data: Path to the raw count data directory. + report_file: Path to save the output HTML report. + call_file: Path to save the output calls TSV file. + title: An optional title for the report. + barcode_whitelist: An optional list of HTO barcodes to include. + min_count_per_cell: The minimum total hashing counts for a cell to be retained. + methods: A list of demultiplexing algorithms to run. Defaults to + ['bff_cluster', 'htodemux', 'multiseq']. + raw_feature_matrix_h5: Path to the 10x h5 gene expression counts file. + Required if using 'demuxem' or 'demuxmix'. + methods_for_consensus: A subset of 'methods' to use for the consensus call. + majority_consensus_threshold: Threshold for making a consensus call. + caller_disagreement_threshold: Threshold for dropping a discordant caller. + + Returns: + A dictionary containing the command executed, stdout, stderr, and paths + to the output report and call files. + """ + if not raw_count_data.is_dir(): + raise FileNotFoundError(f"Input directory not found: {raw_count_data}") + if min_count_per_cell < 0: + raise ValueError("min_count_per_cell must be a non-negative integer.") + + if methods is None: + methods = ['bff_cluster', 'htodemux', 'multiseq'] + + demux_methods_req_h5 = {'demuxem', 'demuxmix'} + if any(m in demux_methods_req_h5 for m in methods): + if raw_feature_matrix_h5 is None: + raise ValueError("raw_feature_matrix_h5 is required for 'demuxem' or 'demuxmix' methods.") + if not raw_feature_matrix_h5.is_file(): + raise FileNotFoundError(f"H5 file not found: {raw_feature_matrix_h5}") + + r_script_parts = [ + "library(cellhashR)", + f"CallAndGenerateReport(rawCountData = '{raw_count_data.resolve()}', reportFile = '{report_file.resolve()}', callFile = '{call_file.resolve()}', minCountPerCell = {min_count_per_cell}", + ] + + if title: + r_script_parts.append(f", title = '{title}'") + if barcode_whitelist: + r_vector = 'c(' + ', '.join(f'"{b}"' for b in barcode_whitelist) + ')' + r_script_parts.append(f", barcodeWhitelist = {r_vector}") + if methods: + r_vector = 'c(' + ', '.join(f'"{m}"' for m in methods) + ')' + r_script_parts.append(f", methods = {r_vector}") + if raw_feature_matrix_h5: + r_script_parts.append(f", rawFeatureMatrixH5 = '{raw_feature_matrix_h5.resolve()}'") + if methods_for_consensus: + r_vector = 'c(' + ', '.join(f'"{m}"' for m in methods_for_consensus) + ')' + r_script_parts.append(f", methodsForConsensus = {r_vector}") + if majority_consensus_threshold is not None: + r_script_parts.append(f", majorityConsensusThreshold = {majority_consensus_threshold}") + if caller_disagreement_threshold is not None: + r_script_parts.append(f", callerDisagreementThreshold = {caller_disagreement_threshold}") + + r_script_parts.append(")") + r_script = "\n".join(r_script_parts) + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(report_file.resolve()), str(call_file.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dacb62dce7a50304d68a223d51a3e5f72d1c0012 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_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-cellhashr/app/bioconductor-cellhashr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_cellhashr' + + +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/Biomni/mcp_generated/mcp_bioconductor-cellhashr/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellhashr/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4335d28fb1a12f3432c47924b84445f09056434f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cellhashr: + build: . + image: mcp-bioconductor-cellhashr:latest + container_name: mcp-bioconductor-cellhashr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cellhashr + 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/Biomni/mcp_generated/mcp_bioconductor-cellhashr/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c3f7d013f8e45029b854456545426302952c694 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cellhashr + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellhashr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellhashr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellid/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-cellid/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fe989065a06a14a78840560dd420a1b13cad37f1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellid/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-cellid via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cellid -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-cellid_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-cellid_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-cellid_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellid/app/bioconductor-cellid_server.py b/Biomni/mcp_generated/mcp_bioconductor-cellid/app/bioconductor-cellid_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4b60eb5f3c1bcb0f0ded2531f154eab5d6d066b1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellid/app/bioconductor-cellid_server.py @@ -0,0 +1,288 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +def run_r_command(script_content: str): + """Helper function to execute R code via Rscript""" + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(script_content) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return result.stdout, result.stderr + except subprocess.CalledProcessError as e: + raise RuntimeError(f"R execution failed: {e.stderr}\nStdout: {e.stdout}") + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_cellid' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cellid_run_mca( + input_rds: str, + output_rds: str, + nmcs: int = 50, + assay: str = "RNA", + slot: str = "counts", + features: Optional[List[str]] = None +): + """ + Performs Multiple Correspondence Analysis (MCA) on a SingleCellExperiment or Seurat object. + MCA allows for the simultaneous representation of cells and genes in a common low-dimensional space. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + if nmcs <= 0: + return {"error": "nmcs must be a positive integer."} + + features_r = "NULL" + if features: + features_formatted = ", ".join([f"'{f}'" for f in features]) + features_r = f"c({features_formatted})" + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + + obj <- readRDS("{input_path}") + + # Run MCA + obj <- RunMCA(obj, nmcs = {nmcs}, assay = "{assay}", slot = "{slot}", features = {features_r}) + + saveRDS(obj, "{output_path}") + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "RunMCA", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def cellid_get_cell_gene_set( + input_rds: str, + output_csv: str, + dims: int = 50, + n_features: int = 200 +): + """ + Extracts the top gene signatures for each individual cell based on MCA coordinates. + """ + input_path = Path(input_rds) + output_path = Path(output_csv) + + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + if dims <= 0 or n_features <= 0: + return {"error": "dims and n_features must be positive integers."} + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + library(data.table) + + obj <- readRDS("{input_path}") + + # Extract gene sets per cell + # dims is treated as 1:dims + gene_sets <- GetCellGeneSet(obj, dims = 1:{dims}, n.features = {n_features}) + + # Convert list to a data table for export + # Each column is a cell, rows are top genes + max_len <- max(sapply(gene_sets, length)) + dt <- as.data.frame(lapply(gene_sets, function(x) c(x, rep(NA, max_len - length(x))))) + + write.csv(dt, "{output_path}", row.names = FALSE) + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "GetCellGeneSet", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def cellid_run_cell_hgt( + input_rds: str, + pathways_gmt: str, + output_rds: str, + dims: int = 50, + n_features: int = 200, + min_size: int = 5 +): + """ + Performs cell-type assignment or functional enrichment using a Hypergeometric Test (HGT). + Matches per-cell gene signatures against a reference database (GMT format). + """ + input_path = Path(input_rds) + gmt_path = Path(pathways_gmt) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + if not gmt_path.exists(): + return {"error": f"GMT file {pathways_gmt} not found."} + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + library(fgsea) + + obj <- readRDS("{input_path}") + pathways <- gmtPathways("{gmt_path}") + + # Run Hypergeometric Test + # Returns a matrix of -log10(p-value) + hgt_matrix <- RunCellHGT(obj, pathways = pathways, dims = 1:{dims}, n.features = {n_features}, minSize = {min_size}) + + # If Seurat, we can add it as an assay or metadata + if(inherits(obj, "Seurat")) {{ + obj[["HGT"]] <- CreateAssayObject(counts = hgt_matrix) + }} else {{ + # For SCE, add to altExp + altExp(obj, "HGT") <- SummarizedExperiment(assays = list(counts = hgt_matrix)) + }} + + saveRDS(obj, "{output_path}") + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "RunCellHGT", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def cellid_run_gsea( + input_rds: str, + pathways_gmt: str, + output_rds: str, + dims: int = 50 +): + """ + Performs Gene Set Enrichment Analysis (GSEA) on cells using the MCA gene rankings. + """ + input_path = Path(input_rds) + gmt_path = Path(pathways_gmt) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + if not gmt_path.exists(): + return {"error": f"GMT file {pathways_gmt} not found."} + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + library(fgsea) + + obj <- readRDS("{input_path}") + pathways <- gmtPathways("{gmt_path}") + + # Run GSEA + # This calculates enrichment scores for each cell and each pathway + gsea_res <- RunGSEA(obj, pathways = pathways, dims = 1:{dims}) + + # Save results (usually returns a matrix of NES) + if(inherits(obj, "Seurat")) {{ + obj[["GSEA"]] <- CreateAssayObject(counts = gsea_res) + }} else {{ + altExp(obj, "GSEA") <- SummarizedExperiment(assays = list(counts = gsea_res)) + }} + + saveRDS(obj, "{output_path}") + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "RunGSEA", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def cellid_run_group_mca( + input_rds: str, + group_by: str, + output_rds: str, + nmcs: int = 50, + assay: str = "RNA", + slot: str = "counts" +): + """ + Performs MCA on grouped cells (e.g., by cluster or cell type) rather than individual cells. + Useful for extracting group-specific gene signatures. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + + obj <- readRDS("{input_path}") + + # Run Group MCA + # This aggregates cells by the specified metadata column before MCA + group_mca <- RunGroupMCA(obj, group.by = "{group_by}", nmcs = {nmcs}, assay = "{assay}", slot = "{slot}") + + saveRDS(group_mca, "{output_path}") + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "RunGroupMCA", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellid/app/bioconductor-cellid_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-cellid/app/bioconductor-cellid_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3cab3103b60f82d274eb4ef8e2fdf3f23a988380 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellid/app/bioconductor-cellid_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-cellid/app/bioconductor-cellid_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_cellid' + + +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/Biomni/mcp_generated/mcp_bioconductor-cellid/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-cellid/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1314ea956fa156847970266461a3cfd9e0b3637f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellid/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cellid: + build: . + image: mcp-bioconductor-cellid:latest + container_name: mcp-bioconductor-cellid + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cellid + 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/Biomni/mcp_generated/mcp_bioconductor-cellid/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-cellid/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f08c7d868e99c3a997a959a96e68214878543b56 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellid/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cellid + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellid/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cellid/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellid/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellmigration/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..993aab057245ddc0d90f7ad4bfda9cc195b99040 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/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-cellmigration via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cellmigration -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-cellmigration_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-cellmigration_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-cellmigration_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_server.py b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f6299cfae128b0016f13eb5101b63d108e1a35ae --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_server.py @@ -0,0 +1,214 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# 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(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_cellmigration' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_cellmigration_analysis( + input_file: Path, + output_dir: Path, + delta_t: float = 1.0, + x_microns: float = 1.0, + y_microns: float = 1.0, + plot_format: str = "png", + plot_width: int = 7, + plot_height: int = 7, + plot_dpi: int = 300, + generate_displacement_plot: bool = True, + generate_speed_plot: bool = True, + generate_rose_plot: bool = True, + generate_angle_plot: bool = True, + generate_straighness_plot: bool = True, + generate_persistence_ratio_plot: bool = True, + generate_displacement_ratio_plot: bool = True, + generate_persistence_plot: bool = True, + generate_cumulative_plot: bool = True, + generate_cumulative_hist_plot: bool = True, + generate_single_cell_plot: bool = True, + generate_all_cells_plot: bool = True, +) -> Dict[str, Any]: + """ + Performs a complete cell migration analysis using the Bioconductor cellmigration package. + + This tool reads ImageJ trajectory data, performs a comprehensive analysis, + and generates a variety of plots and a summary statistics CSV file. + It requires R and the 'cellmigration' Bioconductor package to be installed. + + Args: + input_file: Path to the input data file from ImageJ's manual tracking plugin. + output_dir: Path to the directory where output files will be saved. + delta_t: Time interval between frames (dt). + x_microns: Pixel to micron conversion factor for the x-axis (x.scale). + y_microns: Pixel to micron conversion factor for the y-axis (y.scale). + plot_format: The format for the output plots ('png' or 'pdf'). + plot_width: Width of the plots in inches. + plot_height: Height of the plots in inches. + plot_dpi: Resolution for PNG plots in dots per inch. + generate_displacement_plot: Generate a displacement plot. + generate_speed_plot: Generate a speed plot. + generate_rose_plot: Generate a rose plot of cell turning angles. + generate_angle_plot: Generate a plot of cell turning angles. + generate_straighness_plot: Generate a plot of cell trajectory straightness. + generate_persistence_ratio_plot: Generate a persistence ratio plot. + generate_displacement_ratio_plot: Generate a displacement ratio plot. + generate_persistence_plot: Generate a persistence time plot. + generate_cumulative_plot: Generate a cumulative plot. + generate_cumulative_hist_plot: Generate a cumulative plot with a histogram. + generate_single_cell_plot: Generate a plot for each single cell trajectory. + generate_all_cells_plot: Generate a plot showing all cell trajectories. + + 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 delta_t <= 0: + raise ValueError("delta_t must be a positive number.") + if x_microns <= 0 or y_microns <= 0: + raise ValueError("x_microns and y_microns must be positive numbers.") + if plot_format not in ["png", "pdf"]: + raise ValueError("plot_format must be either 'png' or 'pdf'.") + if plot_width <= 0 or plot_height <= 0 or plot_dpi <= 0: + raise ValueError("Plot dimensions and DPI must be positive integers.") + + # --- 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}. Error: {e}") + + # --- R Script Generation --- + # Using absolute paths to avoid issues with working directories + abs_input_file = input_file.resolve() + abs_output_dir = output_dir.resolve() + + # Helper function to generate R plotting code + def get_plot_code(plot_name: str, plot_function: str) -> str: + return f""" + cat("Generating {plot_name} plot...\\n") + if (plot_format == "png") {{ + png(file.path("{abs_output_dir}", "{plot_name}.png"), width=plot_width, height=plot_height, units="in", res=plot_dpi) + }} else {{ + pdf(file.path("{abs_output_dir}", "{plot_name}.pdf"), width=plot_width, height=plot_height) + }} + {plot_function}(analysis_results) + dev.off() + """ + + r_script_content = f""" + # Load the library, with error handling + if (!requireNamespace("cellmigration", quietly = TRUE)) {{ + stop("The 'cellmigration' package is not installed. Please install it from Bioconductor.", call. = FALSE) + }} + library(cellmigration) + + # --- Parameters --- + inputFile <- "{abs_input_file}" + outputDir <- "{abs_output_dir}" + dt <- {delta_t} + x_scale <- {x_microns} + y_scale <- {y_microns} + plot_format <- "{plot_format}" + plot_width <- {plot_width} + plot_height <- {plot_height} + plot_dpi <- {plot_dpi} + + # --- Main Analysis --- + cat("Reading ImageJ data from:", inputFile, "\\n") + ij_data <- read.ijdata(inputFile, dt=dt, x.scale=x_scale, y.scale=y_scale) + + cat("Analyzing trajectories...\\n") + analysis_results <- analyze.trajectories(ij_data) + + cat("Saving analysis summary...\\n") + write.csv(analysis_results$results, file=file.path(outputDir, "analysis_summary.csv"), row.names = FALSE) + + # --- Plotting --- + if ({str(generate_displacement_plot).upper()}) {{{get_plot_code('displacement', 'plot.displacement')}}} + if ({str(generate_speed_plot).upper()}) {{{get_plot_code('speed', 'plot.speed')}}} + if ({str(generate_rose_plot).upper()}) {{{get_plot_code('rose', 'plot.rose')}}} + if ({str(generate_angle_plot).upper()}) {{{get_plot_code('angle', 'plot.angle')}}} + if ({str(generate_straighness_plot).upper()}) {{{get_plot_code('straighness', 'plot.straighness')}}} + if ({str(generate_persistence_ratio_plot).upper()}) {{{get_plot_code('persistence_ratio', 'plot.persistence.ratio')}}} + if ({str(generate_displacement_ratio_plot).upper()}) {{{get_plot_code('displacement_ratio', 'plot.displacement.ratio')}}} + if ({str(generate_persistence_plot).upper()}) {{{get_plot_code('persistence', 'plot.persistence')}}} + if ({str(generate_cumulative_plot).upper()}) {{{get_plot_code('cumulative', 'plot.cummulative.plot')}}} + if ({str(generate_cumulative_hist_plot).upper()}) {{{get_plot_code('cumulative_hist', 'plot.cummulative.plot.and.hist')}}} + if ({str(generate_single_cell_plot).upper()}) {{{get_plot_code('single_cell', 'plot.single.cell')}}} + if ({str(generate_all_cells_plot).upper()}) {{{get_plot_code('all_cells', 'plot.all.cells')}}} + + cat("Analysis complete.\\n") + """ + + # --- Subprocess Execution --- + command = [] + stdout_str, stderr_str = "", "" + output_files = [] + + try: + 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] + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + # Collect output files + output_files = [str(p) for p in abs_output_dir.glob('*')] + + except FileNotFoundError: + stderr_str = "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH." + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [] + } + except subprocess.CalledProcessError as e: + stderr_str = f"Error executing R script. Return code: {e.returncode}\n" + stderr_str += f"STDOUT:\n{e.stdout}\n" + stderr_str += f"STDERR:\n{e.stderr}\n" + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": stderr_str, + "output_files": [] + } + finally: + # Clean up the temporary R script + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + # --- Structured Result Return --- + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..850295237a2ac07b17030e5d9bdb3f52085632fc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_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-cellmigration/app/bioconductor-cellmigration_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_cellmigration' + + +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/Biomni/mcp_generated/mcp_bioconductor-cellmigration/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellmigration/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7f4acd6d9e372f1235703cd470b334ec2d42b41a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cellmigration: + build: . + image: mcp-bioconductor-cellmigration:latest + container_name: mcp-bioconductor-cellmigration + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cellmigration + 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/Biomni/mcp_generated/mcp_bioconductor-cellmigration/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68005d17f772be1b4e208089f2d55879ebadc3d0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cellmigration + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cellmigration/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cellmigration/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c965ca0990e7554e9ff5d7271b78850a73b387f8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/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-clusterfoldsimilarity via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-clusterfoldsimilarity -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-clusterfoldsimilarity_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-clusterfoldsimilarity_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-clusterfoldsimilarity_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_server.py b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3d7dfa75f82835a4db4a2fd7a520c4fbf08eb906 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_server.py @@ -0,0 +1,190 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, Any, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': mcp_tool_placeholder}) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_clusterfoldsimilarity' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cluster_fold_similarity( + fold_changes_file: Path, + sample_col: str, + cluster_col: str, + log_fc_col: str, + gene_col: str, + output_matrix_file: str = "similarity_matrix.csv", + n_top: int = 50, + top_by: str = "p_val_adj", + p_val_adj_cutoff: float = 0.05, + log_fc_cutoff: float = 0.25, + num_cores: Optional[int] = None, +) -> Dict[str, Any]: + """ + Calculates a similarity matrix between single-cell clusters from different samples + based on the fold changes of shared features. + + This tool wraps the `clusterFoldSimilarity` function from the R/Bioconductor package + ClusterFoldSimilarity. It takes a table of pre-computed fold changes as input. + + Args: + fold_changes_file: Path to the input file containing fold change data. + The file should be a tab-separated (TSV) or comma-separated (CSV) + table with a header. + sample_col: Name of the column that identifies the sample or dataset. + cluster_col: Name of the column that identifies the cluster. + log_fc_col: Name of the column with the log2 fold change values. + gene_col: Name of the column with the gene or feature names. + output_matrix_file: Name for the output CSV file containing the similarity matrix. + Defaults to "similarity_matrix.csv". + n_top: Number of top genes (ranked by `top_by` column) to use for the calculation. + Defaults to 50. + top_by: The column to use for ranking top genes. Defaults to "p_val_adj". + p_val_adj_cutoff: Adjusted p-value cutoff for filtering genes. Defaults to 0.05. + log_fc_cutoff: Log2 fold change cutoff for filtering genes. Defaults to 0.25. + num_cores: Number of cores to use for parallel processing. If not provided, + computation will be run serially. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of output file paths. + """ + # --- Input Validation --- + if not fold_changes_file.is_file(): + raise FileNotFoundError(f"Input file not found: {fold_changes_file}") + + if n_top <= 0: + raise ValueError("n_top must be a positive integer.") + + if p_val_adj_cutoff < 0: + raise ValueError("p_val_adj_cutoff must be non-negative.") + + if log_fc_cutoff < 0: + raise ValueError("log_fc_cutoff must be non-negative.") + + if num_cores is not None and num_cores <= 0: + raise ValueError("num_cores must be a positive integer if specified.") + + # --- R Script Generation --- + # Convert Python None to R's NULL for the script + num_cores_r = "NULL" if num_cores is None else str(num_cores) + + r_script_content = f""" + # Load necessary libraries + if (!requireNamespace("ClusterFoldSimilarity", quietly = TRUE)) {{ + stop("Package ClusterFoldSimilarity is not installed.") + }} + if (!requireNamespace("BiocParallel", quietly = TRUE)) {{ + stop("Package BiocParallel is not installed.") + }} + library(ClusterFoldSimilarity) + library(BiocParallel) + + # --- Parameters from Python --- + fold_changes_file <- "{fold_changes_file.resolve()}" + sample_col <- "{sample_col}" + cluster_col <- "{cluster_col}" + log_fc_col <- "{log_fc_col}" + gene_col <- "{gene_col}" + n_top <- {n_top} + top_by <- "{top_by}" + p_val_adj_cutoff <- {p_val_adj_cutoff} + log_fc_cutoff <- {log_fc_cutoff} + num_cores <- {num_cores_r} + output_file <- "{Path(output_matrix_file).resolve()}" + + # --- Main Logic --- + # Set up parallel processing backend + if (!is.null(num_cores) && num_cores > 1) {{ + bpparam <- MulticoreParam(workers = num_cores) + }} else {{ + bpparam <- SerialParam() + }} + + # Read the input data. read.delim is flexible for both CSV and TSV. + # We use tryCatch to handle potential parsing errors. + fold_changes_data <- tryCatch({{ + # First attempt with tab, common for bioinformatics + read.delim(fold_changes_file, sep = "\\t", header = TRUE, stringsAsFactors = FALSE, check.names = FALSE) + }}, error = function(e) {{ + # Fallback to comma if tab fails + read.delim(fold_changes_file, sep = ",", header = TRUE, stringsAsFactors = FALSE, check.names = FALSE) + }}) + + # Run the core function + cat("Calculating cluster fold similarity...\\n") + similarity_matrix <- clusterFoldSimilarity( + scObject = fold_changes_data, + sample_col = sample_col, + cluster_col = cluster_col, + log_FC_col = log_fc_col, + gene_col = gene_col, + n_top = n_top, + top_by = top_by, + p_val_adj_cutoff = p_val_adj_cutoff, + logFC_cutoff = log_fc_cutoff, + BPPARAM = bpparam + ) + + # Save the output matrix to a CSV file + cat(paste("Writing similarity matrix to:", output_file, "\\n")) + write.csv(similarity_matrix, file = output_file, row.names = TRUE, quote = FALSE) + + cat("Analysis complete.\\n") + """ + + # --- Subprocess Execution --- + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # This error occurs if the R script itself fails + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [], + } + finally: + # Clean up the temporary R script file + Path(script_path).unlink() + + output_files: List[str] = [str(Path(output_matrix_file).resolve())] + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c258de8559b9d04cdb3fe0a738700a68c854dedf --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_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-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_clusterfoldsimilarity' + + +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/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b36e4770cf4e0f1bc677e32d925ef1998f2e44fa --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-clusterfoldsimilarity: + build: . + image: mcp-bioconductor-clusterfoldsimilarity:latest + container_name: mcp-bioconductor-clusterfoldsimilarity + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-clusterfoldsimilarity + 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/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4ae34182f783369a158a1f59e460c17c69ec6650 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-clusterfoldsimilarity + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7d41084c084df555cc75c188a61714a0ec681547 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/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-clusterprofiler via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-clusterprofiler -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-clusterprofiler_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-clusterprofiler_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-clusterprofiler_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_server.py b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae885a230f21315ec5a915bed5b4442935fb6a7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_server.py @@ -0,0 +1,504 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Literal + +# Assume mcp is available in the execution environment +# from mcp import tool as mcp_tool +# For standalone execution, we can create a dummy decorator +class mcp: + def tool(func): + return func + +def _run_r_script( + r_script_content: str, + output_prefix: str, + temp_dir: Path, +) -> dict: + """ + Helper function to execute an R script and handle I/O and errors. + + Args: + r_script_content: A string containing the R code to execute. + output_prefix: The prefix for naming output files. + temp_dir: The temporary directory to run the script and store results. + + Returns: + A dictionary containing the results of the execution. + """ + r_script_path = temp_dir / "clusterprofiler_script.R" + r_script_path.write_text(r_script_content) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + cwd=temp_dir, + ) + + output_files = [ + str(p) for p in temp_dir.glob(f"{Path(output_prefix).name}*") + if p.is_file() + ] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: Rscript 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, + "output_files": [], + } + + +@mcp.tool +def enrich_go( + gene_file: Path, + orgdb: str, + output_prefix: str, + keyType: str = "ENTREZID", + ont: Literal["BP", "MF", "CC", "ALL"] = "BP", + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + universe_file: Optional[Path] = None, + min_gs_size: int = 10, + max_gs_size: int = 500, + readable: bool = False, +) -> dict: + """ + Performs Gene Ontology (GO) over-representation analysis using clusterProfiler::enrichGO. + + Args: + gene_file: Path to a file containing a list of gene IDs, one per line. + orgdb: Name of the organism annotation package (e.g., 'org.Hs.eg.db'). + output_prefix: Prefix for the output files (e.g., 'my_analysis_go'). + keyType: The type of gene IDs in the input file (e.g., 'ENTREZID', 'SYMBOL'). + ont: The GO ontology to test ('BP', 'MF', 'CC', or 'ALL'). + pvalue_cutoff: Cutoff for p-value. + qvalue_cutoff: Cutoff for q-value. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background/universe gene IDs. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + readable: If True, maps gene IDs to gene names. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not gene_file.is_file(): + raise FileNotFoundError(f"Input gene file not found: {gene_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if pvalue_cutoff < 0 or pvalue_cutoff > 1: + raise ValueError("pvalue_cutoff must be between 0 and 1.") + if qvalue_cutoff < 0 or qvalue_cutoff > 1: + raise ValueError("qvalue_cutoff must be between 0 and 1.") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + universe_r_code = f'universe = readLines("{universe_file.resolve()}"),' if universe_file else "" + + r_script = f""" + # Ensure required packages are installed + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2", "{orgdb}") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + library({orgdb}, character.only = TRUE) + + genes <- readLines("{gene_file.resolve()}") + + ego <- enrichGO( + gene = genes, + OrgDb = {orgdb}, + keyType = "{keyType}", + ont = "{ont}", + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + {universe_r_code} + qvalueCutoff = {qvalue_cutoff}, + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size}, + readable = {"TRUE" if readable else "FALSE"} + ) + + if (!is.null(ego) && nrow(as.data.frame(ego)) > 0) {{ + write.csv(as.data.frame(ego), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- barplot(ego, showCategory=20) + ggsave("{output_path_prefix}_barplot.png", plot=p1, width=12, height=10) + + p2 <- dotplot(ego, showCategory=20) + ggsave("{output_path_prefix}_dotplot.png", plot=p2, width=12, height=10) + }} else {{ + print("No significant enrichment found.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) + + +@mcp.tool +def enrich_kegg( + gene_file: Path, + organism: str, + output_prefix: str, + keyType: str = "kegg", + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + universe_file: Optional[Path] = None, + min_gs_size: int = 10, + max_gs_size: int = 500, +) -> dict: + """ + Performs KEGG pathway over-representation analysis using clusterProfiler::enrichKEGG. + + Args: + gene_file: Path to a file containing a list of gene IDs, one per line. + organism: KEGG organism code (e.g., 'hsa' for human, 'mmu' for mouse). + output_prefix: Prefix for the output files (e.g., 'my_analysis_kegg'). + keyType: The type of gene IDs, 'kegg' is recommended. + pvalue_cutoff: Cutoff for p-value. + qvalue_cutoff: Cutoff for q-value. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background/universe gene IDs. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not gene_file.is_file(): + raise FileNotFoundError(f"Input gene file not found: {gene_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if pvalue_cutoff < 0 or pvalue_cutoff > 1: + raise ValueError("pvalue_cutoff must be between 0 and 1.") + if qvalue_cutoff < 0 or qvalue_cutoff > 1: + raise ValueError("qvalue_cutoff must be between 0 and 1.") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + universe_r_code = f'universe = readLines("{universe_file.resolve()}"),' if universe_file else "" + + r_script = f""" + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + + genes <- readLines("{gene_file.resolve()}") + + ekegg <- enrichKEGG( + gene = genes, + organism = "{organism}", + keyType = "{keyType}", + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + {universe_r_code} + qvalueCutoff = {qvalue_cutoff}, + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size} + ) + + if (!is.null(ekegg) && nrow(as.data.frame(ekegg)) > 0) {{ + write.csv(as.data.frame(ekegg), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- barplot(ekegg, showCategory=20) + ggsave("{output_path_prefix}_barplot.png", plot=p1, width=12, height=10) + + p2 <- dotplot(ekegg, showCategory=20) + ggsave("{output_path_prefix}_dotplot.png", plot=p2, width=12, height=10) + }} else {{ + print("No significant enrichment found.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) + + +@mcp.tool +def gse_go( + ranked_gene_file: Path, + orgdb: str, + output_prefix: str, + keyType: str = "ENTREZID", + ont: Literal["BP", "MF", "CC", "ALL"] = "BP", + n_perms: int = 1000, + min_gs_size: int = 10, + max_gs_size: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + verbose: bool = True, + seed: bool = False, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on GO terms using clusterProfiler::gseGO. + + Args: + ranked_gene_file: Path to a 2-column CSV file (no header) with gene ID and a numeric ranking metric (e.g., log2FoldChange). + orgdb: Name of the organism annotation package (e.g., 'org.Hs.eg.db'). + output_prefix: Prefix for the output files (e.g., 'my_gsea_go'). + keyType: The type of gene IDs in the input file. + ont: The GO ontology to test ('BP', 'MF', 'CC', or 'ALL'). + n_perms: Number of permutations for GSEA. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + pvalue_cutoff: Cutoff for p-value. + p_adjust_method: Method for p-value adjustment. + verbose: If True, show progress messages. + seed: If True, sets a random seed for reproducibility. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not ranked_gene_file.is_file(): + raise FileNotFoundError(f"Input gene file not found: {ranked_gene_file}") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + r_script = f""" + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2", "DOSE", "{orgdb}") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + library({orgdb}, character.only = TRUE) + + df <- read.csv("{ranked_gene_file.resolve()}", header=FALSE) + geneList <- df[,2] + names(geneList) <- as.character(df[,1]) + geneList <- sort(geneList, decreasing = TRUE) + + gse <- gseGO( + geneList = geneList, + OrgDb = {orgdb}, + ont = "{ont}", + keyType = "{keyType}", + nPerm = {n_perms}, + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"}, + seed = {"TRUE" if seed else "FALSE"} + ) + + if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{ + write.csv(as.data.frame(gse), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- ridgeplot(gse) + ggsave("{output_path_prefix}_ridgeplot.png", plot=p1, width=12, height=10) + + # GSEA plot for top pathways + gseaplot(gse, geneSetID = 1, title = gse$Description[1]) + ggsave("{output_path_prefix}_gseaplot_top1.png", width=10, height=8) + }} else {{ + print("No significant enrichment found.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) + + +@mcp.tool +def gse_kegg( + ranked_gene_file: Path, + organism: str, + output_prefix: str, + keyType: str = "kegg", + n_perms: int = 1000, + min_gs_size: int = 10, + max_gs_size: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + verbose: bool = True, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on KEGG pathways using clusterProfiler::gseKEGG. + + Args: + ranked_gene_file: Path to a 2-column CSV file (no header) with gene ID and a numeric ranking metric. + organism: KEGG organism code (e.g., 'hsa' for human). + output_prefix: Prefix for the output files (e.g., 'my_gsea_kegg'). + keyType: The type of gene IDs in the input file. + n_perms: Number of permutations for GSEA. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + pvalue_cutoff: Cutoff for p-value. + p_adjust_method: Method for p-value adjustment. + verbose: If True, show progress messages. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not ranked_gene_file.is_file(): + raise FileNotFoundError(f"Input gene file not found: {ranked_gene_file}") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + r_script = f""" + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2", "DOSE") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + + df <- read.csv("{ranked_gene_file.resolve()}", header=FALSE) + geneList <- df[,2] + names(geneList) <- as.character(df[,1]) + geneList <- sort(geneList, decreasing = TRUE) + + gsek <- gseKEGG( + geneList = geneList, + organism = "{organism}", + keyType = "{keyType}", + nPerm = {n_perms}, + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"} + ) + + if (!is.null(gsek) && nrow(as.data.frame(gsek)) > 0) {{ + write.csv(as.data.frame(gsek), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- ridgeplot(gsek) + ggsave("{output_path_prefix}_ridgeplot.png", plot=p1, width=12, height=10) + }} else {{ + print("No significant enrichment found.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) + + +@mcp.tool +def compare_clusters_go( + gene_clusters_file: Path, + orgdb: str, + output_prefix: str, + keyType: str = "ENTREZID", + ont: Literal["BP", "MF", "CC"] = "BP", + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + min_gs_size: int = 10, + max_gs_size: int = 500, + readable: bool = False, +) -> dict: + """ + Compares GO enrichment across multiple gene clusters using clusterProfiler::compareCluster. + + Args: + gene_clusters_file: Path to a 2-column CSV file (no header) with cluster name and gene ID. + orgdb: Name of the organism annotation package (e.g., 'org.Hs.eg.db'). + output_prefix: Prefix for the output files. + keyType: The type of gene IDs in the input file. + ont: The GO ontology to test ('BP', 'MF', or 'CC'). + pvalue_cutoff: Cutoff for p-value. + qvalue_cutoff: Cutoff for q-value. + p_adjust_method: Method for p-value adjustment. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + readable: If True, maps gene IDs to gene names. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not gene_clusters_file.is_file(): + raise FileNotFoundError(f"Input gene clusters file not found: {gene_clusters_file}") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + r_script = f""" + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2", "{orgdb}") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + library({orgdb}, character.only = TRUE) + + df <- read.csv("{gene_clusters_file.resolve()}", header=FALSE) + colnames(df) <- c("cluster", "gene") + + # Convert dataframe to the named list format required by compareCluster + gene_clusters <- split(df$gene, df$cluster) + + comp_result <- compareCluster( + geneClusters = gene_clusters, + fun = "enrichGO", + OrgDb = {orgdb}, + keyType = "{keyType}", + ont = "{ont}", + pvalueCutoff = {pvalue_cutoff}, + qvalueCutoff = {qvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size}, + readable = {"TRUE" if readable else "FALSE"} + ) + + if (!is.null(comp_result) && nrow(as.data.frame(comp_result)) > 0) {{ + write.csv(as.data.frame(comp_result), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- dotplot(comp_result, showCategory=15) + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + ggsave("{output_path_prefix}_dotplot.png", plot=p1, width=14, height=12) + }} else {{ + print("No significant enrichment found across clusters.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..381143f76b3f056ac767affbde2959d1cbf7f4dc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_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-clusterprofiler/app/bioconductor-clusterprofiler_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_clusterprofiler' + + +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/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..39aa3d40e374e62eb9e1d8a6d78f7d881fd28827 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-clusterprofiler: + build: . + image: mcp-bioconductor-clusterprofiler:latest + container_name: mcp-bioconductor-clusterprofiler + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-clusterprofiler + 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/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..716938ee6f00676545d461f0de082e3386ecb6a1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-clusterprofiler + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clusterprofiler/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-clustifyr/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-clustifyr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..52ec0d803f99f7a08118a664f84fa502c5ecfe8e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py b/Biomni/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..479e8abb69c6c5096a5ae81bf9bd02ea73ae4f78 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9a8dc5da9264cbcef08a93d1d7a705cca6df9336 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-clustifyr/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-clustifyr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..815f8ab58e324137dfb25d93e4ee371b34fc90af --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-clustifyr/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-clustifyr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..34e35a6e37b07334f789ad2eaa09c886ac0f1f7e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-clustifyr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-clustifyr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clustifyr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-clustsignal/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6fae5fb2e1686893a0b9d9f0ed3b4cd9fc2d59ae --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/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-clustsignal via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-clustsignal -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-clustsignal_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-clustsignal_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-clustsignal_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_server.py b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5a83586b8ede24dd968539c8b1961cbc9d41f817 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_server.py @@ -0,0 +1,419 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, Any, List, Union + +# This is a placeholder for the actual MCP decorator. +# In a real MCP environment, this would be `from mcp import tool`. +class mcp: + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +# R script templates +R_SCRIPT_HEADER = """ +# Install packages if not already present +if (!requireNamespace("optparse", quietly = TRUE)) install.packages("optparse", repos="http://cran.us.r-project.org") +if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos="http://cran.us.r-project.org") +if (!requireNamespace("clustsig", quietly = TRUE)) BiocManager::install("clustsig", update=FALSE, ask=FALSE) + +library(optparse) +library(clustsig) +""" + +R_SCRIPT_SIG_CLUST = R_SCRIPT_HEADER + """ +# Define command-line options +option_list <- list( + make_option(c("-i", "--input"), type="character", default=NULL, help="Input data matrix file (CSV/TSV, rows=samples, cols=features)"), + make_option(c("-o", "--out_prefix"), type="character", default="clustsig_results", help="Output file prefix"), + make_option(c("-k", "--num_clusters"), type="integer", default=NULL, help="Number of clusters (k)"), + make_option(c("--nsim"), type="integer", default=1000, help="Number of simulations"), + make_option(c("--nrep"), type="integer", default=1, help="Number of replicates for each simulation"), + make_option(c("--labflag"), type="integer", default=0, help="Flag for data with known labels (0 or 1)"), + make_option(c("--label_file"), type="character", default=NULL, help="File with integer labels for columns (required if labflag=1)"), + make_option(c("--icovest"), type="integer", default=1, help="Covariance matrix estimation method (1, 2, or 3)"), + make_option(c("--input_sep"), type="character", default="\\t", help="Input file separator ('\\t' or ',')"), + make_option(c("--input_header"), type="logical", default=TRUE, help="Does the input file have a header?") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +# Validate required arguments +if (is.null(opt$input) || is.null(opt$num_clusters)) { + print_help(opt_parser) + stop("Input data matrix file and number of clusters must be supplied.", call.=FALSE) +} + +# Read input data +x <- as.matrix(read.table(opt$input, header=opt$input_header, sep=opt$input_sep, row.names=1, check.names=FALSE)) + +# Handle labels +label_data <- 0 +if (opt$labflag == 1) { + if (is.null(opt$label_file)) stop("Label file must be provided when labflag is 1.", call.=FALSE) + label_data <- as.integer(read.table(opt$label_file, header=FALSE)[,1]) + if (length(label_data) != ncol(x)) stop("Number of labels must match the number of columns in the data matrix.", call.=FALSE) +} + +# Run sig.clust +set.seed(123) # for reproducibility +results <- sig.clust(x=x, k=opt$num_clusters, nsim=opt$nsim, nrep=opt$nrep, labflag=opt$labflag, label=label_data, icovest=opt$icovest) + +# Save results +p_value_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_p_value.txt")) +ci_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_cluster_indices.txt")) +ci_sim_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_sim_cluster_indices.csv")) +eigval_orig_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_orig_eigenvalues.txt")) +eigval_sim_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_sim_eigenvalues.csv")) + +write.table(results$p.value, file=p_value_file, col.names=FALSE, row.names=FALSE) +write.table(results$ci, file=ci_file, col.names=FALSE, row.names=FALSE) +write.csv(results$ci.sim, file=ci_sim_file, row.names=FALSE) +write.table(results$eigval.orig, file=eigval_orig_file, col.names=FALSE, row.names=FALSE) +write.csv(results$eigval.sim, file=eigval_sim_file, row.names=FALSE) + +cat("All results saved.\\n") +""" + +R_SCRIPT_RECLUSTER = R_SCRIPT_HEADER + """ +option_list <- list( + make_option(c("-i", "--input"), type="character", default=NULL, help="Input data matrix file"), + make_option(c("-o", "--out_prefix"), type="character", default="recluster_results", help="Output file prefix"), + make_option(c("-k", "--num_clusters"), type="integer", default=NULL, help="Number of clusters (k)"), + make_option(c("--mat"), type="character", default="pearson", help="Distance matrix method"), + make_option(c("--method"), type="character", default="average", help="Clustering method"), + make_option(c("--input_sep"), type="character", default="\\t", help="Input file separator ('\\t' or ',')"), + make_option(c("--input_header"), type="logical", default=TRUE, help="Does the input file have a header?") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$input) || is.null(opt$num_clusters)) { + print_help(opt_parser) + stop("Input file and number of clusters must be supplied.", call.=FALSE) +} + +x <- as.matrix(read.table(opt$input, header=opt$input_header, sep=opt$input_sep, row.names=1, check.names=FALSE)) +results <- recluster(x=x, k=opt$num_clusters, mat=opt$mat, method=opt$method) + +ci_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_cluster_indices.txt")) +sh_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_silhouette_width.txt")) + +write.table(results$ci, file=ci_file, col.names=FALSE, row.names=FALSE) +write.table(results$sh, file=sh_file, col.names=FALSE, row.names=FALSE) + +cat("Results saved.\\n") +""" + +R_SCRIPT_SIM_SIG = R_SCRIPT_HEADER + """ +option_list <- list( + make_option(c("-o", "--out_prefix"), type="character", default="sim_sig_data", help="Output file prefix"), + make_option(c("-n", "--num_samples"), type="integer", default=NULL, help="Number of samples (rows)"), + make_option(c("-p", "--num_features"), type="integer", default=NULL, help="Number of features (columns)"), + make_option(c("--p_sig"), type="integer", default=NULL, help="Number of significant features"), + make_option(c("--s_val"), type="double", default=1.0, help="Signal value"), + make_option(c("--v_sig"), type="double", default=1.0, help="Variance of significant features"), + make_option(c("--lab"), type="integer", default=0, help="Flag to return labels (0 or 1)") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$num_samples) || is.null(opt$num_features) || is.null(opt$p_sig)) { + print_help(opt_parser) + stop("Number of samples, features, and significant features must be supplied.", call.=FALSE) +} + +set.seed(123) +results <- sim.sig(n=opt$num_samples, p=opt$num_features, p.sig=opt$p_sig, s.val=opt$s_val, v.sig=opt$v_sig, lab=opt$lab) + +matrix_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_matrix.csv")) + +if (opt$lab == 1) { + label_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_labels.txt")) + write.csv(results$x, file=matrix_file, row.names=FALSE) + write.table(results$label, file=label_file, col.names=FALSE, row.names=FALSE) +} else { + write.csv(results, file=matrix_file, row.names=FALSE) +} + +cat("Simulated data saved.\\n") +""" + +R_SCRIPT_SIM_NULL = R_SCRIPT_HEADER + """ +option_list <- list( + make_option(c("-o", "--out_prefix"), type="character", default="sim_null_data", help="Output file prefix"), + make_option(c("-n", "--num_samples"), type="integer", default=NULL, help="Number of samples (rows)"), + make_option(c("-p", "--num_features"), type="integer", default=NULL, help="Number of features (columns)"), + make_option(c("--lab"), type="integer", default=0, help="Flag to return labels (0 or 1)") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$num_samples) || is.null(opt$num_features)) { + print_help(opt_parser) + stop("Number of samples and features must be supplied.", call.=FALSE) +} + +set.seed(123) +results <- sim.null(n=opt$num_samples, p=opt$num_features, lab=opt$lab) + +matrix_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_matrix.csv")) + +if (opt$lab == 1) { + label_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_labels.txt")) + write.csv(results$x, file=matrix_file, row.names=FALSE) + write.table(results$label, file=label_file, col.names=FALSE, row.names=FALSE) +} else { + write.csv(results, file=matrix_file, row.names=FALSE) +} + +cat("Simulated data saved.\\n") +""" + +def _run_r_script( + script_content: str, + args: List[str], + output_dir: Path, +) -> Dict[str, Union[str, List[str]]]: + """Helper function to run an R script in a temporary directory.""" + script_path = output_dir / "script.R" + with open(script_path, "w") as f: + f.write(script_content) + + cmd = ["Rscript", str(script_path)] + args + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + cwd=output_dir, + ) + + output_files = [str(p) for p in output_dir.glob("*") if p.is_file() and p.name != "script.R"] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_clustsignal' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def sig_clust( + input_matrix: Path, + num_clusters: int, + output_prefix: str, + nsim: int = 1000, + nrep: int = 1, + labflag: int = 0, + label_file: Optional[Path] = None, + icovest: int = 1, + input_separator: str = "tab", + input_header: bool = True, +) -> Dict[str, Any]: + """ + Performs Significant Cluster Analysis using the clustsig R package. + + This tool assesses the statistical significance of clustering results on a dataset. + It compares the within-cluster sum of squares of the data to that of simulated null data. + """ + # Input validation + if not input_matrix.is_file(): + raise FileNotFoundError(f"Input file not found: {input_matrix}") + if num_clusters <= 0: + raise ValueError("Number of clusters must be a positive integer.") + if nsim <= 0: + raise ValueError("Number of simulations (nsim) must be a positive integer.") + if nrep <= 0: + raise ValueError("Number of replicates (nrep) must be a positive integer.") + if labflag not in [0, 1]: + raise ValueError("labflag must be 0 or 1.") + if labflag == 1: + if label_file is None: + raise ValueError("label_file is required when labflag is 1.") + if not label_file.is_file(): + raise FileNotFoundError(f"Label file not found: {label_file}") + if icovest not in [1, 2, 3]: + raise ValueError("icovest must be 1, 2, or 3.") + if input_separator not in ["tab", "comma"]: + raise ValueError("input_separator must be 'tab' or 'comma'.") + + sep_map = {"tab": "\\t", "comma": ","} + + with tempfile.TemporaryDirectory() as tempdir: + workdir = Path(tempdir) + + args = [ + "--input", str(input_matrix.resolve()), + "--out_prefix", str(workdir / output_prefix), + "--num_clusters", str(num_clusters), + "--nsim", str(nsim), + "--nrep", str(nrep), + "--labflag", str(labflag), + "--icovest", str(icovest), + "--input_sep", sep_map[input_separator], + ] + if input_header: + args.append("--input_header") + if label_file: + args.extend(["--label_file", str(label_file.resolve())]) + + result = _run_r_script(R_SCRIPT_SIG_CLUST, args, workdir) + + return result + + +@mcp.tool() +def recluster( + input_matrix: Path, + num_clusters: int, + output_prefix: str, + mat: str = "pearson", + method: str = "average", + input_separator: str = "tab", + input_header: bool = True, +) -> Dict[str, Any]: + """ + Performs hierarchical clustering and calculates cluster indices and silhouette widths. + + This is a utility function from the clustsig package for performing clustering. + """ + # Input validation + if not input_matrix.is_file(): + raise FileNotFoundError(f"Input file not found: {input_matrix}") + if num_clusters <= 0: + raise ValueError("Number of clusters must be a positive integer.") + + valid_mats = ["pearson", "spearman", "kendall", "euclidean"] + if mat not in valid_mats: + raise ValueError(f"Invalid distance matrix method '{mat}'. Must be one of {valid_mats}.") + + valid_methods = ["average", "ward", "single", "complete", "mcquitty", "median", "centroid"] + if method not in valid_methods: + raise ValueError(f"Invalid clustering method '{method}'. Must be one of {valid_methods}.") + + if input_separator not in ["tab", "comma"]: + raise ValueError("input_separator must be 'tab' or 'comma'.") + + sep_map = {"tab": "\\t", "comma": ","} + + with tempfile.TemporaryDirectory() as tempdir: + workdir = Path(tempdir) + + args = [ + "--input", str(input_matrix.resolve()), + "--out_prefix", str(workdir / output_prefix), + "--num_clusters", str(num_clusters), + "--mat", mat, + "--method", method, + "--input_sep", sep_map[input_separator], + ] + if input_header: + args.append("--input_header") + + result = _run_r_script(R_SCRIPT_RECLUSTER, args, workdir) + + return result + + +@mcp.tool() +def sim_sig( + num_samples: int, + num_features: int, + p_sig: int, + output_prefix: str, + s_val: float = 1.0, + v_sig: float = 1.0, + lab: int = 0, +) -> Dict[str, Any]: + """ + Generates simulated data from a multivariate normal distribution with a signal. + + This function is useful for creating test datasets with a known cluster structure. + """ + # Input validation + if num_samples <= 0: + raise ValueError("Number of samples must be a positive integer.") + if num_features <= 0: + raise ValueError("Number of features must be a positive integer.") + if not (0 < p_sig <= num_features): + raise ValueError("Number of significant features (p_sig) must be positive and not exceed num_features.") + if lab not in [0, 1]: + raise ValueError("lab must be 0 or 1.") + + with tempfile.TemporaryDirectory() as tempdir: + workdir = Path(tempdir) + + args = [ + "--out_prefix", str(workdir / output_prefix), + "--num_samples", str(num_samples), + "--num_features", str(num_features), + "--p_sig", str(p_sig), + "--s_val", str(s_val), + "--v_sig", str(v_sig), + "--lab", str(lab), + ] + + result = _run_r_script(R_SCRIPT_SIM_SIG, args, workdir) + + return result + + +@mcp.tool() +def sim_null( + num_samples: int, + num_features: int, + output_prefix: str, + lab: int = 0, +) -> Dict[str, Any]: + """ + Generates simulated data from a multivariate normal distribution with no signal (null). + + This function is useful for creating null datasets for comparison or testing. + """ + # Input validation + if num_samples <= 0: + raise ValueError("Number of samples must be a positive integer.") + if num_features <= 0: + raise ValueError("Number of features must be a positive integer.") + if lab not in [0, 1]: + raise ValueError("lab must be 0 or 1.") + + with tempfile.TemporaryDirectory() as tempdir: + workdir = Path(tempdir) + + args = [ + "--out_prefix", str(workdir / output_prefix), + "--num_samples", str(num_samples), + "--num_features", str(num_features), + "--lab", str(lab), + ] + + result = _run_r_script(R_SCRIPT_SIM_NULL, args, workdir) + + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f06c54b2fbfa060179ae405fd7126ef84a60618c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_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-clustsignal/app/bioconductor-clustsignal_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_clustsignal' + + +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/Biomni/mcp_generated/mcp_bioconductor-clustsignal/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-clustsignal/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dcf3656fcb1e73c28f2f9f64498f92d8c965e8ef --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-clustsignal: + build: . + image: mcp-bioconductor-clustsignal:latest + container_name: mcp-bioconductor-clustsignal + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-clustsignal + 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/Biomni/mcp_generated/mcp_bioconductor-clustsignal/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..895bc594dd965d7a7f30b72fff8b40038ccbd010 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-clustsignal + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-clustsignal/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-clustsignal/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1e1a9b49fc7ea6267c7df02b1ad96b7d47557d59 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_server.py b/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fad979cb135327d992c814fe538f72b0983845a2 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..778d5a23914d720e0da9da3a661fa7d11abddf48 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..abf545b662467e8085f4cce746121deafc82b593 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0081bc8f415129604bd28e7791cccea6de50469e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-complexheatmap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-concordexr/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-concordexr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1c6ea7c8b91b141d18da6d241b21b2fe2e0440a8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-concordexr/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-concordexr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-concordexr -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-concordexr_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-concordexr_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-concordexr_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-concordexr/app/bioconductor-concordexr_server.py b/Biomni/mcp_generated/mcp_bioconductor-concordexr/app/bioconductor-concordexr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b553e9f10a96a65b53696eea39809bdc611b61 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-concordexr/app/bioconductor-concordexr_server.py @@ -0,0 +1,221 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# Mock the decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def compute_concordex( + data_file: Path, + ranks_file: Path, + indices_file: Path, + output_dir: Path, + data_type: str = "counts", + abundance_min: float = 1.0, + abundance_max: Optional[float] = None, + sample_min: float = 0.0, + sample_max: Optional[float] = None, + filter_perc: float = 0.0, + filter_count: int = 0, + plot: bool = True, + plot_format: str = "png", + plot_width: int = 10, + plot_height: int = 10, + export: bool = True, + export_rds: bool = True, +): + """ + Computes the Concordance Index (Concordex) using the concordexR package. + + This tool wraps the `computeConcordex` function. It takes expression/count data, + pre-computed ranks, and sample indices to calculate concordex scores. It can + filter data, generate plots, and export results to files. + + Args: + data_file: Path to the input data file (e.g., counts matrix). Assumed to be a tab-separated file with a header and row names in the first column. + ranks_file: Path to the ranks file. Assumed to be a tab-separated file with a header and row names in the first column. + indices_file: Path to the indices file. Assumed to be a single-column, tab-separated file without a header. + output_dir: Path to the directory where output files will be saved. + data_type: The type of data in `data_file`. Must be either 'counts' or 'ranks'. + abundance_min: The minimum abundance of a feature to be included in the analysis. + abundance_max: The maximum abundance of a feature. If None, no upper limit is applied. + sample_min: The minimum value of a sample to be included. + sample_max: The maximum value of a sample. If None, no upper limit is applied. + filter_perc: The percentage of samples a feature must be present in to be retained. Value must be between 0.0 and 1.0. + filter_count: The minimum number of counts a feature must have across all samples to be retained. + plot: If True, generate concordex plots. + plot_format: The format for the output plots (e.g., 'png', 'pdf', 'svg'). + plot_width: The width of the output plots in inches. + plot_height: The height of the output plots in inches. + export: If True, export the concordex results to text files. + export_rds: If True, save the final concordex R object to an .rds file for later use (e.g., with plot_concordex). + """ + # Input validation + if not data_file.is_file(): + raise FileNotFoundError(f"Input data file not found: {data_file}") + if not ranks_file.is_file(): + raise FileNotFoundError(f"Ranks file not found: {ranks_file}") + if not indices_file.is_file(): + raise FileNotFoundError(f"Indices file not found: {indices_file}") + + if data_type not in ["counts", "ranks"]: + raise ValueError("data_type must be either 'counts' or 'ranks'.") + if not (0.0 <= filter_perc <= 1.0): + raise ValueError("filter_perc must be between 0.0 and 1.0.") + if filter_count < 0: + raise ValueError("filter_count must be a non-negative integer.") + if plot_format not in ["png", "pdf", "svg", "jpeg", "tiff"]: + raise ValueError(f"Unsupported plot format: {plot_format}") + + output_dir.mkdir(parents=True, exist_ok=True) + + # Build the R script + r_script_lines = [ + "library(concordexR)", + f'data <- read.table("{data_file.resolve()}", header=TRUE, sep="\\t", row.names=1, check.names=FALSE)', + f'ranks <- read.table("{ranks_file.resolve()}", header=TRUE, sep="\\t", row.names=1, check.names=FALSE)', + f'indices_df <- read.table("{indices_file.resolve()}", header=FALSE, sep="\\t")', + "indices <- as.list(indices_df$V1)", + "concordex_result <- computeConcordex(", + " data = data,", + " ranks = ranks,", + " indices = indices,", + f' type = "{data_type}",', + f" abundance.min = {abundance_min},", + f" abundance.max = {abundance_max if abundance_max is not None else 'Inf'},", + f" sample.min = {sample_min},", + f" sample.max = {sample_max if sample_max is not None else 'Inf'},", + f" filter.perc = {filter_perc},", + f" filter.count = {filter_count},", + f' output.dir = "{output_dir.resolve()}",', + f" plot = {'TRUE' if plot else 'FALSE'},", + f' plot.format = "{plot_format}",', + f" plot.width = {plot_width},", + f" plot.height = {plot_height},", + f" export = {'TRUE' if export else 'FALSE'}", + ")", + ] + + if export_rds: + rds_path = output_dir.resolve() / "concordex_object.rds" + r_script_lines.append(f'saveRDS(concordex_result, file = "{rds_path}")') + + r_script = "\n".join(r_script_lines) + + # Use a temporary file for the R script + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as f: + f.write(r_script) + r_script_path = Path(f.name) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [str(p) for p in output_dir.glob("**/*") if p.is_file()] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + r_script_path.unlink() + +@mcp.tool +def plot_concordex( + concordex_object_file: Path, + output_dir: Path, + plot_format: str = "png", + plot_width: int = 10, + plot_height: int = 10, +): + """ + Generates plots from a pre-computed concordex object. + + This tool wraps the `plotConcordex` function from the concordexR package. + It takes an .rds file containing a concordex object (generated by the + compute_concordex tool) and creates visualization plots. + + Args: + concordex_object_file: Path to the .rds file containing the concordex object. + output_dir: Path to the directory where output plots will be saved. + plot_format: The format for the output plots (e.g., 'png', 'pdf', 'svg'). + plot_width: The width of the output plots in inches. + plot_height: The height of the output plots in inches. + """ + # Input validation + if not concordex_object_file.is_file(): + raise FileNotFoundError(f"Concordex object file not found: {concordex_object_file}") + if concordex_object_file.suffix != ".rds": + raise ValueError("concordex_object_file must be an .rds file.") + if plot_format not in ["png", "pdf", "svg", "jpeg", "tiff"]: + raise ValueError(f"Unsupported plot format: {plot_format}") + + output_dir.mkdir(parents=True, exist_ok=True) + + # Build the R script + r_script_lines = [ + "library(concordexR)", + f'concordex_obj <- readRDS("{concordex_object_file.resolve()}")', + "plotConcordex(", + " concordex.object = concordex_obj,", + f' output.dir = "{output_dir.resolve()}",', + f' plot.format = "{plot_format}",', + f" plot.width = {plot_width},", + f" plot.height = {plot_height}", + ")", + ] + r_script = "\n".join(r_script_lines) + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as f: + f.write(r_script) + r_script_path = Path(f.name) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [str(p) for p in output_dir.glob("**/*") if p.is_file()] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + r_script_path.unlink() \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-concordexr/app/bioconductor-concordexr_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-concordexr/app/bioconductor-concordexr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d68dabbb207ab4015ac24f47c2204beb0386be77 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-concordexr/app/bioconductor-concordexr_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-concordexr/app/bioconductor-concordexr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_concordexr' + + +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/Biomni/mcp_generated/mcp_bioconductor-concordexr/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-concordexr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-concordexr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-concordexr/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-concordexr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8b5291f8e0b390b106dfec8b76ba69c2afb93482 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-concordexr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-concordexr: + build: . + image: mcp-bioconductor-concordexr:latest + container_name: mcp-bioconductor-concordexr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-concordexr + 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/Biomni/mcp_generated/mcp_bioconductor-concordexr/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-concordexr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb7159d75e2835693c1a0bd67e14b3e286680365 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-concordexr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-concordexr + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-concordexr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-concordexr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-concordexr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-cotan/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-cotan/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b14e58239c11775ee3f73d0f681b3b3ddf905b8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cotan/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-cotan via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cotan -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-cotan_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-cotan_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-cotan_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cotan/app/bioconductor-cotan_server.py b/Biomni/mcp_generated/mcp_bioconductor-cotan/app/bioconductor-cotan_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fff61195e76d7223b6423248202059f92ff91d47 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cotan/app/bioconductor-cotan_server.py @@ -0,0 +1,208 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import List, Optional, Dict, Any + +# 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): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +@mcp.tool +def run_cotan_analysis( + raw_count_matrix: Path, + output_dir: Path, + min_reads_per_cell: int = 1000, + min_cells_per_gene: int = 3, + num_cores: int = 1, + run_gdi: bool = True, + run_clustering: bool = True, + num_clusters: int = 10, + save_cotan_object: bool = True, +) -> Dict[str, Any]: + """ + Performs a complete COTAN analysis for single-cell gene co-expression. + + This tool takes a raw UMI count matrix and runs the standard COTAN workflow, + which includes data cleaning, dispersion estimation, co-expression calculation, + Global Differentiation Index (GDI) analysis, and hierarchical clustering of genes. + + Args: + raw_count_matrix: Path to the input raw count matrix file (CSV format). + Rows should represent genes and columns represent cells. + The first column should contain gene names. + output_dir: Path to the directory where output files will be saved. + min_reads_per_cell: Minimum number of reads for a cell to be kept during cleaning. + min_cells_per_gene: Minimum number of cells where a gene must be expressed to be kept. + num_cores: Number of CPU cores to use for parallelizable steps. + run_gdi: If True, calculates the Global Differentiation Index (GDI) for all genes. + run_clustering: If True, performs hierarchical clustering on the gene co-expression matrix. + num_clusters: The number of clusters to create if `run_clustering` is True. + save_cotan_object: If True, saves the final COTAN R object as an RDS file for further analysis. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output file paths. + """ + # --- Input Validation --- + if not raw_count_matrix.is_file(): + raise FileNotFoundError(f"Input file not found: {raw_count_matrix}") + if min_reads_per_cell <= 0: + raise ValueError("min_reads_per_cell must be a positive integer.") + if min_cells_per_gene <= 0: + raise ValueError("min_cells_per_gene must be a positive integer.") + if num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if run_clustering and num_clusters <= 1: + raise ValueError("num_clusters must be greater than 1 for clustering.") + + # --- 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}") + + output_files = [] + + # --- R Script Generation --- + # Note: R booleans are TRUE/FALSE + r_script_content = textwrap.dedent(f""" + # Load necessary libraries + library(COTAN) + library(Matrix) + + print("Starting COTAN analysis workflow...") + + # --- Parameters --- + raw_count_matrix_path <- "{raw_count_matrix.resolve()}" + output_dir_path <- "{output_dir.resolve()}" + min_reads <- {min_reads_per_cell} + min_cells <- {min_cells_per_gene} + num_cores <- {num_cores} + run_gdi_calc <- {"TRUE" if run_gdi else "FALSE"} + run_clust <- {"TRUE" if run_clustering else "FALSE"} + k_clusters <- {num_clusters} + save_obj <- {"TRUE" if save_cotan_object else "FALSE"} + + # --- Data Loading --- + print(paste("Loading raw count matrix from:", raw_count_matrix_path)) + # Using data.table for fast reading, assuming it's installed as a dependency + # or falling back to read.csv + if (requireNamespace("data.table", quietly = TRUE)) {{ + raw_data <- data.table::fread(raw_count_matrix_path, data.table = FALSE) + rownames(raw_data) <- raw_data[,1] + raw_data[,1] <- NULL + }} else {{ + raw_data <- read.csv(raw_count_matrix_path, header = TRUE, row.names = 1, check.names = FALSE) + }} + raw_data <- as.matrix(raw_data) + print("Data loaded successfully.") + + # --- COTAN Object Creation and Cleaning --- + obj <- COTAN(raw = raw_data) + print("COTAN object created.") + + obj <- clean(obj, min.reads = min_reads, min.cells = min_cells, calcExtraData = FALSE) + print("Data cleaning complete.") + + # --- Core Analysis --- + print("Estimating dispersion...") + obj <- estimateDispersion(obj, cores = num_cores) + + print("Calculating co-expression matrix...") + obj <- calculateCoex(obj, cores = num_cores) + + coex_df <- as.data.frame(as.matrix(getCoex(obj))) + coex_path <- file.path(output_dir_path, "coex_matrix.csv") + write.csv(coex_df, file = coex_path) + print(paste("Co-expression matrix saved to:", coex_path)) + + # --- GDI Calculation --- + if (run_gdi_calc) {{ + print("Calculating Global Differentiation Index (GDI)...") + obj <- calculateGDI(obj) + gdi_df <- getGDI(obj) + gdi_path <- file.path(output_dir_path, "gdi_table.csv") + write.csv(gdi_df, file = gdi_path) + print(paste("GDI table saved to:", gdi_path)) + }} + + # --- Clustering --- + if (run_clust) {{ + print("Performing hierarchical clustering on genes...") + coex_dist <- as.dist(1 - getCoex(obj)) + hc <- hclust(coex_dist, method = "ward.D2") + clusters <- cutree(hc, k = k_clusters) + clusters_df <- data.frame(gene = names(clusters), cluster = clusters) + clusters_path <- file.path(output_dir_path, "gene_clusters.csv") + write.csv(clusters_df, file = clusters_path, row.names = FALSE) + print(paste("Gene clusters saved to:", clusters_path)) + }} + + # --- Save Final Object --- + if (save_obj) {{ + rds_path <- file.path(output_dir_path, "cotan_object.rds") + saveRDS(obj, file = rds_path) + print(paste("COTAN object saved to:", rds_path)) + }} + + print("COTAN analysis completed successfully.") + """) + + # --- Subprocess Execution --- + with tempfile.TemporaryDirectory() as temp_dir: + script_path = Path(temp_dir) / "run_cotan.R" + with open(script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(script_path)] + command_str = " ".join(command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + + # --- Collect Output Files --- + output_files.append(str(output_dir / "coex_matrix.csv")) + if run_gdi: + output_files.append(str(output_dir / "gdi_table.csv")) + if run_clustering: + output_files.append(str(output_dir / "gene_clusters.csv")) + if save_cotan_object: + output_files.append(str(output_dir / "cotan_object.rds")) + + # Verify that files were actually created + output_files = [p for p in output_files if Path(p).exists()] + + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + # --- Structured Result Return --- + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cotan/app/bioconductor-cotan_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-cotan/app/bioconductor-cotan_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..73d244e9ac7f27238f42be38d3ad2f360603e32e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cotan/app/bioconductor-cotan_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-cotan/app/bioconductor-cotan_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_cotan' + + +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/Biomni/mcp_generated/mcp_bioconductor-cotan/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-cotan/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e40f8dacf3543248285cbdb9e68bac1fd70bcf77 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cotan/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cotan: + build: . + image: mcp-bioconductor-cotan:latest + container_name: mcp-bioconductor-cotan + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cotan + 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/Biomni/mcp_generated/mcp_bioconductor-cotan/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-cotan/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..618896ac7d6d52c72c4937dca331e04fd907f73d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cotan/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cotan + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cotan/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cotan/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cotan/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-csoa/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-csoa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3c2e24f3b644ec3185df397f30d71a8ab7bd41ff --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-csoa/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-csoa via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-csoa -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-csoa_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-csoa_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-csoa_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-csoa/app/bioconductor-csoa_server.py b/Biomni/mcp_generated/mcp_bioconductor-csoa/app/bioconductor-csoa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..043835d369c56c9a7a39694761365d742eebbae9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-csoa/app/bioconductor-csoa_server.py @@ -0,0 +1,226 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the actual MCP decorator. +# The code is written to be compatible with the MCP framework. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def csoa_analysis( + expression_file: Path, + genesets_file: Path, + groups_file: Path, + output_prefix: str, + min_size: int = 5, + max_size: Optional[int] = None, + nperm: int = 1000, + p_value_cutoff: float = 0.05, + p_adj_method: str = "BH", + verbose: bool = True, + selected_gs: Optional[str] = None, +): + """ + Performs Clustered Subtype Ontological Analysis (CSOA) using the Bioconductor 'csoa' package. + + This tool takes an expression matrix, gene sets, and sample group information to identify + gene sets that are significantly enriched in different sample subtypes. It generates an + HTML report and saves the full analysis results as an RDS object. + + Args: + expression_file: Path to the expression data file (TSV format, with genes in rows + and samples in columns. The first column should be gene identifiers). + genesets_file: Path to the gene sets file in GMT format. + groups_file: Path to the sample groups file (TSV format with a header, containing two + columns: SampleID and Group). + output_prefix: Prefix for the output files (e.g., 'my_analysis'). This will generate + 'my_analysis_report.html' and 'my_analysis_results.rds'. + min_size: Minimum size of a gene set to be considered for analysis. + max_size: Maximum size of a gene set to be considered. If not provided, no upper + limit is imposed. + nperm: Number of permutations to perform for significance testing. + p_value_cutoff: P-value cutoff for determining significance. + p_adj_method: Method for multiple testing correction. Must be one of 'holm', 'hochberg', + 'hommel', 'bonferroni', 'BH', 'BY', 'fdr', 'none'. + verbose: If True, enables verbose output during the analysis. + selected_gs: A comma-separated string of specific gene set names to analyze. If not + provided, all gene sets in the GMT file are used. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of + generated output files. + """ + # --- Input Validation --- + if not expression_file.is_file(): + raise FileNotFoundError(f"Expression file not found: {expression_file}") + if not genesets_file.is_file(): + raise FileNotFoundError(f"Gene sets file not found: {genesets_file}") + if not groups_file.is_file(): + raise FileNotFoundError(f"Groups file not found: {groups_file}") + + if min_size <= 0: + raise ValueError("min_size must be a positive integer.") + if max_size is not None and max_size < min_size: + raise ValueError("max_size cannot be smaller than min_size.") + if nperm <= 0: + raise ValueError("nperm (number of permutations) must be a positive integer.") + if not (0.0 < p_value_cutoff <= 1.0): + raise ValueError("p_value_cutoff must be between 0 and 1.") + + allowed_adj_methods = ['holm', 'hochberg', 'hommel', 'bonferroni', 'BH', 'BY', 'fdr', 'none'] + if p_adj_method not in allowed_adj_methods: + raise ValueError(f"p_adj_method must be one of {allowed_adj_methods}, but got '{p_adj_method}'.") + + if not output_prefix: + raise ValueError("output_prefix cannot be empty.") + + # --- R Script for Execution --- + # This self-contained R script acts as a command-line wrapper for the csoa library functions. + r_script_content = """ + # Autogenerated R script to run CSOA analysis + suppressPackageStartupMessages(library(argparse)) + suppressPackageStartupMessages(library(csoa)) + suppressPackageStartupMessages(library(Biobase)) + suppressPackageStartupMessages(library(GSEABase)) + + parser <- ArgumentParser(description="Run Clustered Subtype Ontological Analysis (CSOA)") + parser$add_argument("--expression", type="character", required=TRUE, help="Path to the expression data file.") + parser$add_argument("--genesets", type="character", required=TRUE, help="Path to the gene sets file (GMT format).") + parser$add_argument("--groups", type="character", required=TRUE, help="Path to the sample groups file.") + parser$add_argument("--output_prefix", type="character", required=TRUE, help="Prefix for output files.") + parser$add_argument("--min_size", type="integer", default=5, help="Minimum size of a gene set.") + parser$add_argument("--max_size", type="integer", default=NULL, help="Maximum size of a gene set.") + parser$add_argument("--nperm", type="integer", default=1000, help="Number of permutations.") + parser$add_argument("--p_value_cutoff", type="double", default=0.05, help="P-value cutoff.") + parser$add_argument("--p_adj_method", type="character", default="BH", help="P-value adjustment method.") + parser$add_argument("--selected_gs", type="character", default=NULL, help="Comma-separated list of selected gene sets.") + parser$add_argument("--verbose", action="store_true", default=FALSE, help="Enable verbose output.") + args <- parser$parse_args() + + tryCatch({ + if (args$verbose) cat("Loading expression data from:", args$expression, "\\n") + expr_data <- read.delim(args$expression, row.names=1, check.names=FALSE, sep="\\t") + expr_matrix <- as.matrix(expr_data) + + if (args$verbose) cat("Loading sample groups from:", args$groups, "\\n") + groups_data <- read.delim(args$groups, header=TRUE, stringsAsFactors=FALSE, sep="\\t") + + if (ncol(groups_data) < 2) { + stop("Groups file must have at least two columns: SampleID and Group.") + } + + sample_order <- match(colnames(expr_matrix), groups_data[,1]) + if (any(is.na(sample_order))) { + missing_samples <- colnames(expr_matrix)[is.na(sample_order)] + stop(paste("Sample names in groups file do not match all sample names in expression file. Missing:", paste(missing_samples, collapse=", "))) + } + groups_ordered <- groups_data[sample_order, ] + groups_vector <- as.factor(groups_ordered[,2]) + names(groups_vector) <- groups_ordered[,1] + + eset <- ExpressionSet(assayData=expr_matrix) + pData(eset)$groups <- groups_vector + + if (args$verbose) cat("Loading gene sets from:", args$genesets, "\\n") + gsets <- getGmt(args$genesets) + + selected_gs_vector <- NULL + if (!is.null(args$selected_gs)) { + selected_gs_vector <- trimws(strsplit(args$selected_gs, ",")[[1]]) + } + + max_size_val <- if (is.null(args$max_size)) Inf else args$max_size + + if (args$verbose) cat("Running CSOA analysis...\\n") + csoa_res <- csoa( + eset = eset, gsets = gsets, groups = "groups", + min.size = args$min_size, max.size = max_size_val, + nperm = args$nperm, selected.gs = selected_gs_vector, + p.value.cutoff = args$p_value_cutoff, p.adj.method = args$p_adj_method, + verbose = args$verbose + ) + if (args$verbose) cat("CSOA analysis complete.\\n") + + report_file <- paste0(args$output_prefix, "_report.html") + if (args$verbose) cat("Generating HTML report to:", report_file, "\\n") + csoa_report(csoa_res, file=report_file) + + rds_file <- paste0(args$output_prefix, "_results.rds") + if (args$verbose) cat("Saving CSOA results object to:", rds_file, "\\n") + saveRDS(csoa_res, file=rds_file) + + cat("Workflow finished successfully.\\n") + }, error = function(e) { + message("An error occurred during CSOA execution:") + message(conditionMessage(e)) + quit(status=1) + }) + """ + + # --- Command Construction and Execution --- + r_script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_path = Path(r_script_file.name) + r_script_file.write(r_script_content) + + cmd = [ + "Rscript", str(r_script_path), + "--expression", str(expression_file.resolve()), + "--genesets", str(genesets_file.resolve()), + "--groups", str(groups_file.resolve()), + "--output_prefix", output_prefix, + "--min_size", str(min_size), + "--nperm", str(nperm), + "--p_value_cutoff", str(p_value_cutoff), + "--p_adj_method", p_adj_method, + ] + + if max_size is not None: + cmd.extend(["--max_size", str(max_size)]) + if selected_gs: + cmd.extend(["--selected_gs", selected_gs]) + if verbose: + cmd.append("--verbose") + + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + # --- Collect Output --- + output_files: List[str] = [] + report_path = Path(f"{output_prefix}_report.html") + rds_path = Path(f"{output_prefix}_results.rds") + + if report_path.is_file(): + output_files.append(str(report_path)) + if rds_path.is_file(): + output_files.append(str(rds_path)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd) if 'cmd' in locals() else "Command construction failed", + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"CSOA execution failed with return code {e.returncode}", + "output_files": [] + } + finally: + # Clean up the temporary R script + if r_script_path and r_script_path.exists(): + r_script_path.unlink() \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-csoa/app/bioconductor-csoa_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-csoa/app/bioconductor-csoa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d630bea5b5e84a5ae47e538b7dc87905bee1e11d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-csoa/app/bioconductor-csoa_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-csoa/app/bioconductor-csoa_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_csoa' + + +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/Biomni/mcp_generated/mcp_bioconductor-csoa/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-csoa/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-csoa/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-csoa/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-csoa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c4eb958baf0cf83bd29d20caf2f3a04b56dc068e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-csoa/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-csoa: + build: . + image: mcp-bioconductor-csoa:latest + container_name: mcp-bioconductor-csoa + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-csoa + 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/Biomni/mcp_generated/mcp_bioconductor-csoa/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-csoa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fdc168854e55c9573fcb5dab265bfba7f0768b48 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-csoa/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-csoa + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-csoa/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-csoa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-csoa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-ctsv/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-ctsv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eb724cc9838a8a6772f972aac6a8cd14be1ef854 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_server.py b/Biomni/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f4b440d72cb0087b2ed07a266c8b0aa454678f5 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-ctsv/app/bioconductor-ctsv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d70d357d3a8631b2eecaee6288607cc627bfbdce --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-ctsv/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ctsv/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ctsv/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-ctsv/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-ctsv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9ff81c86eee540a7c6bf6a8d1be45b64e058c6b9 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-ctsv/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-ctsv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6db1e33d080c74872941d56c7234ca6d659a2fdc --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-ctsv/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ctsv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ctsv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..02ebac92236f7770576c155e661a1d5f225a564f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/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-curatedatlasqueryr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-curatedatlasqueryr -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-curatedatlasqueryr_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-curatedatlasqueryr_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-curatedatlasqueryr_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..38554dd04ca8cb9e9e6cd28a7c0f8a57f28538e4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py @@ -0,0 +1,256 @@ +import subprocess +import os +import json +from pathlib import Path +from typing import Optional, List, Union + +def _run_r_command(r_code: str) -> dict: + """Helper to execute R code and handle errors.""" + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "stdout": result.stdout, + "stderr": result.stderr, + "success": True + } + except subprocess.CalledProcessError as e: + return { + "stdout": e.stdout, + "stderr": e.stderr, + "success": False, + "error": str(e) + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_curatedatlasqueryr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def get_metadata( + output_csv: str, + force_update: bool = False +) -> dict: + """ + Retrieves the full metadata table from curatedAtlasQueryR and saves it as a CSV file. + + Args: + output_csv: Path where the metadata CSV will be saved. + force_update: If True, forces a re-download of the metadata from the remote source. + """ + output_path = Path(output_csv).resolve() + force_r = "TRUE" if force_update else "FALSE" + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + meta <- get_metadata(force = {force_r}) + write.csv(as.data.frame(meta), file = '{str(output_path)}', row.names = FALSE) + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"curatedAtlasQueryR::get_metadata(force={force_r})", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [], + "status": "success" if res["success"] else "failed" + } + +@mcp.tool() +def list_metadata_fields() -> dict: + """ + Lists all available columns/fields in the curatedAtlasQueryR metadata. + """ + r_code = """ + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + meta <- get_metadata() + cat(paste(colnames(meta), collapse = "\n")) + """ + + res = _run_r_command(r_code) + + if res["success"]: + fields = res["stdout"].strip().split("\n") + return { + "command_executed": "colnames(get_metadata())", + "available_fields": fields, + "stdout": res["stdout"] + } + else: + return { + "error": "Failed to list fields", + "stderr": res["stderr"] + } + +@mcp.tool() +def search_metadata( + query: str, + output_csv: str, + fields: Optional[List[str]] = None +) -> dict: + """ + Searches the curatedAtlasQueryR metadata for specific terms across all or specified fields. + + Args: + query: The search term or regex pattern to look for. + output_csv: Path to save the filtered metadata results. + fields: Optional list of specific metadata columns to search within. + """ + output_path = Path(output_csv).resolve() + + # Handle fields list for R without backslashes in f-string + if fields: + fields_list_str = ", ".join([f"'{f}'" for f in fields]) + fields_r = f"c({fields_list_str})" + else: + fields_r = "NULL" + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + meta <- get_metadata() + search_cols <- {fields_r} + if (is.null(search_cols)) search_cols <- colnames(meta) + + # Filter rows where any of the selected columns match the query + matches <- apply(meta[, search_cols, drop = FALSE], 1, function(row) {{ + any(grepl("{query}", as.character(row), ignore.case = TRUE)) + }}) + + search_res <- meta[matches, ] + write.csv(as.data.frame(search_res), file = '{str(output_path)}', row.names = FALSE) + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"Searching metadata for '{query}' in fields {fields_r}", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +@mcp.tool() +def query_metadata_custom( + r_filter_expression: str, + output_csv: str +) -> dict: + """ + Performs a custom R-style filter on the metadata table using dplyr syntax. + + Args: + r_filter_expression: An R logical expression string (e.g., "tissue == 'liver' & disease == 'normal'"). + output_csv: Path to save the filtered metadata. + """ + output_path = Path(output_csv).resolve() + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + suppressPackageStartupMessages(library(dplyr)) + meta <- get_metadata() + filtered_meta <- meta %>% filter({r_filter_expression}) + write.csv(as.data.frame(filtered_meta), file = '{str(output_path)}', row.names = FALSE) + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"Metadata filter: {r_filter_expression}", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +@mcp.tool() +def get_atlas_data( + sample_ids: List[str], + output_rds: str +) -> dict: + """ + Downloads single-cell data (SingleCellExperiment) for specified sample IDs. + + Args: + sample_ids: A list of sample_id strings to download. + output_rds: Path to save the resulting SingleCellExperiment object (.rds). + """ + output_path = Path(output_rds).resolve() + + if not sample_ids: + return {"error": "No sample_ids provided."} + + ids_list_str = ", ".join([f"'{i}'" for i in sample_ids]) + ids_r = f"c({ids_list_str})" + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + + meta <- get_metadata() + selected_meta <- meta[meta$sample_id %in% {ids_r}, ] + + if(nrow(selected_meta) == 0) stop("No matching sample IDs found in metadata.") + + sce <- get_data(selected_meta) + saveRDS(sce, file = '{str(output_path)}') + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"curatedAtlasQueryR::get_data() for {len(sample_ids)} samples", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +@mcp.tool() +def get_gene_expression( + sample_ids: List[str], + genes: List[str], + output_rds: str +) -> dict: + """ + Retrieves gene expression data for specific genes across specified samples. + + Args: + sample_ids: A list of sample_id strings. + genes: A list of gene symbols or IDs to retrieve. + output_rds: Path to save the resulting SummarizedExperiment object (.rds). + """ + output_path = Path(output_rds).resolve() + + if not sample_ids or not genes: + return {"error": "Both sample_ids and genes must be provided."} + + ids_list_str = ", ".join([f"'{i}'" for i in sample_ids]) + genes_list_str = ", ".join([f"'{g}'" for g in genes]) + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + suppressPackageStartupMessages(library(SummarizedExperiment)) + + meta <- get_metadata() + selected_meta <- meta[meta$sample_id %in% c({ids_list_str}), ] + + if(nrow(selected_meta) == 0) stop("No matching sample IDs found in metadata.") + + se <- get_gene_expression(selected_meta, genes = c({genes_list_str})) + saveRDS(se, file = '{str(output_path)}') + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"curatedAtlasQueryR::get_gene_expression() for {len(genes)} genes", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..11cb48dd3d4dd548a72cc2f55597b9ae6a634f2f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_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-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_curatedatlasqueryr' + + +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/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..61ced17959568e3d32fc631fcbb885443248c4d9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-curatedatlasqueryr: + build: . + image: mcp-bioconductor-curatedatlasqueryr:latest + container_name: mcp-bioconductor-curatedatlasqueryr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-curatedatlasqueryr + 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/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4ebc5295ee989236a3cdfaf8847d8072211ef33 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-curatedatlasqueryr + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-curatedatlasqueryr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-cytomapper/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..05ba47cceccdf90f283645882e3e1a77140c29c5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/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-cytomapper via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cytomapper -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-cytomapper_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-cytomapper_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-cytomapper_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_server.py b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ccd61921f7edd25d225ec81a770135b44a0215a1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_server.py @@ -0,0 +1,132 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# The mcp.tool decorator is a placeholder for the actual implementation in the MCP framework. +# In a real MCP environment, this would be: from mcp import tool +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_cytomapper' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cytomapper_rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + 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 the Rscript command-line interface. + + This tool is a wrapper for Rscript, designed to run R scripts that utilize + Bioconductor packages like 'cytomapper'. Since 'cytomapper' is an R library + without a direct command-line executable, this tool provides the necessary + interface to run user-provided scripts that implement 'cytomapper' workflows. + + 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 instead of script_file. + args: A list of additional arguments to be passed to the R script. + verbose: If True, print information on progress (--verbose). + default_packages: Comma-separated list of package names to be loaded by default. + save: If True, save the workspace at the end of the session (--save). + no_environ: If True, do not read the site and user environment files (--no-environ). + no_site_file: If True, do not read the site-wide Rprofile (--no-site-file). + no_init_file: If True, do not read the user R profile (--no-init-file). + restore: If True, restore previously saved objects at startup (--restore). + 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; the R script is responsible for + managing its own outputs. + """ + # Input validation + if not script_file and not expressions: + raise ValueError("You must provide either 'script_file' or 'expressions'.") + if script_file and expressions: + raise ValueError("You cannot provide both 'script_file' and 'expressions'.") + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist or is not a file: {script_file}") + + command = ["Rscript"] + + # Add Rscript options + 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 execution target (script file or expressions) + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + elif script_file: + command.append(str(script_file)) + + # Add arguments for the R script itself + if args: + command.extend(args) + + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("The 'Rscript' command was not found. Please ensure R is installed and accessible in the system's PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error response + return { + "command_executed": command_str, + "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/Biomni/mcp_generated/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..00c7a130dbbde35e8e95be143e6aae61265f651d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_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-cytomapper/app/bioconductor-cytomapper_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_cytomapper' + + +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/Biomni/mcp_generated/mcp_bioconductor-cytomapper/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..907b3f17199b82cd6261476c9a0b08d00c4e8fd7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cytomapper: + build: . + image: mcp-bioconductor-cytomapper:latest + container_name: mcp-bioconductor-cytomapper + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cytomapper + 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/Biomni/mcp_generated/mcp_bioconductor-cytomapper/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd7bd84c1e8982b4e751012c9542ffeeb64c7e31 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cytomapper + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-cytomapper/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-cytomapper/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-dada2/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-dada2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c72b1a621246143f17e51744c1fe5c08dd7d79a6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dada2/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-dada2 via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dada2 -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-dada2_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-dada2_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-dada2_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dada2/app/bioconductor-dada2_server.py b/Biomni/mcp_generated/mcp_bioconductor-dada2/app/bioconductor-dada2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7bf44e6bb382010830fa4940c97edc55f9f6a927 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dada2/app/bioconductor-dada2_server.py @@ -0,0 +1,762 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import List, Optional, Union + +# Helper function to run R scripts +def _run_r_script(r_script_content: str, output_dir: Path) -> dict: + """ + Executes an R script using Rscript. + """ + # Ensure the output directory exists for temporary files + output_dir.mkdir(parents=True, exist_ok=True) + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R", dir=output_dir) 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)] + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [], # This will be populated by individual tool functions + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command) if 'command' in locals() else "Rscript execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command) if 'command' in locals() else "Rscript execution failed", + "stdout": "", + "stderr": "Rscript command not found. Please ensure R is installed and in your PATH.", + "error": "Rscript not found", + "output_files": [], + } + except Exception as e: + return { + "command_executed": " ".join(command) if 'command' in locals() else "Rscript execution failed", + "stdout": "", + "stderr": str(e), + "error": f"An unexpected error occurred: {e}", + "output_files": [], + } + finally: + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_dada2' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def filter_and_trim( + fwd_reads: List[Path], + output_dir: Path, + rev_reads: Optional[List[Path]] = None, + trunc_len_f: Optional[int] = None, + trunc_len_r: Optional[int] = None, + trim_left_f: int = 0, + trim_left_r: int = 0, + max_n: int = 0, + max_ee_f: float = 2.0, + max_ee_r: float = 2.0, + trunc_q: int = 2, + rm_phix: bool = True, + compress: bool = True, + multithread: Union[bool, int] = False, + verbose: bool = False, +) -> dict: + """ + Performs quality filtering and trimming of raw sequencing reads using dada2's filterAndTrim. + + Args: + fwd_reads: A list of paths to forward FASTQ files. + output_dir: Directory to save filtered FASTQ files. + rev_reads: An optional list of paths to reverse FASTQ files (for paired-end data). + Must be the same length as fwd_reads if provided. + trunc_len_f: Truncate forward reads after this many bases. Reads shorter than this are discarded. + trunc_len_r: Truncate reverse reads after this many bases. Reads shorter than this are discarded. + trim_left_f: Number of nucleotides to remove from the start of each forward read. + trim_left_r: Number of nucleotides to remove from the start of each reverse read. + max_n: After truncation, reads with more than max_n N's will be discarded. + max_ee_f: Forward reads with an expected error rate higher than max_ee_f will be discarded. + max_ee_r: Reverse reads with an expected error rate higher than max_ee_r will be discarded. + trunc_q: Truncate reads at the first instance of a quality score less than or equal to trunc_q. + rm_phix: If TRUE, phiX reads are removed. + compress: If TRUE, the output files are gzipped. + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and paths to output files. + """ + # Input validation + if not fwd_reads: + raise ValueError("fwd_reads cannot be empty.") + for f_read in fwd_reads: + if not f_read.is_file(): + raise FileNotFoundError(f"Forward read file not found: {f_read}") + if rev_reads: + if len(fwd_reads) != len(rev_reads): + raise ValueError("Number of forward and reverse read files must be the same.") + for r_read in rev_reads: + if not r_read.is_file(): + raise FileNotFoundError(f"Reverse read file not found: {r_read}") + if not output_dir.is_dir(): + output_dir.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "fwd_reads <- c(" + ", ".join([f'"{str(p)}"' for p in fwd_reads]) + ")", + "output_dir <- '" + str(output_dir) + "'", + "filt_fwd_paths <- file.path(output_dir, paste0(basename(fwd_reads), '.filtered.fastq.gz'))", + ] + + filter_params = [] + + # Handle paired-end specific parameters (truncLen, trimLeft, maxEE) + if rev_reads: + r_script_lines.append("rev_reads <- c(" + ", ".join([f'"{str(p)}"' for p in rev_reads]) + ")") + r_script_lines.append("filt_rev_paths <- file.path(output_dir, paste0(basename(rev_reads), '.filtered.fastq.gz'))") + + trunc_len_arg_f = "NA" if trunc_len_f is None else str(trunc_len_f) + trunc_len_arg_r = "NA" if trunc_len_r is None else str(trunc_len_r) + if trunc_len_f is not None or trunc_len_r is not None: + filter_params.append(f"truncLen=c({trunc_len_arg_f}, {trunc_len_arg_r})") + + if trim_left_f != 0 or trim_left_r != 0: + filter_params.append(f"trimLeft=c({trim_left_f}, {trim_left_r})") + + if max_ee_f != 2.0 or max_ee_r != 2.0: + filter_params.append(f"maxEE=c({max_ee_f}, {max_ee_r})") + else: # Single-end + if trunc_len_f is not None: + filter_params.append(f"truncLen={trunc_len_f}") + if trim_left_f != 0: + filter_params.append(f"trimLeft={trim_left_f}") + if max_ee_f != 2.0: + filter_params.append(f"maxEE={max_ee_f}") + + # Handle common parameters + if max_n != 0: + filter_params.append(f"maxN={max_n}") + if trunc_q != 2: + filter_params.append(f"truncQ={trunc_q}") + if not rm_phix: + filter_params.append("rm.phix=FALSE") + if not compress: + filter_params.append("compress=FALSE") + if multithread: + if isinstance(multithread, bool): + filter_params.append("multithread=TRUE") + else: + filter_params.append(f"multithread={multithread}") + if verbose: + filter_params.append("verbose=TRUE") + + if rev_reads: + r_script_lines.append( + f"out <- filterAndTrim(fwd_reads, filt_fwd_paths, rev_reads, filt_rev_paths, {', '.join(filter_params)})" + ) + output_files = [output_dir / Path(f_read.name + ".filtered.fastq.gz") for f_read in fwd_reads] + \ + [output_dir / Path(r_read.name + ".filtered.fastq.gz") for r_read in rev_reads] + else: + r_script_lines.append( + f"out <- filterAndTrim(fwd_reads, filt_fwd_paths, {', '.join(filter_params)})" + ) + output_files = [output_dir / Path(f_read.name + ".filtered.fastq.gz") for f_read in fwd_reads] + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_dir) + result["output_files"] = [str(p) for p in output_files] + return result + +@mcp.tool() +def learn_errors( + filtered_reads: List[Path], + output_error_file: Path, + nbases: int = 100000000, + randomize: bool = True, + multithread: Union[bool, int] = False, + verbose: bool = False, +) -> dict: + """ + Learns the error rates from a subset of filtered reads using dada2's learnErrors. + + Args: + filtered_reads: A list of paths to filtered FASTQ files. + output_error_file: Path to save the learned error model (RDS file). + nbases: The minimum number of bases to use for error rate learning. + randomize: If TRUE, the order of samples is randomized before learning errors. + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output error model file. + """ + # Input validation + if not filtered_reads: + raise ValueError("filtered_reads cannot be empty.") + for f_read in filtered_reads: + if not f_read.is_file(): + raise FileNotFoundError(f"Filtered read file not found: {f_read}") + if output_error_file.suffix != ".rds": + raise ValueError("output_error_file must have a .rds extension.") + if nbases <= 0: + raise ValueError("nbases must be a positive integer.") + output_error_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "filtered_reads <- c(" + ", ".join([f'"{str(p)}"' for p in filtered_reads]) + ")", + "err_file <- '" + str(output_error_file) + "'", + ] + + learn_params = [ + f"nbases={nbases}", + f"randomize={str(randomize).upper()}", + ] + if multithread: + if isinstance(multithread, bool): + learn_params.append("multithread=TRUE") + else: + learn_params.append(f"multithread={multithread}") + if verbose: + learn_params.append("verbose=TRUE") + + r_script_lines.append( + f"err <- learnErrors(filtered_reads, {', '.join(learn_params)})" + ) + r_script_lines.append(f"saveRDS(err, file=err_file)") + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_error_file.parent) + result["output_files"] = [str(output_error_file)] + return result + +@mcp.tool() +def dada_denoise( + filtered_reads: List[Path], + error_model_file: Path, + output_dada_file: Path, + pool: Union[bool, str] = False, # Can be TRUE, FALSE, or "pseudo" + multithread: Union[bool, int] = False, + verbose: bool = False, +) -> dict: + """ + Applies the DADA2 denoising algorithm to filtered reads using a learned error model. + + Args: + filtered_reads: A list of paths to filtered FASTQ files. + error_model_file: Path to the learned error model (RDS file) from learn_errors. + output_dada_file: Path to save the denoised sequence object (RDS file). + pool: If TRUE, all samples are pooled together for denoising. If "pseudo", pseudo-pooling is used. + If FALSE, samples are denoised independently. + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output denoised object file. + """ + # Input validation + if not filtered_reads: + raise ValueError("filtered_reads cannot be empty.") + for f_read in filtered_reads: + if not f_read.is_file(): + raise FileNotFoundError(f"Filtered read file not found: {f_read}") + if not error_model_file.is_file(): + raise FileNotFoundError(f"Error model file not found: {error_model_file}") + if error_model_file.suffix != ".rds": + raise ValueError("error_model_file must have a .rds extension.") + if output_dada_file.suffix != ".rds": + raise ValueError("output_dada_file must have a .rds extension.") + if isinstance(pool, str) and pool not in ["pseudo"]: + raise ValueError(f"Invalid string value for 'pool': {pool}. Must be 'pseudo'.") + output_dada_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "filtered_reads <- c(" + ", ".join([f'"{str(p)}"' for p in filtered_reads]) + ")", + "err <- readRDS('" + str(error_model_file) + "')", + "dada_file <- '" + str(output_dada_file) + "'", + ] + + dada_params = [ + "err=err", + ] + if isinstance(pool, bool): + dada_params.append(f"pool={str(pool).upper()}") + elif pool == "pseudo": + dada_params.append('pool="pseudo"') + + if multithread: + if isinstance(multithread, bool): + dada_params.append("multithread=TRUE") + else: + dada_params.append(f"multithread={multithread}") + if verbose: + dada_params.append("verbose=TRUE") + + r_script_lines.append( + f"dada_out <- dada(filtered_reads, {', '.join(dada_params)})" + ) + r_script_lines.append(f"saveRDS(dada_out, file=dada_file)") + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_dada_file.parent) + result["output_files"] = [str(output_dada_file)] + return result + +@mcp.tool() +def merge_paired_reads( + dada_fwd_file: Path, + dada_rev_file: Path, + filtered_fwd_paths: List[Path], + filtered_rev_paths: List[Path], + output_merged_file: Path, + min_overlap: int = 12, + max_mismatch: int = 0, + verbose: bool = False, +) -> dict: + """ + Merges paired-end reads that have been denoised by dada2. + + Args: + dada_fwd_file: Path to the denoised forward sequence object (RDS file) from dada_denoise. + dada_rev_file: Path to the denoised reverse sequence object (RDS file) from dada_denoise. + filtered_fwd_paths: A list of paths to the *filtered* forward FASTQ files (used for sample names). + filtered_rev_paths: A list of paths to the *filtered* reverse FASTQ files (used for sample names). + output_merged_file: Path to save the merged sequence object (RDS file). + min_overlap: The minimum number of overlapping bases required to merge a read pair. + max_mismatch: The maximum number of mismatches allowed in the overlap region. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output merged object file. + """ + # Input validation + if not dada_fwd_file.is_file(): + raise FileNotFoundError(f"Denoised forward file not found: {dada_fwd_file}") + if dada_fwd_file.suffix != ".rds": + raise ValueError("dada_fwd_file must have a .rds extension.") + if not dada_rev_file.is_file(): + raise FileNotFoundError(f"Denoised reverse file not found: {dada_rev_file}") + if dada_rev_file.suffix != ".rds": + raise ValueError("dada_rev_file must have a .rds extension.") + if not filtered_fwd_paths or not filtered_rev_paths: + raise ValueError("filtered_fwd_paths and filtered_rev_paths cannot be empty.") + if len(filtered_fwd_paths) != len(filtered_rev_paths): + raise ValueError("Number of filtered forward and reverse read files must be the same.") + for f_read in filtered_fwd_paths: + if not f_read.is_file(): + raise FileNotFoundError(f"Filtered forward read file not found: {f_read}") + for r_read in filtered_rev_paths: + if not r_read.is_file(): + raise FileNotFoundError(f"Filtered reverse read file not found: {r_read}") + if output_merged_file.suffix != ".rds": + raise ValueError("output_merged_file must have a .rds extension.") + if min_overlap < 0: + raise ValueError("min_overlap cannot be negative.") + if max_mismatch < 0: + raise ValueError("max_mismatch cannot be negative.") + output_merged_file.parent.mkdir(parents=True, exist_ok=True) + + # Extract sample names from filtered file paths + sample_names = [] + for f_path in filtered_fwd_paths: + # Attempt to remove common suffixes to get a clean sample name + name = f_path.name + name = name.replace(".filtered.fastq.gz", "").replace(".fastq.gz", "") + name = name.replace("_R1", "").replace("_1", "").replace("_fwd", "") + sample_names.append(name) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "dada_fwd <- readRDS('" + str(dada_fwd_file) + "')", + "dada_rev <- readRDS('" + str(dada_rev_file) + "')", + "sample_names <- c(" + ", ".join([f'"{s}"' for s in sample_names]) + ")", + "names(dada_fwd) <- sample_names", + "names(dada_rev) <- sample_names", + "merged_file <- '" + str(output_merged_file) + "'", + "filtered_fwd_paths <- c(" + ", ".join([f'"{str(p)}"' for p in filtered_fwd_paths]) + ")", + "filtered_rev_paths <- c(" + ", ".join([f'"{str(p)}"' for p in filtered_rev_paths]) + ")", + ] + + merge_params = [ + f"minOverlap={min_overlap}", + f"maxMismatch={max_mismatch}", + ] + if verbose: + merge_params.append("verbose=TRUE") + + r_script_lines.append( + f"mergers <- mergePairs(dada_fwd, filtered_fwd_paths, dada_rev, filtered_rev_paths, {', '.join(merge_params)})" + ) + r_script_lines.append(f"saveRDS(mergers, file=merged_file)") + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_merged_file.parent) + result["output_files"] = [str(output_merged_file)] + return result + +@mcp.tool() +def make_sequence_table( + dada_objects_files: List[Path], + output_seq_table_file: Path, + output_seq_table_csv: Optional[Path] = None, + samples_names: Optional[List[str]] = None, + verbose: bool = False, +) -> dict: + """ + Constructs an amplicon sequence variant (ASV) table from denoised or merged sequence objects. + + Args: + dada_objects_files: A list of paths to denoised (from dada_denoise) or merged (from merge_paired_reads) + sequence object RDS files. + output_seq_table_file: Path to save the ASV table (RDS file). + output_seq_table_csv: Optional path to save the ASV table as a CSV file. + samples_names: Optional list of sample names corresponding to the dada_objects_files. + If None, names are inferred from the RDS filenames. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and paths to output files. + """ + # Input validation + if not dada_objects_files: + raise ValueError("dada_objects_files cannot be empty.") + for obj_file in dada_objects_files: + if not obj_file.is_file(): + raise FileNotFoundError(f"Dada object file not found: {obj_file}") + if obj_file.suffix != ".rds": + raise ValueError(f"Dada object file {obj_file} must have a .rds extension.") + if output_seq_table_file.suffix != ".rds": + raise ValueError("output_seq_table_file must have a .rds extension.") + output_seq_table_file.parent.mkdir(parents=True, exist_ok=True) + if output_seq_table_csv: + if output_seq_table_csv.suffix != ".csv": + raise ValueError("output_seq_table_csv must have a .csv extension.") + output_seq_table_csv.parent.mkdir(parents=True, exist_ok=True) + if samples_names and len(samples_names) != len(dada_objects_files): + raise ValueError("Number of sample names must match number of dada object files.") + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "dada_objects <- list(" + ", ".join([f"readRDS('{str(p)}')" for p in dada_objects_files]) + ")", + ] + + if samples_names: + r_script_lines.append("sample_names <- c(" + ", ".join([f'"{s}"' for s in samples_names]) + ")") + r_script_lines.append("names(dada_objects) <- sample_names") + else: + # Infer sample names from file names (e.g., remove .rds and common processing suffixes) + inferred_names = [] + for p in dada_objects_files: + name = p.stem + name = name.replace(".filtered", "").replace(".denoised", "").replace(".merged", "") + inferred_names.append(name) + r_script_lines.append("sample_names <- c(" + ", ".join([f'"{s}"' for s in inferred_names]) + ")") + r_script_lines.append("names(dada_objects) <- sample_names") + + r_script_lines.append( + f"seq_table <- makeSequenceTable(dada_objects)" + ) + r_script_lines.append(f"saveRDS(seq_table, file='{str(output_seq_table_file)}')") + + output_files = [str(output_seq_table_file)] + if output_seq_table_csv: + r_script_lines.append(f"write.csv(seq_table, file='{str(output_seq_table_csv)}', row.names=TRUE)") + output_files.append(str(output_seq_table_csv)) + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_seq_table_file.parent) + result["output_files"] = output_files + return result + +@mcp.tool() +def remove_bimera_denovo( + seq_table_file: Path, + output_nochim_table_file: Path, + output_nochim_table_csv: Optional[Path] = None, + method: str = "consensus", + multithread: Union[bool, int] = False, + verbose: bool = False, +) -> dict: + """ + Removes chimeric sequences from an ASV table using dada2's removeBimeraDenovo. + + Args: + seq_table_file: Path to the ASV table (RDS file) from make_sequence_table. + output_nochim_table_file: Path to save the chimera-removed ASV table (RDS file). + output_nochim_table_csv: Optional path to save the chimera-removed ASV table as a CSV file. + method: The method to use for chimera removal. "consensus" (default) or "pooled". + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and paths to output files. + """ + # Input validation + if not seq_table_file.is_file(): + raise FileNotFoundError(f"Sequence table file not found: {seq_table_file}") + if seq_table_file.suffix != ".rds": + raise ValueError("seq_table_file must have a .rds extension.") + if output_nochim_table_file.suffix != ".rds": + raise ValueError("output_nochim_table_file must have a .rds extension.") + output_nochim_table_file.parent.mkdir(parents=True, exist_ok=True) + if output_nochim_table_csv: + if output_nochim_table_csv.suffix != ".csv": + raise ValueError("output_nochim_table_csv must have a .csv extension.") + output_nochim_table_csv.parent.mkdir(parents=True, exist_ok=True) + if method not in ["consensus", "pooled"]: + raise ValueError(f"Invalid method: {method}. Must be 'consensus' or 'pooled'.") + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "seq_table <- readRDS('" + str(seq_table_file) + "')", + "nochim_file <- '" + str(output_nochim_table_file) + "'", + ] + + bimera_params = [ + f"method='{method}'", + ] + if multithread: + if isinstance(multithread, bool): + bimera_params.append("multithread=TRUE") + else: + bimera_params.append(f"multithread={multithread}") + if verbose: + bimera_params.append("verbose=TRUE") + + r_script_lines.append( + f"seq_table_nochim <- removeBimeraDenovo(seq_table, {', '.join(bimera_params)})" + ) + r_script_lines.append(f"saveRDS(seq_table_nochim, file=nochim_file)") + + output_files = [str(output_nochim_table_file)] + if output_nochim_table_csv: + r_script_lines.append(f"write.csv(seq_table_nochim, file='{str(output_nochim_table_csv)}', row.names=TRUE)") + output_files.append(str(output_nochim_table_csv)) + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_nochim_table_file.parent) + result["output_files"] = output_files + return result + +@mcp.tool() +def assign_taxonomy( + seq_table_file: Path, + ref_fasta_file: Path, + output_taxonomy_file: Path, + output_taxonomy_csv: Optional[Path] = None, + min_boot: int = 50, + multithread: Union[bool, int] = False, + try_rc: bool = False, + verbose: bool = False, +) -> dict: + """ + Assigns taxonomy to ASVs using the dada2 assignTaxonomy function. + + Args: + seq_table_file: Path to the ASV table (RDS file) from make_sequence_table or remove_bimera_denovo. + ref_fasta_file: Path to the reference FASTA file for taxonomic assignment (e.g., SILVA, RDP). + output_taxonomy_file: Path to save the taxonomy table (RDS file). + output_taxonomy_csv: Optional path to save the taxonomy table as a CSV file. + min_boot: Minimum bootstrap confidence for assigning a taxonomic level. + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + try_rc: If TRUE, the reverse-complement of each ASV is also used for classification. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and paths to output files. + """ + # Input validation + if not seq_table_file.is_file(): + raise FileNotFoundError(f"Sequence table file not found: {seq_table_file}") + if seq_table_file.suffix != ".rds": + raise ValueError("seq_table_file must have a .rds extension.") + if not ref_fasta_file.is_file(): + raise FileNotFoundError(f"Reference FASTA file not found: {ref_fasta_file}") + if output_taxonomy_file.suffix != ".rds": + raise ValueError("output_taxonomy_file must have a .rds extension.") + output_taxonomy_file.parent.mkdir(parents=True, exist_ok=True) + if output_taxonomy_csv: + if output_taxonomy_csv.suffix != ".csv": + raise ValueError("output_taxonomy_csv must have a .csv extension.") + output_taxonomy_csv.parent.mkdir(parents=True, exist_ok=True) + if not (0 <= min_boot <= 100): + raise ValueError("min_boot must be between 0 and 100.") + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "seq_table <- readRDS('" + str(seq_table_file) + "')", + "ref_fasta <- '" + str(ref_fasta_file) + "'", + "tax_file <- '" + str(output_taxonomy_file) + "'", + ] + + assign_params = [ + f"minBoot={min_boot}", + f"tryRC={str(try_rc).upper()}", + ] + if multithread: + if isinstance(multithread, bool): + assign_params.append("multithread=TRUE") + else: + assign_params.append(f"multithread={multithread}") + if verbose: + assign_params.append("verbose=TRUE") + + r_script_lines.append( + f"taxa <- assignTaxonomy(seq_table, ref_fasta, {', '.join(assign_params)})" + ) + r_script_lines.append(f"saveRDS(taxa, file=tax_file)") + + output_files = [str(output_taxonomy_file)] + if output_taxonomy_csv: + r_script_lines.append(f"write.csv(taxa, file='{str(output_taxonomy_csv)}', row.names=TRUE)") + output_files.append(str(output_taxonomy_csv)) + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_taxonomy_file.parent) + result["output_files"] = output_files + return result + +@mcp.tool() +def plot_quality_profile( + fastq_file: Path, + output_plot_file: Path, + n_reads: int = 1000000, +) -> dict: + """ + Generates a quality profile plot for a FASTQ file using dada2's plotQualityProfile. + + Args: + fastq_file: Path to the FASTQ file (raw or filtered). + output_plot_file: Path to save the quality profile plot (e.g., .png, .pdf). + n_reads: The number of reads to sample from the FASTQ file for plotting. + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output plot file. + """ + # Input validation + if not fastq_file.is_file(): + raise FileNotFoundError(f"FASTQ file not found: {fastq_file}") + if output_plot_file.suffix not in [".png", ".pdf", ".jpeg", ".tiff"]: + raise ValueError("output_plot_file must have a .png, .pdf, .jpeg, or .tiff extension.") + if n_reads <= 0: + raise ValueError("n_reads must be a positive integer.") + output_plot_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "fastq_file <- '" + str(fastq_file) + "'", + "plot_file <- '" + str(output_plot_file) + "'", + ] + + # Determine plotting device based on suffix + if output_plot_file.suffix == ".png": + r_script_lines.append(f"png(plot_file, width=800, height=600)") + elif output_plot_file.suffix == ".pdf": + r_script_lines.append(f"pdf(plot_file, width=10, height=8)") + elif output_plot_file.suffix == ".jpeg": + r_script_lines.append(f"jpeg(plot_file, width=800, height=600)") + elif output_plot_file.suffix == ".tiff": + r_script_lines.append(f"tiff(plot_file, width=800, height=600)") + + r_script_lines.append(f"plotQualityProfile(fastq_file, n={n_reads})") + r_script_lines.append("dev.off()") # Close the plotting device + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_plot_file.parent) + result["output_files"] = [str(output_plot_file)] + return result + +@mcp.tool() +def plot_errors( + error_model_file: Path, + output_plot_file: Path, +) -> dict: + """ + Generates an error rate plot from a learned error model using dada2's plotErrors. + + Args: + error_model_file: Path to the learned error model (RDS file) from learn_errors. + output_plot_file: Path to save the error plot (e.g., .png, .pdf). + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output plot file. + """ + # Input validation + if not error_model_file.is_file(): + raise FileNotFoundError(f"Error model file not found: {error_model_file}") + if error_model_file.suffix != ".rds": + raise ValueError("error_model_file must have a .rds extension.") + if output_plot_file.suffix not in [".png", ".pdf", ".jpeg", ".tiff"]: + raise ValueError("output_plot_file must have a .png, .pdf, .jpeg, or .tiff extension.") + output_plot_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "err <- readRDS('" + str(error_model_file) + "')", + "plot_file <- '" + str(output_plot_file) + "'", + ] + + # Determine plotting device based on suffix + if output_plot_file.suffix == ".png": + r_script_lines.append(f"png(plot_file, width=800, height=600)") + elif output_plot_file.suffix == ".pdf": + r_script_lines.append(f"pdf(plot_file, width=10, height=8)") + elif output_plot_file.suffix == ".jpeg": + r_script_lines.append(f"jpeg(plot_file, width=800, height=600)") + elif output_plot_file.suffix == ".tiff": + r_script_lines.append(f"tiff(plot_file, width=800, height=600)") + + r_script_lines.append(f"plotErrors(err, nominalQ=TRUE)") + r_script_lines.append("dev.off()") # Close the plotting device + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_plot_file.parent) + result["output_files"] = [str(output_plot_file)] + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-dada2/app/bioconductor-dada2_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-dada2/app/bioconductor-dada2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2b4e8d5bc442467126dd9d4267775af92545a143 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dada2/app/bioconductor-dada2_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-dada2/app/bioconductor-dada2_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_dada2' + + +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/Biomni/mcp_generated/mcp_bioconductor-dada2/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-dada2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dada2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-dada2/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-dada2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..04eceaaf308ba5bafb83003b54e5489155d995c0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dada2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dada2: + build: . + image: mcp-bioconductor-dada2:latest + container_name: mcp-bioconductor-dada2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dada2 + 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/Biomni/mcp_generated/mcp_bioconductor-dada2/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-dada2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8a4a34928a005c4265f2e6c7ea67ed4817f8c92a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dada2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dada2 + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dada2/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-dada2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dada2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-data-packages/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-data-packages/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..58d8e02b0aef74db7e2e9514bae607a6208870c7 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_server.py b/Biomni/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_server.py new file mode 100644 index 0000000000000000000000000000000000000000..da46b8bc503a4957a0a94c41d8a4d92cfe9e94f5 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-data-packages/app/bioconductor-data-packages_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d2fead283b6e8bcf843fb60ebd493d1751ad8f4e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-data-packages/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-data-packages/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-data-packages/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-data-packages/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-data-packages/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0d8d5a3e5ea75f6a8a9d10e4afddae0f74a6bd20 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-data-packages/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-data-packages/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fae089583404a67cf5f48b9cab9c8e51f9c0eb24 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-data-packages/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-data-packages/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-data-packages/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-decipher/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-decipher/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d5c0a1b5a4acc0ab1e4f03c7158652c8bdb04b3e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decipher/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-decipher via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-decipher -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-decipher_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-decipher_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-decipher_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-decipher/app/bioconductor-decipher_server.py b/Biomni/mcp_generated/mcp_bioconductor-decipher/app/bioconductor-decipher_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8b6ac9ae3d5e82fc6e4ac586791d8f6ecca588 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decipher/app/bioconductor-decipher_server.py @@ -0,0 +1,439 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Dict, Any, Optional, List + +# MCP decorators are used directly as the execution environment provides them. +# In a local development setup, you would use: +# from mcp import tool as mcp + +def _run_r_script( + r_script_content: str, + args: List[str], + output_files_map: Dict[str, Path] +) -> Dict[str, Any]: + """ + Helper function to execute an R script and return a structured result. + """ + cmd = ["Rscript", "-"] + args + # Create a user-friendly representation of the command + command_executed = f"echo '{r_script_content}' | Rscript - {' '.join(args)}" + + try: + result = subprocess.run( + cmd, + input=r_script_content, + capture_output=True, + text=True, + check=True, + ) + + # Verify that all expected output files were created and are not empty + for key, path in output_files_map.items(): + if not path.is_file() or path.stat().st_size == 0: + raise FileNotFoundError( + f"Expected output file '{path}' was not created or is empty. " + f"R script stderr: {result.stderr}" + ) + + 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 subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } + except FileNotFoundError as e: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": str(e), + "error": "An output file was not generated as expected.", + } + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_decipher' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def align_sequences( + input_fasta: Path, + substitution_matrix: Optional[str] = None, + gap_opening: float = 10.0, + gap_extension: float = 0.1, + processors: int = 1, +) -> Dict[str, Any]: + """ + Performs multiple sequence alignment on sequences using DECIPHER's AlignSeqs. + + This tool aligns a set of DNA, RNA, or amino acid sequences provided in a FASTA file. + It automatically detects the sequence type. + + Args: + input_fasta: Path to the input FASTA file containing unaligned sequences. + substitution_matrix: The substitution matrix to use (e.g., 'BLOSUM62', 'PAM40'). + If None, DECIPHER will choose a default based on sequence type. + gap_opening: The penalty for opening a gap. + gap_extension: The penalty for extending a gap. + processors: The number of processors to use for alignment. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + # Load required libraries + suppressPackageStartupMessages(library(DECIPHER)) + + # Get command line arguments + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + subMatrix <- if (args[3] == "NULL") NULL else args[3] + gapOpen <- as.numeric(args[4]) + gapExt <- as.numeric(args[5]) + procs <- as.integer(args[6]) + + # Read sequences (readBStringSet is generic for DNA, RNA, AA) + seqs <- readBStringSet(inputFile) + + # Perform alignment + cat("Starting sequence alignment...\\n", file = stderr()) + aligned_seqs <- AlignSeqs(seqs, + gapOpening = gapOpen, + gapExtension = gapExt, + substitutionMatrix = subMatrix, + processors = procs, + verbose = TRUE) + cat("Alignment complete.\\n", file = stderr()) + + # Write the aligned sequences to the output file + writeXStringSet(aligned_seqs, filepath = outputFile) + cat("Output written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_aligned_fasta = temp_path / "aligned.fasta" + + args = [ + str(input_fasta.resolve()), + str(output_aligned_fasta.resolve()), + str(substitution_matrix) if substitution_matrix else "NULL", + str(gap_opening), + str(gap_extension), + str(processors), + ] + + return _run_r_script(r_script, args, {"aligned_fasta": output_aligned_fasta}) + + +@mcp.tool() +def find_chimeras( + input_fasta: Path, + processors: int = 1, +) -> Dict[str, Any]: + """ + Identifies chimeric sequences in a FASTA file using DECIPHER's isChimera. + + This tool screens a set of sequences (typically 16S rRNA amplicons) and + identifies which ones are likely to be chimeras formed during PCR. + + Args: + input_fasta: Path to the input FASTA file containing sequences to check. + processors: The number of processors to use for chimera detection. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(DECIPHER)) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + procs <- as.integer(args[3]) + + cat("Reading sequences...\\n", file = stderr()) + seqs <- readDNAStringSet(inputFile) + + cat("Finding chimeras...\\n", file = stderr()) + chimera_flags <- isChimera(seqs, processors = procs, verbose = TRUE) + + chimera_names <- names(seqs)[chimera_flags] + + cat(length(chimera_names), "chimeras found.\\n", file = stderr()) + writeLines(chimera_names, con = outputFile) + cat("Chimeric sequence names written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_chimera_list = temp_path / "chimeric_sequences.txt" + + args = [ + str(input_fasta.resolve()), + str(output_chimera_list.resolve()), + str(processors), + ] + + return _run_r_script(r_script, args, {"chimera_list": output_chimera_list}) + + +@mcp.tool() +def classify_sequences( + query_fasta: Path, + training_set: Path, + confidence_threshold: float = 0.7, + processors: int = 1, +) -> Dict[str, Any]: + """ + Classifies sequences using a pre-trained DECIPHER model (IdTaxa). + + This tool assigns taxonomic classification to sequences based on a provided + training set file (e.g., SILVA, RDP, Greengenes). + + Args: + query_fasta: Path to the FASTA file of sequences to classify. + training_set: Path to the .RData file containing the training set object. + confidence_threshold: The minimum confidence required to assign a taxonomy. + processors: The number of processors to use for classification. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not query_fasta.is_file(): + raise FileNotFoundError(f"Query FASTA file not found: {query_fasta}") + if not training_set.is_file(): + raise FileNotFoundError(f"Training set file not found: {training_set}") + if not 0.0 <= confidence_threshold <= 1.0: + raise ValueError("Confidence threshold must be between 0.0 and 1.0.") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(DECIPHER)) + + args <- commandArgs(trailingOnly = TRUE) + queryFile <- args[1] + trainingFile <- args[2] + outputFile <- args[3] + conf <- as.numeric(args[4]) + procs <- as.integer(args[5]) + + cat("Reading query sequences...\\n", file = stderr()) + seqs <- readDNAStringSet(queryFile) + + cat("Loading training set...\\n", file = stderr()) + load(trainingFile) # Assumes this loads an object named 'trainingSet' + + cat("Classifying sequences with IdTaxa...\\n", file = stderr()) + ids <- IdTaxa(seqs, trainingSet, threshold = conf, processors = procs, verbose = TRUE) + + # Format the output into a table + get_taxonomy <- function(x) { + if (length(x) > 0 && length(x[[1]]$taxon) > 0) { + paste(x[[1]]$taxon, collapse=";") + } else { + "Unclassified" + } + } + taxonomy_strings <- sapply(ids, get_taxonomy) + output_df <- data.frame(sequence_name = names(seqs), taxonomy = taxonomy_strings) + + cat("Writing classification results...\\n", file = stderr()) + write.table(output_df, file = outputFile, sep = "\\t", row.names = FALSE, quote = FALSE) + cat("Output written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_classification_tsv = temp_path / "classification.tsv" + + args = [ + str(query_fasta.resolve()), + str(training_set.resolve()), + str(output_classification_tsv.resolve()), + str(confidence_threshold), + str(processors), + ] + + return _run_r_script(r_script, args, {"classification_results": output_classification_tsv}) + + +@mcp.tool() +def design_primers( + input_aligned_fasta: Path, + min_length: int = 18, + max_length: int = 25, + min_tm: float = 50.0, + max_tm: float = 65.0, + min_gc: float = 40.0, + max_gc: float = 60.0, + max_degeneracy: int = 4, + processors: int = 1, +) -> Dict[str, Any]: + """ + Designs group-specific PCR primers from an aligned FASTA file using DesignPrimers. + + Args: + input_aligned_fasta: Path to an aligned FASTA file of target sequences. + min_length: Minimum primer length. + max_length: Maximum primer length. + min_tm: Minimum melting temperature (°C). + max_tm: Maximum melting temperature (°C). + min_gc: Minimum GC content (percent). + max_gc: Maximum GC content (percent). + max_degeneracy: Maximum number of degenerate bases allowed in a primer. + processors: The number of processors to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not input_aligned_fasta.is_file(): + raise FileNotFoundError(f"Input aligned FASTA file not found: {input_aligned_fasta}") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(DECIPHER)) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + minL <- as.integer(args[3]) + maxL <- as.integer(args[4]) + minTm <- as.numeric(args[5]) + maxTm <- as.numeric(args[6]) + minGC <- as.numeric(args[7]) + maxGC <- as.numeric(args[8]) + maxD <- as.integer(args[9]) + procs <- as.integer(args[10]) + + cat("Reading aligned sequences...\\n", file = stderr()) + seqs <- readDNAStringSet(inputFile) + + cat("Designing primers...\\n", file = stderr()) + primers <- DesignPrimers( + seqs, minLength = minL, maxLength = maxL, minTm = minTm, maxTm = maxTm, + minGC = minGC, maxGC = maxGC, maxDegeneracy = maxD, + processors = procs, verbose = TRUE + ) + + cat(nrow(primers), "candidate primers found.\\n", file = stderr()) + write.table(primers, file = outputFile, sep = "\\t", row.names = FALSE, quote = FALSE) + cat("Primer table written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_primers_tsv = temp_path / "primers.tsv" + + args = [ + str(input_aligned_fasta.resolve()), + str(output_primers_tsv.resolve()), + str(min_length), str(max_length), str(min_tm), str(max_tm), + str(min_gc), str(max_gc), str(max_degeneracy), str(processors), + ] + + return _run_r_script(r_script, args, {"designed_primers": output_primers_tsv}) + + +@mcp.tool() +def design_probes( + input_aligned_fasta: Path, + min_length: int = 18, + max_length: int = 50, + min_tm: float = 60.0, + max_tm: float = 80.0, + min_gc: float = 40.0, + max_gc: float = 60.0, + max_degeneracy: int = 1, + processors: int = 1, +) -> Dict[str, Any]: + """ + Designs hybridization probes (e.g., for FISH) from an aligned FASTA file using DesignProbes. + + Args: + input_aligned_fasta: Path to an aligned FASTA file of target sequences. + min_length: Minimum probe length. + max_length: Maximum probe length. + min_tm: Minimum melting temperature (°C). + max_tm: Maximum melting temperature (°C). + min_gc: Minimum GC content (percent). + max_gc: Maximum GC content (percent). + max_degeneracy: Maximum number of degenerate bases allowed in a probe. + processors: The number of processors to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not input_aligned_fasta.is_file(): + raise FileNotFoundError(f"Input aligned FASTA file not found: {input_aligned_fasta}") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(DECIPHER)) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + minL <- as.integer(args[3]) + maxL <- as.integer(args[4]) + minTm <- as.numeric(args[5]) + maxTm <- as.numeric(args[6]) + minGC <- as.numeric(args[7]) + maxGC <- as.numeric(args[8]) + maxD <- as.integer(args[9]) + procs <- as.integer(args[10]) + + cat("Reading aligned sequences...\\n", file = stderr()) + seqs <- readDNAStringSet(inputFile) + + cat("Designing probes...\\n", file = stderr()) + probes <- DesignProbes( + seqs, minLength = minL, maxLength = maxL, minTm = minTm, maxTm = maxTm, + minGC = minGC, maxGC = maxGC, maxDegeneracy = maxD, + processors = procs, verbose = TRUE + ) + + cat(nrow(probes), "candidate probes found.\\n", file = stderr()) + write.table(probes, file = outputFile, sep = "\\t", row.names = FALSE, quote = FALSE) + cat("Probe table written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_probes_tsv = temp_path / "probes.tsv" + + args = [ + str(input_aligned_fasta.resolve()), + str(output_probes_tsv.resolve()), + str(min_length), str(max_length), str(min_tm), str(max_tm), + str(min_gc), str(max_gc), str(max_degeneracy), str(processors), + ] + + return _run_r_script(r_script, args, {"designed_probes": output_probes_tsv}) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-decipher/app/bioconductor-decipher_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-decipher/app/bioconductor-decipher_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2b6a3a87e0253befdecc329c6968d9d226b37b64 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decipher/app/bioconductor-decipher_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-decipher/app/bioconductor-decipher_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_decipher' + + +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/Biomni/mcp_generated/mcp_bioconductor-decipher/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-decipher/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decipher/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-decipher/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-decipher/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..10686798d56c15c9f8d405ebcaf06e7ae62b78ca --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decipher/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-decipher: + build: . + image: mcp-bioconductor-decipher:latest + container_name: mcp-bioconductor-decipher + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-decipher + 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/Biomni/mcp_generated/mcp_bioconductor-decipher/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-decipher/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..551ecb92037dae092073d842ab487868a010c2e4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decipher/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-decipher + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-decipher/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-decipher/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decipher/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-decontam/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-decontam/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b841dc6fd6491701fc9d712aa92aad2174e6eed7 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_server.py b/Biomni/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ec61400556fffc522339bc4ff2f66808ccf4a6d4 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-decontam/app/bioconductor-decontam_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ce314e63102909fabf0930e6385b0a2cfc949f0d --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-decontam/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-decontam/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decontam/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-decontam/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-decontam/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c6ce8822731866aa0f4eb6b74685000567296134 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-decontam/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-decontam/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb54043185521d18619255a22a22a8db8de09be4 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-decontam/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-decontam/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decontam/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-decontx/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-decontx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..820ab9780370a368b6c65cf4a3dfb8651f02dc92 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decontx/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-decontx via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-decontx -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-decontx_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-decontx_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-decontx_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-decontx/app/bioconductor-decontx_server.py b/Biomni/mcp_generated/mcp_bioconductor-decontx/app/bioconductor-decontx_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa6cc2128f9c654bb0aa83dbaf7c76792bfb8d7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decontx/app/bioconductor-decontx_server.py @@ -0,0 +1,334 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_decontx' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def decontx( + x: Path, + output_prefix: str, + z: Optional[Path] = None, + batch: Optional[Path] = None, + max_iter: int = 500, + delta_a: float = 1.0, + delta_b: float = 10.0, + phi: Optional[Path] = None, + theta: Optional[Path] = None, + effective_length: Optional[Path] = None, + length_normalization: str = "tpm", + num_chains: int = 3, + num_cores: int = 1, + seed: int = 12345, + logfile: Optional[Path] = None, + verbose: bool = True, +): + """ + Estimate and remove RNA contamination in single-cell data using DecontX. + + This tool wraps the decontX R function to identify and remove contamination + from ambient RNA in single-cell RNA-seq count data. + + Args: + x: Path to the input count matrix file (e.g., CSV). Rows should be + genes and columns should be cells. The first column should contain + gene names. + output_prefix: Prefix for the output files. The directory will be + created if it doesn't exist. + z: Optional path to a file containing cell labels. One label per line. + batch: Optional path to a file containing batch labels. One label per line. + max_iter: Maximum number of iterations for the Gibbs sampler. + delta_a: The first concentration parameter for the Dirichlet prior on + contamination levels. + delta_b: The second concentration parameter for the Dirichlet prior on + contamination levels. + phi: Optional path to a file containing the background contamination + distribution. If not provided, it will be estimated. + theta: Optional path to a file containing the native expression + distribution for each cell. If not provided, it will be estimated. + effective_length: Optional path to a file containing effective transcript + lengths for length normalization. + length_normalization: The length normalization method to be used. + One of 'tpm', 'fpm', 'fpkm', 'none'. + num_chains: The number of MCMC chains to run. + num_cores: The number of cores to use for parallel processing. + seed: The seed for the random number generator. + logfile: Optional path to a file where logs will be written. + verbose: If True, print progress messages to stderr. + """ + # --- Input Validation --- + if not x.is_file(): + raise FileNotFoundError(f"Input count matrix file not found: {x}") + if z and not z.is_file(): + raise FileNotFoundError(f"Cell labels file not found: {z}") + if batch and not batch.is_file(): + raise FileNotFoundError(f"Batch labels file not found: {batch}") + if phi and not phi.is_file(): + raise FileNotFoundError(f"Phi distribution file not found: {phi}") + if theta and not theta.is_file(): + raise FileNotFoundError(f"Theta distribution file not found: {theta}") + if effective_length and not effective_length.is_file(): + raise FileNotFoundError(f"Effective length file not found: {effective_length}") + + if max_iter <= 0: + raise ValueError("max_iter must be a positive integer.") + if num_chains <= 0: + raise ValueError("num_chains must be a positive integer.") + if num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if delta_a <= 0 or delta_b <= 0: + raise ValueError("Delta parameters (delta_a, delta_b) must be positive.") + + allowed_norm = ["tpm", "fpm", "fpkm", "none"] + if length_normalization not in allowed_norm: + raise ValueError(f"length_normalization must be one of {allowed_norm}") + + # --- File and Path Handling --- + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_counts_path = Path(f"{output_prefix}_decontXcounts.csv") + output_contamination_path = Path(f"{output_prefix}_contamination.csv") + + with tempfile.TemporaryDirectory() as temp_dir: + script_path = Path(temp_dir) / "run_decontx.R" + + # --- R Script Generation --- + z_r = f'"{z.resolve()}"' if z else "NULL" + batch_r = f'"{batch.resolve()}"' if batch else "NULL" + phi_r = f'read.csv("{phi.resolve()}", header=FALSE)$V1' if phi else "NULL" + theta_r = f'read.csv("{theta.resolve()}", header=FALSE)$V1' if theta else "NULL" + effective_length_r = f'read.csv("{effective_length.resolve()}", header=FALSE)$V1' if effective_length else "NULL" + logfile_r = f'"{logfile.resolve()}"' if logfile else "NULL" + verbose_r = "TRUE" if verbose else "FALSE" + + r_script = f""" + library(decontX) + library(SingleCellExperiment) + library(Matrix) + + counts <- as.matrix(read.csv("{x.resolve()}", row.names=1, check.names=FALSE)) + + z_data <- if (!is.null({z_r})) read.csv({z_r}, header=FALSE, stringsAsFactors=TRUE)$V1 else NULL + batch_data <- if (!is.null({batch_r})) read.csv({batch_r}, header=FALSE, stringsAsFactors=TRUE)$V1 else NULL + phi_data <- if (!is.null({phi_r})) {phi_r} else NULL + theta_data <- if (!is.null({theta_r})) {theta_r} else NULL + effectiveLength_data <- if (!is.null({effective_length_r})) {effective_length_r} else NULL + + sce <- SingleCellExperiment(assays = list(counts = counts)) + + set.seed({seed}) + sce <- decontX( + x = sce, + z = z_data, + batch = batch_data, + maxIter = {max_iter}, + delta = c({delta_a}, {delta_b}), + phi = phi_data, + theta = theta_data, + effectiveLength = effectiveLength_data, + lengthNormalization = "{length_normalization}", + numChains = {num_chains}, + numCores = {num_cores}, + logfile = {logfile_r}, + verbose = {verbose_r} + ) + + decontaminated_counts <- decontXcounts(sce) + contamination_scores <- colData(sce)$decontX_contamination + results_df <- data.frame(contamination = contamination_scores, row.names = colnames(sce)) + + write.csv(as.matrix(decontaminated_counts), file="{output_counts_path.resolve()}", row.names=TRUE) + write.csv(results_df, file="{output_contamination_path.resolve()}", row.names=TRUE) + """ + + with open(script_path, "w") as f: + f.write(r_script) + + # --- Subprocess Execution --- + command = ["Rscript", str(script_path)] + command_str = " ".join(map(str, command)) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + + output_files = [ + str(output_counts_path), + str(output_contamination_path) + ] + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "DecontX execution failed.", + "return_code": e.returncode + } + +@mcp.tool() +def decontpro( + x: Path, + output_prefix: str, + z: Optional[Path] = None, + batch: Optional[Path] = None, + max_iter: int = 200, + delta_a: float = 1.0, + delta_b: float = 1.0, + gamma: float = 1.0, + beta: float = 1.0, + num_chains: int = 3, + num_cores: int = 1, + seed: int = 12345, + logfile: Optional[Path] = None, + verbose: bool = True, +): + """ + Estimate and remove protein contamination in CITE-seq data using DecontPro. + + This tool wraps the decontPro R function to identify and remove contamination + from ambient and background sources in single-cell protein expression data. + + Args: + x: Path to the input ADT count matrix file (e.g., CSV). Rows should be + proteins and columns should be cells. The first column should contain + protein names. + output_prefix: Prefix for the output files. The directory will be + created if it doesn't exist. + z: Optional path to a file containing cell labels. One label per line. + batch: Optional path to a file containing batch labels. One label per line. + max_iter: Maximum number of iterations for the Gibbs sampler. + delta_a: The first concentration parameter for the Dirichlet prior on + contamination levels. + delta_b: The second concentration parameter for the Dirichlet prior on + contamination levels. + gamma: The background contamination distribution parameter. + beta: The native expression distribution parameter for each cell. + num_chains: The number of MCMC chains to run. + num_cores: The number of cores to use for parallel processing. + seed: The seed for the random number generator. + logfile: Optional path to a file where logs will be written. + verbose: If True, print progress messages to stderr. + """ + # --- Input Validation --- + if not x.is_file(): + raise FileNotFoundError(f"Input ADT count matrix file not found: {x}") + if z and not z.is_file(): + raise FileNotFoundError(f"Cell labels file not found: {z}") + if batch and not batch.is_file(): + raise FileNotFoundError(f"Batch labels file not found: {batch}") + + if max_iter <= 0: + raise ValueError("max_iter must be a positive integer.") + if num_chains <= 0: + raise ValueError("num_chains must be a positive integer.") + if num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if delta_a <= 0 or delta_b <= 0: + raise ValueError("Delta parameters (delta_a, delta_b) must be positive.") + if gamma <= 0 or beta <= 0: + raise ValueError("Gamma and Beta parameters must be positive.") + + # --- File and Path Handling --- + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_counts_path = Path(f"{output_prefix}_decontPro_counts.csv") + output_contamination_path = Path(f"{output_prefix}_decontPro_contamination.csv") + + with tempfile.TemporaryDirectory() as temp_dir: + script_path = Path(temp_dir) / "run_decontpro.R" + + # --- R Script Generation --- + z_r = f'"{z.resolve()}"' if z else "NULL" + batch_r = f'"{batch.resolve()}"' if batch else "NULL" + logfile_r = f'"{logfile.resolve()}"' if logfile else "NULL" + verbose_r = "TRUE" if verbose else "FALSE" + + r_script = f""" + library(decontX) + library(SingleCellExperiment) + library(Matrix) + + counts <- as.matrix(read.csv("{x.resolve()}", row.names=1, check.names=FALSE)) + + z_data <- if (!is.null({z_r})) read.csv({z_r}, header=FALSE, stringsAsFactors=TRUE)$V1 else NULL + batch_data <- if (!is.null({batch_r})) read.csv({batch_r}, header=FALSE, stringsAsFactors=TRUE)$V1 else NULL + + sce <- SingleCellExperiment(assays = list(counts = counts)) + + set.seed({seed}) + sce <- decontPro( + x = sce, + z = z_data, + batch = batch_data, + maxIter = {max_iter}, + delta = c({delta_a}, {delta_b}), + gamma = {gamma}, + beta = {beta}, + numChains = {num_chains}, + numCores = {num_cores}, + logfile = {logfile_r}, + verbose = {verbose_r} + ) + + decontaminated_counts <- metadata(sce)$decontPro$decontPro_counts + contamination_scores <- colData(sce)$decontPro_contamination + results_df <- data.frame(contamination = contamination_scores, row.names = colnames(sce)) + + write.csv(as.matrix(decontaminated_counts), file="{output_counts_path.resolve()}", row.names=TRUE) + write.csv(results_df, file="{output_contamination_path.resolve()}", row.names=TRUE) + """ + + with open(script_path, "w") as f: + f.write(r_script) + + # --- Subprocess Execution --- + command = ["Rscript", str(script_path)] + command_str = " ".join(map(str, command)) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + + output_files = [ + str(output_counts_path), + str(output_contamination_path) + ] + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "DecontPro execution failed.", + "return_code": e.returncode + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-decontx/app/bioconductor-decontx_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-decontx/app/bioconductor-decontx_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a846e56dc462be8ca8c3250c2d1d5ff900442fea --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decontx/app/bioconductor-decontx_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-decontx/app/bioconductor-decontx_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_decontx' + + +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/Biomni/mcp_generated/mcp_bioconductor-decontx/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-decontx/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..54278d77b94074aee3436b6a210fcfbe16409ac2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decontx/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-decontx: + build: . + image: mcp-bioconductor-decontx:latest + container_name: mcp-bioconductor-decontx + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-decontx + 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/Biomni/mcp_generated/mcp_bioconductor-decontx/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-decontx/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..494d5271b04b4f4c9ab6c0e7d89038eb55a793e2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decontx/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-decontx + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-decontx/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-decontx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-decontx/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..af527c8333371e1f05ee96a65ee3d6f9e4fb7a13 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/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-deconvobuddies via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-deconvobuddies -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-deconvobuddies_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-deconvobuddies_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-deconvobuddies_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_server.py b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a1eb8147e87d0f6d813073db6cdf99407fd50487 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_server.py @@ -0,0 +1,286 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_deconvobuddies' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def get_mean_ratio( + sce_path: str, + cell_type_col: str, + assay_name: str = "logcounts", + output_path: str = "mean_ratio_stats.rds", +) -> Dict[str, Any]: + """ + Calculate the Mean Ratio for each gene and cell type in a SingleCellExperiment object. + This is a key metric for identifying specific marker genes for deconvolution. + """ + sce_p = Path(sce_path) + if not sce_p.exists(): + raise FileNotFoundError(f"Input SCE file not found: {sce_path}") + + # Construct R command + r_code = f""" + library(DeconvoBuddies) + library(SingleCellExperiment) + sce <- readRDS('{sce_path}') + stats <- get_mean_ratio(sce, cellType_col = '{cell_type_col}', assay_name = '{assay_name}') + saveRDS(stats, '{output_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"DeconvoBuddies::get_mean_ratio on {sce_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def find_markers_1v_all( + sce_path: str, + cell_type_col: str, + assay_name: str = "logcounts", + output_path: str = "findMarkers_stats.rds", +) -> Dict[str, Any]: + """ + Wrapper for scran::findMarkers to perform 1-vs-all comparisons for cell type marker identification. + """ + sce_p = Path(sce_path) + if not sce_p.exists(): + raise FileNotFoundError(f"Input SCE file not found: {sce_path}") + + r_code = f""" + library(DeconvoBuddies) + library(SingleCellExperiment) + sce <- readRDS('{sce_path}') + stats <- findMarkers_1vAll(sce, cellType_col = '{cell_type_col}', assay_name = '{assay_name}') + saveRDS(stats, '{output_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"DeconvoBuddies::findMarkers_1vAll on {sce_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def plot_marker_expression( + sce_path: str, + stats_path: str, + cell_type_col: str, + n_markers: int = 5, + assay_name: str = "logcounts", + output_plot: str = "marker_expression.pdf", +) -> Dict[str, Any]: + """ + Visualize the expression of top marker genes across cell types using violin plots. + """ + if n_markers <= 0: + raise ValueError("n_markers must be a positive integer") + + sce_p = Path(sce_path) + stats_p = Path(stats_path) + if not sce_p.exists() or not stats_p.exists(): + raise FileNotFoundError("Input SCE or Stats file not found.") + + r_code = f""" + library(DeconvoBuddies) + library(SingleCellExperiment) + library(ggplot2) + sce <- readRDS('{sce_path}') + stats <- readRDS('{stats_path}') + + # Get top markers + top_markers <- stats[stats$Rank <= {n_markers}, "gene"] + + plot <- plot_marker_express(sce, + stats, + cell_type_col = '{cell_type_col}', + n_genes = {n_markers}, + assay_name = '{assay_name}') + + ggsave('{output_plot}', plot, width = 10, height = 8) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "DeconvoBuddies::plot_marker_express", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_plot] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def make_cell_colors( + cell_types: List[str], + palette: str = "hue_pal", + seed: int = 123, +) -> Dict[str, Any]: + """ + Generate a consistent color palette for cell types. + """ + cell_types_str = 'c("' + '","'.join(cell_types) + '")' + + r_code = f""" + library(DeconvoBuddies) + set.seed({seed}) + colors <- make_cell_colors(cell_types = {cell_types_str}, palette = '{palette}') + cat(jsonlite::toJSON(as.list(colors))) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "DeconvoBuddies::make_cell_colors", + "stdout": result.stdout, + "stderr": result.stderr, + "colors": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def plot_set_basis( + sce_path: str, + basis_matrix_path: str, + cell_type_col: str, + output_plot: str = "basis_plot.pdf", +) -> Dict[str, Any]: + """ + Plot the basis matrix (reference profile) to visualize the expression of markers in the reference. + """ + sce_p = Path(sce_path) + basis_p = Path(basis_matrix_path) + + if not sce_p.exists() or not basis_p.exists(): + raise FileNotFoundError("Input SCE or Basis Matrix file not found.") + + r_code = f""" + library(DeconvoBuddies) + library(SingleCellExperiment) + library(ggplot2) + sce <- readRDS('{sce_path}') + basis <- readRDS('{basis_matrix_path}') + + plot <- plot_set_basis(sce, basis, cellType_col = '{cell_type_col}') + ggsave('{output_plot}', plot, width = 8, height = 6) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "DeconvoBuddies::plot_set_basis", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_plot] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def create_merged_sce( + sce_paths: List[str], + output_path: str = "merged_sce.rds", +) -> Dict[str, Any]: + """ + Merge multiple SingleCellExperiment objects into one, ensuring consistent metadata. + """ + if not sce_paths: + raise ValueError("List of SCE paths cannot be empty") + + for p in sce_paths: + if not Path(p).exists(): + raise FileNotFoundError(f"File not found: {p}") + + paths_r = 'c("' + '","'.join(sce_paths) + '")' + + r_code = f""" + library(SingleCellExperiment) + sce_list <- lapply({paths_r}, readRDS) + # Simple merge logic for SCE + merged_sce <- do.call(cbind, sce_list) + saveRDS(merged_sce, '{output_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Manual SCE Merge via Rscript", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..37a8f0f7cf5613d980335d04af98c058d49fdb7e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_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-deconvobuddies/app/bioconductor-deconvobuddies_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_deconvobuddies' + + +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/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3879582e1c4b2d6bfbc7c26d642832328bfc0e31 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-deconvobuddies: + build: . + image: mcp-bioconductor-deconvobuddies:latest + container_name: mcp-bioconductor-deconvobuddies + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-deconvobuddies + 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/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0939aef8616e2a4d908ea17157ad8e306e3bb61a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-deconvobuddies + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deconvobuddies/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-delayedarray/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-delayedarray/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-delayedarray/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..727a460343f6fb737b5caace83184a909970a929 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/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-delayedmatrixstats via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-delayedmatrixstats -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-delayedmatrixstats_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-delayedmatrixstats_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-delayedmatrixstats_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_server.py b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_server.py new file mode 100644 index 0000000000000000000000000000000000000000..827d67ca4603ba8e19a2b41e10896ecfcb052d4a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_server.py @@ -0,0 +1,189 @@ +import subprocess +from pathlib import Path +from typing import List, Optional + +# In a real MCP environment, the 'mcp' module would be available. +# The following is a placeholder to make the code runnable for testing. +class _MCP: + def tool(self): + def decorator(f): + return f + return decorator +mcp = _MCP() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_delayedmatrixstats' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def fastqc( + sequence_files: List[Path], + outdir: Optional[Path] = None, + extract: bool = True, + format: Optional[str] = None, + threads: int = 1, + contaminants: Optional[Path] = None, + adapters: Optional[Path] = None, + limits: Optional[Path] = None, + quiet: bool = False, + java_path: Optional[Path] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + max_memory: Optional[str] = None, + casava: bool = False, + nano: bool = False, + nofilter: bool = False, + nogroup: bool = False, + min_base_quality: Optional[int] = None, + read_group_size: Optional[int] = None, + kmers: Optional[int] = None, +): + """ + Run FastQC, a quality control tool for high throughput sequence data. + + This tool takes a set of sequence files and produces a quality control + report for each one, which can be used to assess the quality of raw data. + """ + # 1. Input Validation + if not sequence_files: + raise ValueError("At least one sequence file must be provided.") + + for seq_file in sequence_files: + if not seq_file.exists(): + raise FileNotFoundError(f"Input sequence file not found: {seq_file}") + + if format and format.lower() not in ["fastq", "bam", "sam"]: + raise ValueError("Invalid format specified. Must be one of 'fastq', 'bam', 'sam'.") + + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + + for optional_file in [contaminants, adapters, limits, java_path]: + if optional_file and not optional_file.exists(): + raise FileNotFoundError(f"Optional file not found: {optional_file}") + + # 2. Command Construction + cmd = ["fastqc"] + + if outdir: + # Ensure output directory exists + outdir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--outdir", str(outdir)]) + + if not extract: + cmd.append("--noextract") + + if format: + cmd.extend(["--format", format.lower()]) + + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + if contaminants: + cmd.extend(["--contaminants", str(contaminants)]) + + if adapters: + cmd.extend(["--adapters", str(adapters)]) + + if limits: + cmd.extend(["--limits", str(limits)]) + + if quiet: + cmd.append("--quiet") + + if java_path: + cmd.extend(["--java", str(java_path)]) + + if min_length is not None: + cmd.extend(["--min_length", str(min_length)]) + + if max_length is not None: + cmd.extend(["--max_length", str(max_length)]) + + if max_memory: + cmd.extend(["--max_memory", str(max_memory)]) + + if casava: + cmd.append("--casava") + + if nano: + cmd.append("--nano") + + if nofilter: + cmd.append("--nofilter") + + if nogroup: + cmd.append("--nogroup") + + if min_base_quality is not None: + cmd.extend(["--min_base_quality", str(min_base_quality)]) + + if read_group_size is not None: + cmd.extend(["--read_group_size", str(read_group_size)]) + + if kmers is not None: + cmd.extend(["--kmers", str(kmers)]) + + cmd.extend([str(f) for f in sequence_files]) + command_executed = " ".join(cmd) + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + # This error occurs if the 'fastqc' executable is not in the system's PATH + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'fastqc' command not found. Please ensure FastQC is installed and in your PATH.", + "output_files": [], + "return_code": 127 + } + except subprocess.CalledProcessError as e: + # This error occurs if FastQC returns a non-zero exit code + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "return_code": e.returncode + } + + # 4. Discover and list output files + output_dir_path = outdir if outdir else sequence_files[0].parent + output_files = [] + for seq_file in sequence_files: + # FastQC output naming convention: strip common extensions and add _fastqc.zip/html + base_name = seq_file.name + for ext in ['.gz', '.bz2', '.txt', '.sam', '.bam', '.fastq', '.fq']: + if base_name.lower().endswith(ext): + base_name = base_name[:-len(ext)] + + zip_file = output_dir_path / f"{base_name}_fastqc.zip" + html_file = output_dir_path / f"{base_name}_fastqc.html" + + if zip_file.exists(): + output_files.append(str(zip_file)) + # The HTML file is inside the ZIP unless --noextract is used with an older FastQC + # or if --extract is used. We will primarily report the zip and the unzipped HTML if it exists. + if html_file.exists(): + output_files.append(str(html_file)) + + # 5. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": sorted(list(set(output_files))), # Ensure unique paths + "return_code": result.returncode + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..efda66bcc6286a7f1682589c376665d5ff3244e9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_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-delayedmatrixstats/app/bioconductor-delayedmatrixstats_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_delayedmatrixstats' + + +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/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..639ad771950cf50d4867c1f9f233bfc20e285322 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-delayedmatrixstats: + build: . + image: mcp-bioconductor-delayedmatrixstats:latest + container_name: mcp-bioconductor-delayedmatrixstats + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-delayedmatrixstats + 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/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0bc8b4b932138dfc95c27d2c84e87b006ad0ea06 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-delayedmatrixstats + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-delayedmatrixstats/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-deseq2/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-deseq2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6ce2c11f459604c91a335ffbaba16221d791a713 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deseq2/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-deseq2 via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-deseq2 -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-deseq2_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-deseq2_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-deseq2_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-deseq2/app/bioconductor-deseq2_server.py b/Biomni/mcp_generated/mcp_bioconductor-deseq2/app/bioconductor-deseq2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fb023716054df310f98f92617afc6b8110046f02 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deseq2/app/bioconductor-deseq2_server.py @@ -0,0 +1,299 @@ +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_deseq2' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def deseq2_differential_expression( + counts_path: str, + metadata_path: str, + design_formula: str, + output_results_path: str, + contrast_column: Optional[str] = None, + reference_level: Optional[str] = None, + treated_level: Optional[str] = None, + alpha: float = 0.05, + lfc_threshold: float = 0.0, + test_type: str = "Wald", + fit_type: str = "parametric", + reduced_formula: Optional[str] = None, + shrink_lfc: bool = True, + shrink_type: str = "apeglm" +): + """ + Performs differential expression analysis using DESeq2. + + Args: + counts_path: Path to the raw counts matrix (CSV/TSV, genes as rows, samples as columns). + metadata_path: Path to the sample metadata (CSV/TSV, samples as rows). + design_formula: The design formula (e.g., '~ condition' or '~ genotype + condition'). + output_results_path: Path where the results CSV will be saved. + contrast_column: The column in metadata to use for comparison. + reference_level: The baseline/control level in the contrast column. + treated_level: The treatment level in the contrast column. + alpha: Significance threshold (FDR). + lfc_threshold: Log2 fold change threshold for null hypothesis. + test_type: 'Wald' or 'LRT' (Likelihood Ratio Test). + fit_type: 'parametric', 'local', or 'mean'. + reduced_formula: Required if test_type is 'LRT' (e.g., '~ 1'). + shrink_lfc: Whether to apply Log2 Fold Change shrinkage. + shrink_type: Type of shrinkage estimator ('apeglm', 'ashr', or 'normal'). + """ + counts_p = Path(counts_path) + meta_p = Path(metadata_path) + out_p = Path(output_results_path) + + if not counts_p.exists(): + raise FileNotFoundError(f"Counts file not found: {counts_path}") + if not meta_p.exists(): + raise FileNotFoundError(f"Metadata file not found: {metadata_path}") + if test_type == "LRT" and not reduced_formula: + raise ValueError("reduced_formula is required when test_type is 'LRT'") + + # Construct R script + r_script = f""" + library(DESeq2) + + # Load data + counts <- read.csv("{counts_p}", row.names=1, check.names=FALSE) + coldata <- read.csv("{meta_p}", row.names=1, check.names=FALSE) + + # Ensure factors + for(col in colnames(coldata)) {{ + if(is.character(coldata[[col]])) coldata[[col]] <- as.factor(coldata[[col]]) + }} + + # Create DESeqDataSet + dds <- DESeqDataSetFromMatrix(countData=counts, colData=coldata, design=as.formula("{design_formula}")) + + # Run DESeq + if ("{test_type}" == "LRT") {{ + dds <- DESeq(dds, test="LRT", reduced=as.formula("{reduced_formula}"), fitType="{fit_type}") + }} else {{ + dds <- DESeq(dds, test="Wald", fitType="{fit_type}") + }} + + # Results extraction + if (!is.null("{contrast_column}") && !is.null("{reference_level}") && !is.null("{treated_level}")) {{ + res <- results(dds, contrast=c("{contrast_column}", "{treated_level}", "{reference_level}"), + alpha={alpha}, lfcThreshold={lfc_threshold}) + + if ({str(shrink_lfc).upper()}) {{ + # Shrinkage requires the coefficient name or contrast + # apeglm is preferred but requires 'coef' + res <- lfcShrink(dds, contrast=c("{contrast_column}", "{treated_level}", "{reference_level}"), + res=res, type="{shrink_type}") + }} + }} else {{ + res <- results(dds, alpha={alpha}, lfcThreshold={lfc_threshold}) + }} + + write.csv(as.data.frame(res), file="{out_p}") + """ + + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + 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(out_p)] + } + except subprocess.CalledProcessError as e: + return { + "error": "DESeq2 execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def deseq2_transform_counts( + counts_path: str, + metadata_path: str, + design_formula: str, + output_path: str, + method: str = "vst", + blind: bool = True +): + """ + Transforms count data using Variance Stabilizing Transformation (VST) or Regularized Log (rlog). + Useful for PCA, clustering, and visualization. + + Args: + counts_path: Path to raw counts matrix. + metadata_path: Path to sample metadata. + design_formula: Design formula (e.g., '~ condition'). + output_path: Path to save the transformed matrix CSV. + method: Transformation method ('vst' or 'rlog'). + blind: Whether to perform transformation in a blind manner (independent of design). + """ + counts_p = Path(counts_path) + meta_p = Path(metadata_path) + out_p = Path(output_path) + + if method not in ["vst", "rlog"]: + raise ValueError("Method must be 'vst' or 'rlog'") + + r_script = f""" + library(DESeq2) + counts <- read.csv("{counts_p}", row.names=1, check.names=FALSE) + coldata <- read.csv("{meta_p}", row.names=1, check.names=FALSE) + dds <- DESeqDataSetFromMatrix(countData=counts, colData=coldata, design=as.formula("{design_formula}")) + + if ("{method}" == "vst") {{ + transformed <- vst(dds, blind={str(blind).upper()}) + }} else {{ + transformed <- rlog(dds, blind={str(blind).upper()}) + }} + + write.csv(assay(transformed), file="{out_p}") + """ + + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + 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(out_p)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def deseq2_get_normalized_counts( + counts_path: str, + metadata_path: str, + design_formula: str, + output_path: str, + normalization_type: str = "ratio" +): + """ + Calculates size factors and returns normalized counts. + + Args: + counts_path: Path to raw counts matrix. + metadata_path: Path to sample metadata. + design_formula: Design formula. + output_path: Path to save normalized counts CSV. + normalization_type: Method for size factor estimation ('ratio', 'poscounts', 'iterate'). + """ + counts_p = Path(counts_path) + meta_p = Path(metadata_path) + out_p = Path(output_path) + + r_script = f""" + library(DESeq2) + counts <- read.csv("{counts_p}", row.names=1, check.names=FALSE) + coldata <- read.csv("{meta_p}", row.names=1, check.names=FALSE) + dds <- DESeqDataSetFromMatrix(countData=counts, colData=coldata, design=as.formula("{design_formula}")) + dds <- estimateSizeFactors(dds, type="{normalization_type}") + norm_counts <- counts(dds, normalized=TRUE) + write.csv(norm_counts, file="{out_p}") + """ + + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + 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(out_p)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def deseq2_plot_pca( + counts_path: str, + metadata_path: str, + design_formula: str, + intgroup_columns: List[str], + output_plot_path: str, + ntop: int = 500 +): + """ + Generates a PCA plot from DESeq2 transformed data. + + Args: + counts_path: Path to raw counts matrix. + metadata_path: Path to sample metadata. + design_formula: Design formula. + intgroup_columns: List of columns in metadata to use for grouping/coloring. + output_plot_path: Path to save the PCA plot (PDF or PNG). + ntop: Number of top variable genes to use for PCA. + """ + counts_p = Path(counts_path) + meta_p = Path(metadata_path) + out_p = Path(output_plot_path) + + intgroup_r = 'c("' + '","'.join(intgroup_columns) + '")' + + r_script = f""" + library(DESeq2) + library(ggplot2) + counts <- read.csv("{counts_p}", row.names=1, check.names=FALSE) + coldata <- read.csv("{meta_p}", row.names=1, check.names=FALSE) + dds <- DESeqDataSetFromMatrix(countData=counts, colData=coldata, design=as.formula("{design_formula}")) + vsd <- vst(dds, blind=TRUE) + + pca_data <- plotPCA(vsd, intgroup={intgroup_r}, ntop={ntop}, returnData=TRUE) + percentVar <- round(100 * attr(pca_data, "percentVar")) + + p <- ggplot(pca_data, aes(PC1, PC2, color={intgroup_columns[0]})) + + geom_point(size=3) + + xlab(paste0("PC1: ", percentVar[1], "% variance")) + + ylab(paste0("PC2: ", percentVar[2], "% variance")) + + coord_fixed() + + theme_bw() + + ggsave("{out_p}", plot=p, device="{out_p.suffix[1:]}") + """ + + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + 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(out_p)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + Path(tmp_path).unlink(missing_ok=True) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-deseq2/app/bioconductor-deseq2_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-deseq2/app/bioconductor-deseq2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bc727069044eadfcee6381fed0e748c38ee8c92b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deseq2/app/bioconductor-deseq2_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-deseq2/app/bioconductor-deseq2_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_deseq2' + + +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/Biomni/mcp_generated/mcp_bioconductor-deseq2/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-deseq2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deseq2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-deseq2/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-deseq2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..44fca83c313aca169d4a672bc807c812c843473f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deseq2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-deseq2: + build: . + image: mcp-bioconductor-deseq2:latest + container_name: mcp-bioconductor-deseq2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-deseq2 + 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/Biomni/mcp_generated/mcp_bioconductor-deseq2/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-deseq2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6e0fbe21343a08899e814e52812d2bb7e94709bd --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deseq2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-deseq2 + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-deseq2/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-deseq2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-deseq2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-despace/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-despace/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4da99cfeeacc2224edafb176136f0e1db9162e6c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-despace/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-despace via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-despace -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-despace_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-despace_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-despace_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-despace/app/bioconductor-despace_server.py b/Biomni/mcp_generated/mcp_bioconductor-despace/app/bioconductor-despace_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ebab6e701e77bf65c7cabacc484b11911f32ba8f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-despace/app/bioconductor-despace_server.py @@ -0,0 +1,303 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# MCP is a placeholder for the Model Context Protocol library. +# In a real environment, this would be: from mcp import tool +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_despace' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cluster_scrnaseq( + sc_object_path: Path, + output_rds_path: Path, + s_topics: int = 10, + n_top_genes: int = 2000, +) -> dict: + """ + Performs clustering on single-cell RNA-seq data as a preprocessing step for DeSpace. + + This tool wraps the `cluster_scRNAseq` function from the DeSpace R package. It takes a + Seurat object, identifies highly variable genes, performs dimensionality reduction, + and identifies clusters based on topic modeling. + + Args: + sc_object_path: Path to the input single-cell Seurat object (.rds file). + output_rds_path: Path to save the clustered single-cell Seurat object (.rds file). + s_topics: The number of topics (S) for topic modeling, representing putative cell types. + n_top_genes: Number of highly variable genes to use for clustering. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output file. + """ + # --- Input Validation --- + if not sc_object_path.is_file(): + raise FileNotFoundError(f"Input single-cell object not found: {sc_object_path}") + if not output_rds_path.parent.exists(): + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + logging.info(f"Created output directory: {output_rds_path.parent}") + + if s_topics <= 0: + raise ValueError("s_topics must be a positive integer.") + if n_top_genes <= 0: + raise ValueError("n_top_genes must be a positive integer.") + + # --- Command Construction --- + # This assumes a wrapper R script 'cluster_scrnaseq.R' is in the system's PATH. + cmd = [ + "Rscript", "cluster_scrnaseq.R", + "--sc_object_path", str(sc_object_path), + "--output_rds_path", str(output_rds_path), + "--s_topics", str(s_topics), + "--n_top_genes", str(n_top_genes), + ] + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + logging.info("Single-cell clustering completed successfully.") + except FileNotFoundError: + err_msg = "Error: 'Rscript' command not found. Please ensure R and the required wrapper scripts are in the 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"Single-cell clustering failed with exit code {e.returncode}.") + return {"command_executed": command_executed, "stdout": e.stdout, "stderr": e.stderr, "output_files": []} + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds_path)] + } + +@mcp.tool() +def cluster_sp_data( + sp_object_path: Path, + output_rds_path: Path, + resolution: float = 0.8, +) -> dict: + """ + Performs clustering on spatial transcriptomics data as a preprocessing step for DeSpace. + + This tool wraps the `cluster_sp_data` function from the DeSpace R package. It takes a + spatial Seurat object, normalizes the data, finds variable features, and performs + graph-based clustering. + + Args: + sp_object_path: Path to the input spatial Seurat object (.rds file). + output_rds_path: Path to save the clustered spatial Seurat object (.rds file). + resolution: Clustering resolution for the Louvain algorithm. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output file. + """ + # --- Input Validation --- + if not sp_object_path.is_file(): + raise FileNotFoundError(f"Input spatial object not found: {sp_object_path}") + if not output_rds_path.parent.exists(): + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + logging.info(f"Created output directory: {output_rds_path.parent}") + + if resolution <= 0.0: + raise ValueError("resolution must be a positive float.") + + # --- Command Construction --- + # This assumes a wrapper R script 'cluster_sp_data.R' is in the system's PATH. + cmd = [ + "Rscript", "cluster_sp_data.R", + "--sp_object_path", str(sp_object_path), + "--output_rds_path", str(output_rds_path), + "--resolution", str(resolution), + ] + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + logging.info("Spatial data clustering completed successfully.") + except FileNotFoundError: + err_msg = "Error: 'Rscript' command not found. Please ensure R and the required wrapper scripts are in the 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"Spatial data clustering failed with exit code {e.returncode}.") + return {"command_executed": command_executed, "stdout": e.stdout, "stderr": e.stderr, "output_files": []} + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds_path)] + } + +@mcp.tool() +def run_despace( + sc_object_path: Path, + sp_object_path: Path, + output_rds_path: Path, + sc_assay: str = "RNA", + sc_slot: str = "counts", + sp_assay: str = "Spatial", + sp_slot: str = "counts", + num_markers_sc: int = 10, + num_markers_sp: int = 10, + s_topics: int = 10, + n_top_genes: int = 2000, + resolution: float = 0.8, + sample_id: Optional[str] = None, + num_threads: int = 1, + save_model: bool = False, + model_path: Optional[Path] = None, +) -> dict: + """ + Runs the main DeSpace algorithm to integrate single-cell and spatial transcriptomics data. + + This tool wraps the `DeSpace` R function. It can perform clustering internally if not + already present in the input objects, or it can use pre-computed clusters. The main + output is a Seurat object with cell-type deconvolution results. + + Args: + sc_object_path: Path to the single-cell Seurat object (.rds file). + sp_object_path: Path to the spatial transcriptomics Seurat object (.rds file). + output_rds_path: Path to save the resulting Seurat object with DeSpace results. + sc_assay: Assay to use from the single-cell Seurat object. + sc_slot: Slot to use from the single-cell assay (e.g., 'counts', 'data'). + sp_assay: Assay to use from the spatial Seurat object. + sp_slot: Slot to use from the spatial assay (e.g., 'counts', 'data'). + num_markers_sc: Number of markers to use for each single-cell cluster. + num_markers_sp: Number of markers to use for each spatial cluster. + s_topics: The number of topics (S) for topic modeling, used if sc-data is not pre-clustered. + n_top_genes: Number of highly variable genes, used if sc-data is not pre-clustered. + resolution: Clustering resolution, used if sp-data is not pre-clustered. + sample_id: Optional identifier for the sample, used for saving the model. + num_threads: Number of parallel threads to use. + save_model: If True, save the trained DeSpace model. + model_path: Path to save the DeSpace model file. Required if save_model is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not sc_object_path.is_file(): + raise FileNotFoundError(f"Single-cell input file not found: {sc_object_path}") + if not sp_object_path.is_file(): + raise FileNotFoundError(f"Spatial input file not found: {sp_object_path}") + + if not output_rds_path.parent.exists(): + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + logging.info(f"Created output directory: {output_rds_path.parent}") + + if num_markers_sc <= 0: + raise ValueError("num_markers_sc must be a positive integer.") + if num_markers_sp <= 0: + raise ValueError("num_markers_sp must be a positive integer.") + if s_topics <= 0: + raise ValueError("s_topics must be a positive integer.") + if n_top_genes <= 0: + raise ValueError("n_top_genes must be a positive integer.") + if resolution <= 0.0: + raise ValueError("resolution must be a positive float.") + if num_threads <= 0: + raise ValueError("num_threads must be a positive integer.") + + if save_model: + if model_path is None: + raise ValueError("model_path must be provided when save_model is True.") + if not model_path.parent.exists(): + model_path.parent.mkdir(parents=True, exist_ok=True) + logging.info(f"Created model output directory: {model_path.parent}") + + # --- Command Construction --- + # This assumes a wrapper R script 'run_despace.R' is in the system's PATH. + cmd = [ + "Rscript", "run_despace.R", + "--sc_object_path", str(sc_object_path), + "--sp_object_path", str(sp_object_path), + "--output_rds_path", str(output_rds_path), + "--sc_assay", sc_assay, + "--sc_slot", sc_slot, + "--sp_assay", sp_assay, + "--sp_slot", sp_slot, + "--num_markers_sc", str(num_markers_sc), + "--num_markers_sp", str(num_markers_sp), + "--s_topics", str(s_topics), + "--n_top_genes", str(n_top_genes), + "--resolution", str(resolution), + "--num_threads", str(num_threads), + ] + + if sample_id: + cmd.extend(["--sample_id", sample_id]) + + if save_model and model_path: + cmd.append("--save_model") + cmd.extend(["--model_path", str(model_path)]) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + logging.info("DeSpace execution completed successfully.") + except FileNotFoundError: + err_msg = "Error: 'Rscript' command not found. Please ensure R and the required wrapper scripts are in the 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"DeSpace execution failed with exit code {e.returncode}.") + return {"command_executed": command_executed, "stdout": e.stdout, "stderr": e.stderr, "output_files": []} + + # --- Structured Result Return --- + output_files: List[str] = [str(output_rds_path)] + if save_model and model_path: + output_files.append(str(model_path)) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-despace/app/bioconductor-despace_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-despace/app/bioconductor-despace_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ab996f5409eb671a3d03e0d41f347214521533 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-despace/app/bioconductor-despace_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-despace/app/bioconductor-despace_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_despace' + + +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/Biomni/mcp_generated/mcp_bioconductor-despace/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-despace/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-despace/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-despace/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-despace/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a02735107b0381e3e0a06f2c081e776f2bd05b3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-despace/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-despace: + build: . + image: mcp-bioconductor-despace:latest + container_name: mcp-bioconductor-despace + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-despace + 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/Biomni/mcp_generated/mcp_bioconductor-despace/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-despace/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aa7dcfc187fbd6567c43123ac5cc15ac3a6a30d3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-despace/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-despace + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-despace/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-despace/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-despace/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-diffbind/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-diffbind/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..688e4b88373ed30f5a74d5f62ced57b363eb1fc3 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_server.py b/Biomni/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd61607c37bca9be1cf86268553917ec81b74c3 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-diffbind/app/bioconductor-diffbind_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5d9a62f8fdb2232066170a010012510be2613f3e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-diffbind/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-diffbind/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-diffbind/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-diffbind/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-diffbind/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..18b3fc5e962c25d0514a55227a62185efbc6e09a --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-diffbind/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-diffbind/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..839a0d08388f697b8b465c52c817fde4915186d0 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-diffbind/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-diffbind/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-diffbind/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-dino/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-dino/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e82559b1698fd13bbb4072e5206c349eeaab3da --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dino/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-dino via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dino -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-dino_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-dino_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-dino_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dino/app/bioconductor-dino_server.py b/Biomni/mcp_generated/mcp_bioconductor-dino/app/bioconductor-dino_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b088b5b2c0604a24c6a8f46ee102d6d321dea91 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dino/app/bioconductor-dino_server.py @@ -0,0 +1,203 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_dino' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def normalize_single_cell_data( + input_sce_path: Path, + output_sce_path: Path, + output_normalized_matrix_path: Optional[Path] = None, + seed: Optional[int] = None, + num_cores: Optional[int] = None, +) -> Dict[str, Any]: + """ + Normalizes single-cell mRNA sequencing data using the Bioconductor Dino package. + + This tool corrects for technical variation, particularly sequencing depth, + producing a matrix of corrected expression where the dependency between + sequencing depth and the full distribution of normalized expression is removed. + It is particularly useful for highly sparse datasets from UMI-based protocols. + + Args: + input_sce_path: Path to the input SingleCellExperiment R object file (.rds). + This file should contain raw count data. + output_sce_path: Path to save the output normalized SingleCellExperiment + R object file (.rds). + output_normalized_matrix_path: Optional path to save the normalized + expression matrix as a CSV file. If provided, + the normalized logcounts will be extracted + and written to this file. + seed: Optional integer seed for reproducibility of random processes + within the normalization. Must be a positive integer. + num_cores: Optional integer specifying the number of cores to use for + parallel processing. Must be a positive integer. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # 1. Input Validation + if not input_sce_path.is_file(): + raise ValueError(f"Input SingleCellExperiment file not found: {input_sce_path}") + if not input_sce_path.suffix == ".rds": + raise ValueError(f"Input file must be an .rds file, but got: {input_sce_path.suffix}") + + if output_sce_path.suffix != ".rds": + raise ValueError(f"Output SingleCellExperiment file must have a .rds extension, but got: {output_sce_path.suffix}") + output_sce_path.parent.mkdir(parents=True, exist_ok=True) + + if output_normalized_matrix_path: + if not output_normalized_matrix_path.suffix.lower() in [".csv", ".tsv"]: + raise ValueError(f"Output normalized matrix file must be .csv or .tsv, but got: {output_normalized_matrix_path.suffix}") + output_normalized_matrix_path.parent.mkdir(parents=True, exist_ok=True) + + if seed is not None: + if not isinstance(seed, int) or seed <= 0: + raise ValueError(f"Seed must be a positive integer, but got: {seed}") + + if num_cores is not None: + if not isinstance(num_cores, int) or num_cores <= 0: + raise ValueError(f"Number of cores must be a positive integer, but got: {num_cores}") + + # 2. File Path Handling and R Script Generation + r_script_content = f""" + library(Dino) + library(SingleCellExperiment) + library(BiocParallel) + library(Matrix) # For sparse matrix handling if needed + library(utils) # For write.csv/write.table + + # Set seed for reproducibility if provided + if (!is.null({seed})) {{ + set.seed({seed}) + }} + + # Set up parallel processing if num_cores is provided + if (!is.null({num_cores})) {{ + BPPARAM <- MulticoreParam(workers = {num_cores}) + }} else {{ + BPPARAM <- SerialParam() # Default to serial processing + }} + + # Load input SingleCellExperiment object + sce <- readRDS("{input_sce_path}") + + # Ensure 'counts' assay exists, as Dino typically operates on raw counts + if (!("counts" %in% assayNames(sce))) {{ + stop("Input SingleCellExperiment object must contain a 'counts' assay.") + }} + + # Perform Dino normalization + # The main normalization function in Dino is typically called 'DinoNormalize' + # or similar, operating on a SingleCellExperiment object. + # Assuming a function `DinoNormalize` exists and takes an SCE and BPPARAM. + # If the actual function name is different, this needs to be updated. + message("Starting Dino normalization...") + normalized_sce <- DinoNormalize(sce, BPPARAM = BPPARAM) + message("Dino normalization complete.") + + # Save the normalized SingleCellExperiment object + saveRDS(normalized_sce, "{output_sce_path}") + message("Normalized SingleCellExperiment object saved to {output_sce_path}") + + # Optionally save the normalized expression matrix + if (!is.null("{output_normalized_matrix_path}")) {{ + # Dino typically stores normalized data in 'logcounts' or a similar assay + if ("logcounts" %in% assayNames(normalized_sce)) {{ + normalized_matrix <- assay(normalized_sce, "logcounts") + }} else if ("normcounts" %in% assayNames(normalized_sce)) {{ + normalized_matrix <- assay(normalized_sce, "normcounts") + }} else {{ + stop("Normalized assay (e.g., 'logcounts' or 'normcounts') not found in the output SingleCellExperiment object.") + }} + + # Determine separator based on file extension + if (grepl("\\.csv$", "{output_normalized_matrix_path}", ignore.case = TRUE)) {{ + write.csv(as.matrix(normalized_matrix), "{output_normalized_matrix_path}", row.names = TRUE) + message("Normalized expression matrix saved to {output_normalized_matrix_path} as CSV.") + }} else if (grepl("\\.tsv$", "{output_normalized_matrix_path}", ignore.case = TRUE)) {{ + write.table(as.matrix(normalized_matrix), "{output_normalized_matrix_path}", sep = "\\t", quote = FALSE, row.names = TRUE) + message("Normalized expression matrix saved to {output_normalized_matrix_path} as TSV.") + }} else {{ + warning("Unsupported output format for normalized matrix. Skipping saving matrix.") + }} + }} + """ + + # Use a temporary file for the R script + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + command_executed = " ".join(command) + + stdout: str = "" + stderr: str = "" + output_files: List[str] = [] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + env=os.environ.copy() # Pass current environment to Rscript + ) + stdout = process.stdout + stderr = process.stderr + + if output_sce_path.is_file(): + output_files.append(str(output_sce_path)) + else: + raise FileNotFoundError(f"Expected output SCE file not found: {output_sce_path}") + + if output_normalized_matrix_path and output_normalized_matrix_path.is_file(): + output_files.append(str(output_normalized_matrix_path)) + + except subprocess.CalledProcessError as e: + stdout = e.stdout + stderr = e.stderr + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "error": f"R script failed with exit code {e.returncode}. See stderr for details.", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": "Rscript command not found. Is R installed and in your PATH?", + "error": "Rscript executable not found.", + "output_files": [], + } + finally: + # Clean up the temporary R script file + if r_script_path.exists(): + os.remove(r_script_path) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +# Note: The actual function name for normalization within the Dino package +# (e.g., `DinoNormalize`) is an assumption based on common Bioconductor practices +# and the package's description. If the specific function name or its parameters +# differ, the R script content within this Python function would need adjustment +# based on the official Dino package documentation (e.g., by running `help(package="Dino")` +# or `?DinoNormalize` in an R session after installing the package). + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-dino/app/bioconductor-dino_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-dino/app/bioconductor-dino_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cf39a17533e2eb8ad1c16ce71169d61fa09a92f8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dino/app/bioconductor-dino_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-dino/app/bioconductor-dino_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_dino' + + +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/Biomni/mcp_generated/mcp_bioconductor-dino/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-dino/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4fd86a2fb530e480a3be61540646fc99417a27c2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dino/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dino: + build: . + image: mcp-bioconductor-dino:latest + container_name: mcp-bioconductor-dino + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dino + 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/Biomni/mcp_generated/mcp_bioconductor-dino/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-dino/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d43d9329de36095538b4692008941e84a395ce3d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dino/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dino + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dino/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-dino/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dino/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b140ffebcc28a004b81e016332d3c19575de84d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/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-dirichletmultinomial via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dirichletmultinomial -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-dirichletmultinomial_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-dirichletmultinomial_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-dirichletmultinomial_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py new file mode 100644 index 0000000000000000000000000000000000000000..515dadf544f1918789d0a462eeeb649222d32ed5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py @@ -0,0 +1,225 @@ +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 imported. +def tool(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_dirichletmultinomial' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def dirichlet_multinomial_dmn( + count_matrix: Path, + k: int, + output_prefix: str, + b: int = 100, + verbose: bool = False, + seed: Optional[int] = None, +) -> dict: + """ + Fits a Dirichlet-Multinomial Mixture Model to count data. + + This tool serves as a wrapper for the dmn() function from the Bioconductor + R package 'DirichletMultinomial'. It takes a count matrix (samples x features) + and fits a model to identify a specified number of clusters (k). + + Tool Requirements: + - R installed and in the system's PATH. + - Rscript executable. + - The following R packages installed: 'DirichletMultinomial', 'readr', 'dplyr', 'tidyr'. + + Args: + count_matrix: Path to the input count matrix file. The file should be + tab-separated (TSV) with a header. The first column must + contain sample identifiers. + k: The number of mixture components (clusters) to fit. Must be an integer >= 2. + output_prefix: A string prefix for all output files. + b: The number of random starts for initialization. Corresponds to the 'B' + parameter in the dmn() function. Defaults to 100. + verbose: If True, enables verbose output from the R script. Defaults to False. + seed: An optional integer for setting the random seed in R for reproducibility. + Defaults to None. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of paths to the generated output files. + """ + # --- 1. Input and Parameter Validation --- + if not count_matrix.is_file(): + raise FileNotFoundError(f"Input file not found: {count_matrix}") + if k < 2: + raise ValueError("k (number of components) must be an integer of 2 or greater.") + if b <= 0: + raise ValueError("b (number of random starts) must be a positive integer.") + if not output_prefix: + raise ValueError("output_prefix cannot be empty.") + + # --- 2. R Script Generation --- + # Convert Python types to R-compatible string representations + verbose_str = "TRUE" if verbose else "FALSE" + seed_str = str(seed) if seed is not None else "NULL" + + # Using absolute paths is safer for subprocess execution + abs_count_matrix_path = count_matrix.resolve() + abs_output_prefix = Path(output_prefix).resolve() + + r_script_content = f""" + # Load required libraries + # Suppress startup messages for cleaner output + suppressPackageStartupMessages(library(DirichletMultinomial)) + suppressPackageStartupMessages(library(readr)) + suppressPackageStartupMessages(library(dplyr)) + suppressPackageStartupMessages(library(tidyr)) + suppressPackageStartupMessages(library(tibble)) + + # --- Parameters passed from Python --- + count_file <- "{abs_count_matrix_path}" + k_value <- {k} + b_value <- {b} + verbose_value <- {verbose_str} + output_prefix <- "{abs_output_prefix}" + seed_value <- {seed_str} + + # --- Main script --- + tryCatch({{ + # Set seed for reproducibility + if (!is.null(seed_value)) {{ + set.seed(seed_value) + }} + + # Load data + message("Reading count matrix from: ", count_file) + counts_df <- readr::read_tsv(count_file, col_types = cols()) + + # Convert first column to row names and the rest to a matrix + count_matrix <- as.matrix(counts_df[,-1]) + rownames(count_matrix) <- counts_df[[1]] + message("Dimensions of count matrix: ", nrow(count_matrix), " samples, ", ncol(count_matrix), " features.") + + # Validate that data is integer counts + if (!all(count_matrix == floor(count_matrix))) {{ + stop("Count matrix contains non-integer values. Please provide a raw count matrix.") + }} + + # Fit the Dirichlet-Multinomial model + message("Fitting DMN model with k=", k_value, "...") + fit <- dmn(count_matrix, k = k_value, B = b_value, verbose = verbose_value) + message("Model fitting complete.") + + # --- Save outputs --- + # Since we fit for a single k, extract that model directly + best_fit <- fit[[1]] + + # 1. Save the full model object + model_rds_path <- paste0(output_prefix, "_model.rds") + message("Saving model object to: ", model_rds_path) + saveRDS(fit, file = model_rds_path) + + # 2. Save goodness-of-fit statistics + gof_path <- paste0(output_prefix, "_gof.tsv") + message("Saving goodness-of-fit statistics to: ", gof_path) + gof_stats <- data.frame( + k = sapply(fit, n_components), + laplace = sapply(fit, laplace), + aic = sapply(fit, AIC), + bic = sapply(fit, BIC) + ) + readr::write_tsv(gof_stats, gof_path) + + # 3. Save mixture weights (proportions of each component) + mixture_weights_path <- paste0(output_prefix, "_mixture_weights.tsv") + message("Saving mixture weights to: ", mixture_weights_path) + mixture_weights_df <- as.data.frame(mixturewt(best_fit)) + colnames(mixture_weights_df) <- paste0("Component_", 1:ncol(mixture_weights_df)) + readr::write_tsv(mixture_weights_df, mixture_weights_path) + + # 4. Save cluster assignments for each sample + assignments_path <- paste0(output_prefix, "_cluster_assignments.tsv") + message("Saving cluster assignments to: ", assignments_path) + assignments <- data.frame( + sample_id = rownames(count_matrix), + best_component = apply(mixture(best_fit), 1, which.max) + ) + readr::write_tsv(assignments, assignments_path) + + # 5. Save component parameters (theta values for each feature) + theta_path <- paste0(output_prefix, "_component_parameters.tsv") + message("Saving component parameters (theta) to: ", theta_path) + theta_values <- as.data.frame(fitted(best_fit)) + colnames(theta_values) <- paste0("Component_", 1:ncol(theta_values)) + theta_values <- tibble::rownames_to_column(theta_values, var = "feature_id") + readr::write_tsv(theta_values, theta_path) + + message("Script finished successfully.") + }}, error = function(e) {{ + message("An error occurred in the R script: ", e$message) + quit(status = 1, save = "no") + }}) + """ + + # --- 3. Subprocess Execution --- + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_dmn.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(r_script_path)] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + except FileNotFoundError: + raise RuntimeError( + "Rscript not found. Please ensure R is installed and " + "'Rscript' is in your system's PATH." + ) + except subprocess.CalledProcessError as e: + error_message = ( + f"The R script failed with exit code {e.returncode}.\n" + f"This could be due to missing R packages (DirichletMultinomial, readr, dplyr, tidyr) " + f"or an issue with the input data format.\n" + f"Command: {command_str}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) from e + + # --- 4. Collect and Return Structured Output --- + output_files_generated: List[str] = [] + expected_suffixes = [ + "_model.rds", + "_gof.tsv", + "_mixture_weights.tsv", + "_cluster_assignments.tsv", + "_component_parameters.tsv", + ] + for suffix in expected_suffixes: + output_file = Path(f"{abs_output_prefix}{suffix}") + if output_file.exists(): + output_files_generated.append(str(output_file)) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_generated, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6d6dbaea423dcf99095e8fbe3e62577752a8d422 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_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-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_dirichletmultinomial' + + +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/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cb60f4389afe631128c813da64d85d6a4bc4d26e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dirichletmultinomial: + build: . + image: mcp-bioconductor-dirichletmultinomial:latest + container_name: mcp-bioconductor-dirichletmultinomial + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dirichletmultinomial + 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/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c361af9475e4996a82d48c65765813a91eb93eb4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dirichletmultinomial + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dirichletmultinomial/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-dnacopy/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..acfa6545a2f171d74ff198f82cd7aaba66db4989 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/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-dnacopy via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dnacopy -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-dnacopy_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-dnacopy_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-dnacopy_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0689beccafb1bc4991e8ebbb1daff93377fcf2ea --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py @@ -0,0 +1,208 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Optional, Union + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def tool(func): + """A dummy decorator to mimic @mcp.tool() for standalone execution.""" + return func + +@tool +def dnacopy_segment( + input_file: Path, + output_prefix: str, + sample_id_col: str, + chrom_col: str, + maploc_col: str, + data_col: str, + smooth_cna: bool = True, + make_plot: bool = True, + alpha: float = 0.01, + nperm: int = 10000, + p_method: str = "hybrid", + min_width: int = 2, + undo_splits: str = "sdundo", + undo_sd: float = 3.0, + trim: float = 0.025, + verbose: int = 1, +) -> Dict[str, Union[str, List[str]]]: + """ + Performs Circular Binary Segmentation (CBS) on copy number data using the R package DNAcopy. + + This tool takes a tab-delimited file containing genomic data (chromosome, position, log-ratio) + and segments it to identify regions of equal copy number. + + Args: + input_file: Path to the input tab-delimited data file. + output_prefix: Prefix for the output files (e.g., 'my_sample'). + sample_id_col: Name of the column containing sample identifiers. + chrom_col: Name of the column containing chromosome identifiers. + maploc_col: Name of the column containing genomic map locations (positions). + data_col: Name of the column containing the log2 ratio copy number data. + smooth_cna: If True, apply the `smooth.CNA` function before segmentation. Defaults to True. + make_plot: If True, generate a plot of the segmentation results as a PDF. Defaults to True. + alpha: Significance level to accept a change-point. Defaults to 0.01. + nperm: Number of permutations for `p.method='perm'`. Defaults to 10000. + p_method: Method to compute p-values. Must be 'hybrid' or 'perm'. Defaults to 'hybrid'. + min_width: The minimum number of markers for a segment. Defaults to 2. + undo_splits: Method for undoing splits. Must be 'none', 'prune', or 'sdundo'. Defaults to 'sdundo'. + undo_sd: The number of standard deviations for the undoing rule. Defaults to 3.0. + trim: Proportion of data to be trimmed for variance calculation. Defaults to 0.025. + verbose: Verbosity level (0, 1, or 2). Defaults to 1. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # --- 1. Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + p_method_choices = ["hybrid", "perm"] + if p_method not in p_method_choices: + raise ValueError(f"p_method must be one of {p_method_choices}, not '{p_method}'") + + undo_splits_choices = ["none", "prune", "sdundo"] + if undo_splits not in undo_splits_choices: + raise ValueError(f"undo_splits must be one of {undo_splits_choices}, not '{undo_splits}'") + + if not (0 < alpha < 1): + raise ValueError("alpha must be between 0 and 1.") + + if not (0 <= trim < 0.5): + raise ValueError("trim must be between 0 and 0.5.") + + if nperm <= 0: + raise ValueError("nperm must be a positive integer.") + + if min_width < 2: + raise ValueError("min_width must be an integer >= 2.") + + if verbose not in [0, 1, 2]: + raise ValueError("verbose must be 0, 1, or 2.") + + # --- 2. Define Output Paths --- + output_seg_file = Path(f"{output_prefix}.seg") + output_plot_file = Path(f"{output_prefix}.pdf") + output_files = [str(output_seg_file)] + if make_plot: + output_files.append(str(output_plot_file)) + + # --- 3. Generate R Script --- + # This script reads the data, creates a CNA object, optionally smooths it, + # runs segmentation, and writes the output. It also handles non-numeric + # chromosome names like 'X' and 'Y'. + r_script = f""" + # Load the library + library(DNAcopy) + + # Read the input data + cat("Reading input file: {input_file}\\n") + raw_data <- read.table("{input_file}", header=TRUE, sep="\\t", stringsAsFactors=FALSE, check.names=FALSE) + + # Ensure required columns exist + required_cols <- c("{sample_id_col}", "{chrom_col}", "{maploc_col}", "{data_col}") + if (!all(required_cols %in% colnames(raw_data))) {{ + stop("One or more required columns not found in the input file.") + }} + + # Pre-process chromosome column to handle non-numeric values (e.g., X, Y) + cat("Processing chromosome identifiers...\\n") + raw_data[["{chrom_col}"]] <- as.character(raw_data[["{chrom_col}"]]) + raw_data[["{chrom_col}"]][toupper(raw_data[["{chrom_col}"]]) == 'X'] <- 23 + raw_data[["{chrom_col}"]][toupper(raw_data[["{chrom_col}"]]) == 'Y'] <- 24 + raw_data[["{chrom_col}"]][toupper(raw_data[["{chrom_col}"]]) == 'MT'] <- 25 + raw_data[["{chrom_col}"]] <- suppressWarnings(as.numeric(raw_data[["{chrom_col}"]])) + + # Filter out rows with NA values in key columns after conversion + raw_data <- raw_data[ + !is.na(raw_data[["{chrom_col}"]]) & + !is.na(raw_data[["{maploc_col}"]]) & + !is.na(raw_data[["{data_col}"]]), + ] + + # Create CNA object + cat("Creating CNA object...\\n") + CNA.object <- CNA( + genomdat = raw_data[["{data_col}"]], + chrom = raw_data[["{chrom_col}"]], + maploc = raw_data[["{maploc_col}"]], + data.type = 'logratio', + sampleid = raw_data[["{sample_id_col}"]] + ) + + # Smooth the data if requested + target_object <- CNA.object + if ({str(smooth_cna).upper()}) {{ + cat("Smoothing CNA object...\\n") + target_object <- smooth.CNA(CNA.object) + }} + + # Perform segmentation + cat("Performing segmentation...\\n") + segmentation <- segment( + target_object, + alpha = {alpha}, + nperm = {nperm}, + p.method = "{p_method}", + min.width = {min_width}, + undo.splits = "{undo_splits}", + undo.SD = {undo_sd}, + trim = {trim}, + verbose = {verbose} + ) + + # Write segmentation output + cat("Writing segmentation output to {output_seg_file}\\n") + write.table(segmentation$output, file="{output_seg_file}", sep="\\t", quote=FALSE, row.names=FALSE) + + # Generate plot if requested + if ({str(make_plot).upper()}) {{ + cat("Generating plot at {output_plot_file}\\n") + pdf("{output_plot_file}") + plot(segmentation, plot.type="w") + dev.off() + }} + + cat("DNAcopy analysis complete.\\n") + """ + + # --- 4. Execute R Script --- + command = [] + 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] + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # Provide a more informative error message + error_message = ( + f"DNAcopy R script failed with exit code {e.returncode}.\n" + f"Command: {' '.join(command)}\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() + + # --- 5. Return Structured Output --- + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f09446bf36755c4c16c3fb912ce7e02d20e55469 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_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-dnacopy/app/bioconductor-dnacopy_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_dnacopy' + + +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/Biomni/mcp_generated/mcp_bioconductor-dnacopy/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-dnacopy/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2a3bc04cf7735b56b19adb7824aab027ad1edc38 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dnacopy: + build: . + image: mcp-bioconductor-dnacopy:latest + container_name: mcp-bioconductor-dnacopy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dnacopy + 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/Biomni/mcp_generated/mcp_bioconductor-dnacopy/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a899be3d3c4b68ef4f21429190feaaf5b44d4dbf --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dnacopy + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dnacopy/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dnacopy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-dose/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-dose/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..701e64e535c03274c35882af067c4460458a3eef --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dose/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-dose via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dose -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-dose_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-dose_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-dose_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dose/app/bioconductor-dose_server.py b/Biomni/mcp_generated/mcp_bioconductor-dose/app/bioconductor-dose_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6d59c1cb57f4b98d0e8202272870422c32e463e8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dose/app/bioconductor-dose_server.py @@ -0,0 +1,736 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, Literal, List +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +log = logging.getLogger(__name__) + +# Mock the mcp.tool decorator for standalone execution +class mcp: + def tool(func): + return func + +# Define a common type for p-value adjustment methods +PAdjustMethod = Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] + +@mcp.tool +def enrich_do( + gene_list_file: Path, + organism_db: str, + output_prefix: str, + key_type: str = "ENTREZID", + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: PAdjustMethod = "BH", + universe_file: Optional[Path] = None, + min_gssize: int = 10, + max_gssize: int = 500, + readable: bool = False, +) -> dict: + """ + Performs Disease Ontology (DO) enrichment analysis on a given gene list. + + This tool requires an R environment with 'DOSE', 'clusterProfiler', 'enrichplot', + and the specified organism database (e.g., 'org.Hs.eg.db') installed. + + Args: + gene_list_file: Path to a file containing a list of gene IDs, one per line. + organism_db: Name of the Bioconductor organism annotation package (e.g., "org.Hs.eg.db"). + output_prefix: Prefix for all output files (e.g., 'my_analysis/do_enrichment'). + key_type: The type of gene identifier in the input file (e.g., "ENTREZID", "SYMBOL", "ENSEMBL"). + pvalue_cutoff: Cutoff for p-value significance. + qvalue_cutoff: Cutoff for q-value (FDR) significance. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background gene IDs. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + readable: If True, maps gene IDs to gene symbols in the output. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not gene_list_file.is_file(): + raise FileNotFoundError(f"Gene list file not found: {gene_list_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if min_gssize < 0 or max_gssize < 0 or min_gssize > max_gssize: + raise ValueError("Invalid min_gssize or max_gssize.") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "dotplot": Path(f"{output_prefix}_dotplot.png"), + "cnetplot": Path(f"{output_prefix}_cnetplot.png"), + } + + r_script_content = f""" + # Load required libraries + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + + # Check if organism DB is installed, if not, stop with an error + if (!requireNamespace("{organism_db}", quietly = TRUE)) {{ + stop("Required organism database '{organism_db}' is not installed. Please install it from Bioconductor.", call. = FALSE) + }} + library({organism_db}, character.only = TRUE) + + # Read gene list + genes <- read.table("{gene_list_file.resolve()}", header = FALSE, stringsAsFactors = FALSE)$V1 + + # Read universe if provided + universe_genes <- NULL + if (!is.null("{universe_file}")) {{ + universe_genes <- read.table("{str(universe_file.resolve()) if universe_file else ''}", header = FALSE, stringsAsFactors = FALSE)$V1 + }} + + # Run enrichment analysis + edo <- enrichDO( + gene = genes, + OrgDb = {organism_db}, + keyType = "{key_type}", + ont = "DO", + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + universe = universe_genes, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + qvalueCutoff = {qvalue_cutoff}, + readable = {"TRUE" if readable else "FALSE"} + ) + + # Save results if any were found + if (!is.null(edo) && nrow(as.data.frame(edo)) > 0) {{ + write.csv(as.data.frame(edo), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + + # Generate and save plots + p1 <- dotplot(edo, showCategory=30) + ggsave(p1, filename="{output_files['dotplot'].resolve()}", width=10, height=8) + + # Cnetplot requires converting gene IDs if readable is TRUE + edo_plot <- if ("{readable}" == "TRUE") setReadable(edo, OrgDb = {organism_db}, keyType="{key_type}") else edo + p2 <- cnetplot(edo_plot, categorySize="pvalue") + ggsave(p2, filename="{output_files['cnetplot'].resolve()}", width=12, height=10) + + cat("Analysis complete. Results and plots saved.\\n") + }} else {{ + cat("No significant enrichment found.\\n") + # Create an empty results file to indicate completion + file.create("{output_files['results_table'].resolve()}") + }} + """ + + 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 + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # Clean up temporary file + Path(r_script_path).unlink() + + # Filter out non-existent files if no results were found + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + # Clean up temporary file + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def gse_do( + ranked_gene_list_file: Path, + organism_db: str, + output_prefix: str, + key_type: str = "ENTREZID", + n_permutations: int = 1000, + min_gssize: int = 10, + max_gssize: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: PAdjustMethod = "BH", + verbose: bool = True, + seed: bool = False, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on Disease Ontology (DO). + + This tool requires an R environment with 'DOSE', 'clusterProfiler', 'enrichplot', + and the specified organism database (e.g., 'org.Hs.eg.db') installed. + + Args: + ranked_gene_list_file: Path to a two-column file (GeneID, Score/FoldChange) without a header. + organism_db: Name of the Bioconductor organism annotation package (e.g., "org.Hs.eg.db"). + output_prefix: Prefix for all output files. + key_type: The type of gene identifier in the input file. + n_permutations: Number of permutations for GSEA. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + pvalue_cutoff: Cutoff for p-value significance. + p_adjust_method: Method for p-value adjustment. + verbose: If True, prints progress messages. + seed: If True, sets a random seed for reproducibility. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not ranked_gene_list_file.is_file(): + raise FileNotFoundError(f"Ranked gene list file not found: {ranked_gene_list_file}") + if n_permutations <= 0: + raise ValueError("Number of permutations must be positive.") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "gseaplot": Path(f"{output_prefix}_gseaplot.png"), + "ridgeplot": Path(f"{output_prefix}_ridgeplot.png"), + } + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + + if (!requireNamespace("{organism_db}", quietly = TRUE)) {{ + stop("Required organism database '{organism_db}' is not installed.", call. = FALSE) + }} + library({organism_db}, character.only = TRUE) + + # Read and prepare ranked gene list + df <- read.table("{ranked_gene_list_file.resolve()}", header = FALSE, col.names = c("ID", "Score")) + geneList <- df$Score + names(geneList) <- as.character(df$ID) + geneList <- sort(geneList, decreasing = TRUE) + + # Run GSEA + gse <- gseDO( + geneList = geneList, + OrgDb = {organism_db}, + keyType = "{key_type}", + nPerm = {n_permutations}, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"}, + seed = {"TRUE" if seed else "FALSE"} + ) + + if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{ + write.csv(as.data.frame(gse), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + + # Generate and save plots + # Get the top term ID for the GSEA plot + top_term_id <- as.data.frame(gse)[1, "ID"] + p1 <- gseaplot(gse, geneSetID = top_term_id, title = gse[top_term_id, "Description"]) + ggsave(p1, filename="{output_files['gseaplot'].resolve()}", width=10, height=8) + + p2 <- ridgeplot(gse) + ggsave(p2, filename="{output_files['ridgeplot'].resolve()}", width=12, height=10) + + cat("GSEA complete. Results and plots saved.\\n") + }} else {{ + cat("No significant GSEA results found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + 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 + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def enrich_ncg( + gene_list_file: Path, + output_prefix: str, + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: PAdjustMethod = "BH", + universe_file: Optional[Path] = None, + min_gssize: int = 10, + max_gssize: int = 500, + readable: bool = False, +) -> dict: + """ + Performs Network of Cancer Genes (NCG) enrichment analysis. + + This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed. + It uses built-in NCG data, so an organism DB is not required. Gene IDs must be Entrez IDs. + + Args: + gene_list_file: Path to a file containing a list of Entrez gene IDs, one per line. + output_prefix: Prefix for all output files. + pvalue_cutoff: Cutoff for p-value significance. + qvalue_cutoff: Cutoff for q-value (FDR) significance. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background gene IDs. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + readable: If True, maps gene IDs to gene symbols. Requires 'org.Hs.eg.db'. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not gene_list_file.is_file(): + raise FileNotFoundError(f"Gene list file not found: {gene_list_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "dotplot": Path(f"{output_prefix}_dotplot.png"), + } + + readable_setup = "" + if readable: + readable_setup = """ + if (!requireNamespace("org.Hs.eg.db", quietly = TRUE)) { + stop("The 'readable=TRUE' option requires 'org.Hs.eg.db'. Please install it from Bioconductor.", call. = FALSE) + } + library(org.Hs.eg.db) + """ + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + {readable_setup} + + genes <- read.table("{gene_list_file.resolve()}", header = FALSE, stringsAsFactors = FALSE)$V1 + + universe_genes <- NULL + if (!is.null("{universe_file}")) {{ + universe_genes <- read.table("{str(universe_file.resolve()) if universe_file else ''}", header = FALSE, stringsAsFactors = FALSE)$V1 + }} + + encg <- enrichNCG( + gene = genes, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + universe = universe_genes, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + qvalueCutoff = {qvalue_cutoff}, + readable = {"TRUE" if readable else "FALSE"} + ) + + if (!is.null(encg) && nrow(as.data.frame(encg)) > 0) {{ + write.csv(as.data.frame(encg), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + p1 <- dotplot(encg, showCategory=30) + ggsave(p1, filename="{output_files['dotplot'].resolve()}", width=10, height=8) + cat("NCG enrichment complete.\\n") + }} else {{ + cat("No significant NCG enrichment found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + 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 + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def gse_ncg( + ranked_gene_list_file: Path, + output_prefix: str, + n_permutations: int = 1000, + min_gssize: int = 10, + max_gssize: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: PAdjustMethod = "BH", + verbose: bool = True, + seed: bool = False, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on Network of Cancer Genes (NCG). + + This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed. + Gene IDs must be Entrez IDs. + + Args: + ranked_gene_list_file: Path to a two-column file (EntrezID, Score/FoldChange) without a header. + output_prefix: Prefix for all output files. + n_permutations: Number of permutations for GSEA. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + pvalue_cutoff: Cutoff for p-value significance. + p_adjust_method: Method for p-value adjustment. + verbose: If True, prints progress messages. + seed: If True, sets a random seed for reproducibility. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not ranked_gene_list_file.is_file(): + raise FileNotFoundError(f"Ranked gene list file not found: {ranked_gene_list_file}") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "ridgeplot": Path(f"{output_prefix}_ridgeplot.png"), + } + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + + df <- read.table("{ranked_gene_list_file.resolve()}", header = FALSE, col.names = c("ID", "Score")) + geneList <- df$Score + names(geneList) <- as.character(df$ID) + geneList <- sort(geneList, decreasing = TRUE) + + gse <- gseNCG( + geneList = geneList, + nPerm = {n_permutations}, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"}, + seed = {"TRUE" if seed else "FALSE"} + ) + + if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{ + write.csv(as.data.frame(gse), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + p1 <- ridgeplot(gse) + ggsave(p1, filename="{output_files['ridgeplot'].resolve()}", width=12, height=10) + cat("NCG GSEA complete.\\n") + }} else {{ + cat("No significant NCG GSEA results found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + 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 + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def enrich_dgn( + gene_list_file: Path, + output_prefix: str, + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: PAdjustMethod = "BH", + universe_file: Optional[Path] = None, + min_gssize: int = 10, + max_gssize: int = 500, + readable: bool = False, +) -> dict: + """ + Performs DisGeNET enrichment analysis. + + This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed. + Gene IDs must be Entrez IDs. + + Args: + gene_list_file: Path to a file containing a list of Entrez gene IDs, one per line. + output_prefix: Prefix for all output files. + pvalue_cutoff: Cutoff for p-value significance. + qvalue_cutoff: Cutoff for q-value (FDR) significance. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background gene IDs. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + readable: If True, maps gene IDs to gene symbols. Requires 'org.Hs.eg.db'. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not gene_list_file.is_file(): + raise FileNotFoundError(f"Gene list file not found: {gene_list_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "dotplot": Path(f"{output_prefix}_dotplot.png"), + } + + readable_setup = "" + if readable: + readable_setup = """ + if (!requireNamespace("org.Hs.eg.db", quietly = TRUE)) { + stop("The 'readable=TRUE' option requires 'org.Hs.eg.db'. Please install it from Bioconductor.", call. = FALSE) + } + library(org.Hs.eg.db) + """ + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + {readable_setup} + + genes <- read.table("{gene_list_file.resolve()}", header = FALSE, stringsAsFactors = FALSE)$V1 + + universe_genes <- NULL + if (!is.null("{universe_file}")) {{ + universe_genes <- read.table("{str(universe_file.resolve()) if universe_file else ''}", header = FALSE, stringsAsFactors = FALSE)$V1 + }} + + edgn <- enrichDGN( + gene = genes, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + universe = universe_genes, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + qvalueCutoff = {qvalue_cutoff}, + readable = {"TRUE" if readable else "FALSE"} + ) + + if (!is.null(edgn) && nrow(as.data.frame(edgn)) > 0) {{ + write.csv(as.data.frame(edgn), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + p1 <- dotplot(edgn, showCategory=30) + ggsave(p1, filename="{output_files['dotplot'].resolve()}", width=10, height=8) + cat("DisGeNET enrichment complete.\\n") + }} else {{ + cat("No significant DisGeNET enrichment found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + 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 + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def gse_dgn( + ranked_gene_list_file: Path, + output_prefix: str, + n_permutations: int = 1000, + min_gssize: int = 10, + max_gssize: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: PAdjustMethod = "BH", + verbose: bool = True, + seed: bool = False, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on DisGeNET. + + This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed. + Gene IDs must be Entrez IDs. + + Args: + ranked_gene_list_file: Path to a two-column file (EntrezID, Score/FoldChange) without a header. + output_prefix: Prefix for all output files. + n_permutations: Number of permutations for GSEA. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + pvalue_cutoff: Cutoff for p-value significance. + p_adjust_method: Method for p-value adjustment. + verbose: If True, prints progress messages. + seed: If True, sets a random seed for reproducibility. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not ranked_gene_list_file.is_file(): + raise FileNotFoundError(f"Ranked gene list file not found: {ranked_gene_list_file}") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "ridgeplot": Path(f"{output_prefix}_ridgeplot.png"), + } + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + + df <- read.table("{ranked_gene_list_file.resolve()}", header = FALSE, col.names = c("ID", "Score")) + geneList <- df$Score + names(geneList) <- as.character(df$ID) + geneList <- sort(geneList, decreasing = TRUE) + + gse <- gseDGN( + geneList = geneList, + nPerm = {n_permutations}, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"}, + seed = {"TRUE" if seed else "FALSE"} + ) + + if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{ + write.csv(as.data.frame(gse), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + p1 <- ridgeplot(gse) + ggsave(p1, filename="{output_files['ridgeplot'].resolve()}", width=12, height=10) + cat("DisGeNET GSEA complete.\\n") + }} else {{ + cat("No significant DisGeNET GSEA results found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + 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 + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dose/app/bioconductor-dose_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-dose/app/bioconductor-dose_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..befa28a6932c5e5293e673c6bceaec1c6c4c2a08 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dose/app/bioconductor-dose_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-dose/app/bioconductor-dose_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_dose' + + +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/Biomni/mcp_generated/mcp_bioconductor-dose/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-dose/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dose/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-dose/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-dose/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..376316817b1839f8e71282772f7841fad3c91011 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dose/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dose: + build: . + image: mcp-bioconductor-dose:latest + container_name: mcp-bioconductor-dose + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dose + 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/Biomni/mcp_generated/mcp_bioconductor-dose/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-dose/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c620138711796e54adfe97dd442b9b327e07163 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dose/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dose + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-dose/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-dose/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-dose/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-ebseq/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ebseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ebseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-edger/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-edger/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..afa6508a4a79e041e41e6dba488188175d2bf18b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-edger/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-edger via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-edger -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-edger_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-edger_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-edger_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_server.py b/Biomni/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a54a68420dd5092a56d6fb0567bcfad5c714dfad --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_server.py @@ -0,0 +1,291 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal + +# MCP decorator stub. In a real environment, this would be: +# from mcp import mcp +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def run_edger_glm( + counts_file: Path, + metadata_file: Path, + design_formula: str, + contrast: List[str], + output_prefix: str, + min_cpm: float = 1.0, + min_samples_fraction: float = 0.5, + norm_method: Literal["TMM", "TMMwsp", "RLE", "upperquartile", "none"] = "TMM", + estimate_disp_robust: bool = True, + glm_fit_robust: bool = True, + test_method: Literal["QLFTest", "LRT"] = "QLFTest", +) -> dict: + """ + Performs differential expression analysis using the edgeR GLM workflow. + + This tool is suitable for complex experimental designs (e.g., multiple factors, + batch effects, interactions) that can be specified with a design formula. + + Args: + counts_file: Path to the input counts matrix file (CSV format). + Rows should be genes and columns should be samples. + metadata_file: Path to the sample metadata file (CSV format). + Rows should be samples (matching counts_file columns) and + columns should be experimental factors. + design_formula: The design formula for the model matrix (e.g., "~ batch + condition"). + Must start with '~'. + contrast: A list of three strings defining the contrast to be tested: + [factor, level1, level2]. This tests level1 vs level2 for the given factor. + output_prefix: The prefix for the output results file. + min_cpm: The minimum counts-per-million (CPM) a gene must have to be considered + for filtering. Defaults to 1.0. + min_samples_fraction: The fraction of samples in the smallest group that must + meet the min_cpm threshold for a gene to be kept. Defaults to 0.5. + norm_method: Normalization method to be used. Defaults to "TMM". + estimate_disp_robust: Use robust estimation for dispersion. Defaults to True. + glm_fit_robust: Use robust estimation for GLM fitting. Defaults to True. + test_method: The statistical test to perform (Quasi-likelihood F-test or + Likelihood Ratio Test). Defaults to "QLFTest". + + Returns: + A dictionary containing the execution command, stdout, stderr, and output file paths. + """ + # --- Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not design_formula.startswith("~"): + raise ValueError("design_formula must start with '~'") + if len(contrast) != 3: + raise ValueError("contrast must be a list of three strings: [factor, level1, level2]") + if not (0 < min_samples_fraction <= 1): + raise ValueError("min_samples_fraction must be between 0 and 1") + + output_file = Path(f"{output_prefix}_edger_glm_results.csv") + + # --- R Script Generation --- + r_script_content = f""" + # Load libraries + library(edgeR) + options(warn=-1) + + # --- Parameters --- + counts_file <- "{counts_file.resolve()}" + metadata_file <- "{metadata_file.resolve()}" + output_file <- "{output_file.resolve()}" + design_formula_str <- "{design_formula}" + contrast_factor <- "{contrast[0]}" + contrast_level1 <- "{contrast[1]}" + contrast_level2 <- "{contrast[2]}" + min_cpm <- {min_cpm} + min_samples_fraction <- {min_samples_fraction} + norm_method <- "{norm_method}" + estimate_disp_robust_r <- {"TRUE" if estimate_disp_robust else "FALSE"} + glm_fit_robust_r <- {"TRUE" if glm_fit_robust else "FALSE"} + test_method <- "{test_method}" + + # --- Data Loading --- + counts <- read.csv(counts_file, row.names=1, check.names=FALSE) + metadata <- read.csv(metadata_file, row.names=1, check.names=FALSE) + + if (!all(colnames(counts) %in% rownames(metadata))) {{ + stop("Not all column names in counts_file are present as row names in metadata_file.") + }} + metadata <- metadata[colnames(counts), , drop=FALSE] + + # --- edgeR Workflow --- + dge <- DGEList(counts=counts, samples=metadata) + + # Filtering + design_for_filter <- model.matrix(as.formula(design_formula_str), data=dge$samples) + min_samples <- floor(min(colSums(design_for_filter)) * min_samples_fraction) + if (min_samples < 1) {{ min_samples <- 1 }} + cat(paste("Filtering: Keeping genes with >", min_cpm, "CPM in at least", min_samples, "samples.\\n")) + keep <- rowSums(cpm(dge) > min_cpm) >= min_samples + dge <- dge[keep, , keep.lib.sizes=FALSE] + cat(paste(sum(keep), "genes remaining after filtering.\\n")) + + # Normalization + dge <- calcNormFactors(dge, method=norm_method) + + # Design matrix + design <- model.matrix(as.formula(design_formula_str), data=dge$samples) + + # Check if contrast levels are valid + c1 <- paste0(contrast_factor, contrast_level1) + c2 <- paste0(contrast_factor, contrast_level2) + if (!c1 %in% colnames(design)) stop(paste("Contrast level", c1, "not found in design matrix columns:", paste(colnames(design), collapse=", "))) + if (!c2 %in% colnames(design)) stop(paste("Contrast level", c2, "not found in design matrix columns:", paste(colnames(design), collapse=", "))) + + # Estimate dispersion + dge <- estimateDisp(dge, design, robust=estimate_disp_robust_r) + + # Model fitting and testing + contrast_str <- paste0(c1, "-", c2) + contrast_arg <- makeContrasts(contrasts=contrast_str, levels=design) + + if (test_method == "QLFTest") {{ + fit <- glmQLFit(dge, design, robust=glm_fit_robust_r) + test <- glmQLFTest(fit, contrast=contrast_arg) + }} else if (test_method == "LRT") {{ + fit <- glmFit(dge, design, robust=glm_fit_robust_r) + test <- glmLRT(fit, contrast=contrast_arg) + }} else {{ + stop("Unsupported test method.") + }} + + results <- topTags(test, n=Inf)$table + write.csv(results, file=output_file, row.names=TRUE) + cat(paste("edgeR GLM analysis completed. Results saved to", output_file, "\\n")) + """ + + # --- Subprocess Execution --- + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return {"command_executed": command_executed, "stdout": "", "stderr": "Error: Rscript 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, "output_files": []} + finally: + Path(script_path).unlink() + + return {"command_executed": command_executed, "stdout": stdout, "stderr": stderr, "output_files": [str(output_file)] if output_file.exists() else []} + + +@mcp.tool +def run_edger_exact_test( + counts_file: Path, + metadata_file: Path, + group_column: str, + group1: str, + group2: str, + output_prefix: str, + min_cpm: float = 1.0, + min_samples_fraction: float = 0.7, + norm_method: Literal["TMM", "TMMwsp", "RLE", "upperquartile", "none"] = "TMM", + dispersion_method: Literal["common", "trended", "tagwise"] = "tagwise", +) -> dict: + """ + Performs DE analysis for a two-group comparison using edgeR's exact test. + + This tool is optimized for simple experiments comparing two groups (e.g., treatment vs. control). + + Args: + counts_file: Path to the input counts matrix file (CSV format). + metadata_file: Path to the sample metadata file (CSV format). + group_column: The name of the column in metadata_file that contains group information. + group1: The name of the first group (numerator in logFC, e.g., 'treatment'). + group2: The name of the second group (denominator in logFC, e.g., 'control'). + output_prefix: The prefix for the output results file. + min_cpm: The minimum counts-per-million (CPM) a gene must have. Defaults to 1.0. + min_samples_fraction: The fraction of samples in the smallest group that must + meet the min_cpm threshold for a gene to be kept. Defaults to 0.7. + norm_method: Normalization method to be used. Defaults to "TMM". + dispersion_method: The method for dispersion estimation. 'tagwise' is recommended. + Defaults to "tagwise". + + Returns: + A dictionary containing the execution command, stdout, stderr, and output file paths. + """ + # --- Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not (0 < min_samples_fraction <= 1): + raise ValueError("min_samples_fraction must be between 0 and 1") + + output_file = Path(f"{output_prefix}_edger_exact_test_results.csv") + + # --- R Script Generation --- + r_script_content = f""" + library(edgeR) + options(warn=-1) + + # --- Parameters --- + counts_file <- "{counts_file.resolve()}" + metadata_file <- "{metadata_file.resolve()}" + output_file <- "{output_file.resolve()}" + group_column <- "{group_column}" + group1 <- "{group1}" + group2 <- "{group2}" + min_cpm <- {min_cpm} + min_samples_fraction <- {min_samples_fraction} + norm_method <- "{norm_method}" + dispersion_method <- "{dispersion_method}" + + # --- Data Loading --- + counts <- read.csv(counts_file, row.names=1, check.names=FALSE) + metadata <- read.csv(metadata_file, row.names=1, check.names=FALSE) + + metadata_subset <- metadata[metadata[[group_column]] %in% c(group1, group2), ] + if (nrow(metadata_subset) == 0) stop("No samples found for the specified groups.") + counts_subset <- counts[, rownames(metadata_subset)] + + # --- edgeR Workflow --- + group <- factor(metadata_subset[[group_column]]) + dge <- DGEList(counts=counts_subset, group=group) + + # Filtering + min_samples <- floor(min(table(group)) * min_samples_fraction) + if (min_samples < 1) {{ min_samples <- 1 }} + cat(paste("Filtering: Keeping genes with >", min_cpm, "CPM in at least", min_samples, "samples.\\n")) + keep <- rowSums(cpm(dge) > min_cpm) >= min_samples + dge <- dge[keep, , keep.lib.sizes=FALSE] + cat(paste(sum(keep), "genes remaining after filtering.\\n")) + + # Normalization + dge <- calcNormFactors(dge, method=norm_method) + + # Estimate dispersion + if (dispersion_method == "common") {{ + dge <- estimateCommonDisp(dge) + }} else if (dispersion_method == "trended") {{ + dge <- estimateCommonDisp(dge) + dge <- estimateTrendedDisp(dge) + }} else {{ + dge <- estimateDisp(dge) + }} + + # Perform exact test (group1 vs group2) + et <- exactTest(dge, pair=c(group2, group1)) + + results <- topTags(et, n=Inf)$table + write.csv(results, file=output_file, row.names=TRUE) + cat(paste("edgeR exact test completed. Results saved to", output_file, "\\n")) + """ + + # --- Subprocess Execution --- + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return {"command_executed": command_executed, "stdout": "", "stderr": "Error: Rscript 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, "output_files": []} + finally: + Path(script_path).unlink() + + return {"command_executed": command_executed, "stdout": stdout, "stderr": stderr, "output_files": [str(output_file)] if output_file.exists() else []} \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8abe51678d0ce5daf6fea73656b83613c09ebd5c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_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-edger/app/bioconductor-edger_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_edger' + + +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/Biomni/mcp_generated/mcp_bioconductor-edger/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-edger/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-edger/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-edger/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-edger/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3c2d48e4be4ae96adc8e3d2a236e22da2a3d7e41 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-edger/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-edger: + build: . + image: mcp-bioconductor-edger:latest + container_name: mcp-bioconductor-edger + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-edger + 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/Biomni/mcp_generated/mcp_bioconductor-edger/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-edger/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6dc7924789c820fb39041415eb915f5b2f3558e6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-edger/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-edger + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-edger/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-edger/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-edger/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-ensembldb/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9b0f11efd1181364a6ae2124d61ec7bc886f56fb --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/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-ensembldb via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ensembldb -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-ensembldb_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-ensembldb_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-ensembldb_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b16aa3887d89f6af557937f4480a2a8aa12f8734 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py @@ -0,0 +1,433 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Assume mcp.tool is imported from a framework library +class mcp: + def tool(func): + return func + +def _run_r_script(r_script_content: str, args: List[str]) -> Dict[str, Any]: + """ + A helper function to execute an R script using Rscript, handling errors. + + This function requires that R and the required Bioconductor packages + (e.g., ensembldb, AnnotationFilter) are installed in the execution environment. + + Args: + r_script_content: A string containing the R code to execute. + args: A list of command-line arguments for the R script. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + + Raises: + RuntimeError: If Rscript is not found in the system's PATH. + subprocess.CalledProcessError: If the R script execution fails. + """ + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script_content) + + command = ["Rscript", str(script_path)] + args + + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + return { + "command_executed": " ".join(command), + "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"R script execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + # Re-raise with a more informative stderr + raise subprocess.CalledProcessError(e.returncode, e.cmd, output=e.stdout, stderr=error_message) + finally: + if 'script_path' in locals() and script_path.exists(): + script_path.unlink() + +@mcp.tool +def create_ensdb_from_gtf( + gtf_file: Path, + output_db: Path, + organism: str, + genome_version: str, + ensembl_version: str, +) -> Dict[str, Any]: + """ + Creates an EnsemblDB SQLite database from a GTF file. + + This tool wraps the `ensDbFromGtf` function from the R/Bioconductor + package 'ensembldb'. It requires R and the 'ensembldb' package to be + installed in the environment. + + Args: + gtf_file: Path to the input GTF file. + output_db: Path for the output SQLite database file. + organism: Name of the organism (e.g., 'Homo_sapiens'). + genome_version: Genome build version (e.g., 'GRCh38'). + ensembl_version: Ensembl release version (e.g., '104'). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + # Input validation + if not gtf_file.is_file(): + raise FileNotFoundError(f"Input GTF file not found: {gtf_file}") + if not output_db.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_db.parent}") + if not all([organism, genome_version, ensembl_version]): + raise ValueError("organism, genome_version, and ensembl_version must be non-empty strings.") + + r_script = textwrap.dedent(""" + library("ensembldb") + args <- commandArgs(trailingOnly = TRUE) + ensDbFromGtf( + gtf = args[1], + outfile = args[2], + organism = args[3], + genomeVersion = args[4], + version = args[5] + ) + """) + + args = [ + str(gtf_file), + str(output_db), + organism, + genome_version, + ensembl_version + ] + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_db)] + return result + +@mcp.tool +def create_ensdb_from_gff( + gff_file: Path, + output_db: Path, + organism: str, + genome_version: str, + ensembl_version: str, +) -> Dict[str, Any]: + """ + Creates an EnsemblDB SQLite database from a GFF3 file. + + This tool wraps the `ensDbFromGff` function from the R/Bioconductor + package 'ensembldb'. It requires R and the 'ensembldb' package to be + installed in the environment. + + Args: + gff_file: Path to the input GFF3 file. + output_db: Path for the output SQLite database file. + organism: Name of the organism (e.g., 'Homo_sapiens'). + genome_version: Genome build version (e.g., 'GRCh38'). + ensembl_version: Ensembl release version (e.g., '104'). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + # Input validation + if not gff_file.is_file(): + raise FileNotFoundError(f"Input GFF file not found: {gff_file}") + if not output_db.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_db.parent}") + if not all([organism, genome_version, ensembl_version]): + raise ValueError("organism, genome_version, and ensembl_version must be non-empty strings.") + + r_script = textwrap.dedent(""" + library("ensembldb") + args <- commandArgs(trailingOnly = TRUE) + ensDbFromGff( + gff = args[1], + outfile = args[2], + organism = args[3], + genomeVersion = args[4], + version = args[5] + ) + """) + + args = [ + str(gff_file), + str(output_db), + organism, + genome_version, + ensembl_version + ] + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_db)] + return result + +def _build_query_script(query_function: str, extra_r_code: str = "") -> str: + """Helper to generate the R script for various query types.""" + return textwrap.dedent(f""" + library("ensembldb") + library("AnnotationFilter") + + args <- commandArgs(trailingOnly = TRUE) + + parse_args <- function(args) {{ + params <- list() + for (arg in args) {{ + if (startsWith(arg, "--")) {{ + parts <- strsplit(substring(arg, 3), "=", fixed = TRUE)[[1]] + key <- parts[1] + value <- if (length(parts) > 1) parts[2] else TRUE + params[[key]] <- value + }} + }} + return(params) + }} + + params <- parse_args(args) + + if (is.null(params$db) || is.null(params$outfile)) {{ + stop("Both --db and --outfile arguments are required.") + }} + + edb <- EnsDb(params$db) + + filter_list <- list() + if (!is.null(params$filter_gene_id)) {{ + filter_list <- c(filter_list, GeneIdFilter(params$filter_gene_id)) + }} + if (!is.null(params$filter_gene_biotype)) {{ + filter_list <- c(filter_list, GeneBiotypeFilter(params$filter_gene_biotype)) + }} + if (!is.null(params$filter_seq_name)) {{ + filter_list <- c(filter_list, SeqNameFilter(params$filter_seq_name)) + }} + if (!is.null(params$filter_tx_id)) {{ + filter_list <- c(filter_list, TxIdFilter(params$filter_tx_id)) + }} + if (!is.null(params$filter_tx_biotype)) {{ + filter_list <- c(filter_list, TxBiotypeFilter(params$filter_tx_biotype)) + }} + if (!is.null(params$filter_exon_id)) {{ + filter_list <- c(filter_list, ExonIdFilter(params$filter_exon_id)) + }} + + final_filter <- NULL + if (length(filter_list) > 0) {{ + final_filter <- AnnotationFilterList(filter_list, logicOp = "&") + }} + + {extra_r_code} + + results <- {query_function}(edb, filter = final_filter) + + write.table(as.data.frame(results), file = params$outfile, sep = "\t", row.names = FALSE, quote = FALSE) + + cat("Successfully wrote query results to:", params$outfile, "\n") + """) + +@mcp.tool +def query_genes( + db_file: Path, + output_tsv: Path, + filter_gene_id: Optional[str] = None, + filter_gene_biotype: Optional[str] = None, + filter_seq_name: Optional[str] = None, +) -> Dict[str, Any]: + """ + Queries gene information from an EnsemblDB SQLite database. + + This tool wraps the `genes` function from 'ensembldb'. It requires R, + 'ensembldb', and 'AnnotationFilter' packages. + + Args: + db_file: Path to the input EnsemblDB SQLite file. + output_tsv: Path for the output TSV file. + filter_gene_id: Optional filter by Ensembl gene ID. + filter_gene_biotype: Optional filter by gene biotype (e.g., 'protein_coding'). + filter_seq_name: Optional filter by sequence/chromosome name (e.g., 'X'). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if not output_tsv.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}") + + r_script = _build_query_script("genes") + + args = [f"--db={db_file}", f"--outfile={output_tsv}"] + if filter_gene_id: + args.append(f"--filter_gene_id={filter_gene_id}") + if filter_gene_biotype: + args.append(f"--filter_gene_biotype={filter_gene_biotype}") + if filter_seq_name: + args.append(f"--filter_seq_name={filter_seq_name}") + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_tsv)] + return result + +@mcp.tool +def query_transcripts( + db_file: Path, + output_tsv: Path, + filter_gene_id: Optional[str] = None, + filter_tx_id: Optional[str] = None, + filter_tx_biotype: Optional[str] = None, +) -> Dict[str, Any]: + """ + Queries transcript information from an EnsemblDB SQLite database. + + This tool wraps the `transcripts` function from 'ensembldb'. It requires R, + 'ensembldb', and 'AnnotationFilter' packages. + + Args: + db_file: Path to the input EnsemblDB SQLite file. + output_tsv: Path for the output TSV file. + filter_gene_id: Optional filter by Ensembl gene ID. + filter_tx_id: Optional filter by Ensembl transcript ID. + filter_tx_biotype: Optional filter by transcript biotype (e.g., 'protein_coding'). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if not output_tsv.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}") + + r_script = _build_query_script("transcripts") + + args = [f"--db={db_file}", f"--outfile={output_tsv}"] + if filter_gene_id: + args.append(f"--filter_gene_id={filter_gene_id}") + if filter_tx_id: + args.append(f"--filter_tx_id={filter_tx_id}") + if filter_tx_biotype: + args.append(f"--filter_tx_biotype={filter_tx_biotype}") + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_tsv)] + return result + +@mcp.tool +def query_exons( + db_file: Path, + output_tsv: Path, + filter_gene_id: Optional[str] = None, + filter_tx_id: Optional[str] = None, + filter_exon_id: Optional[str] = None, +) -> Dict[str, Any]: + """ + Queries exon information from an EnsemblDB SQLite database. + + This tool wraps the `exons` function from 'ensembldb'. It requires R, + 'ensembldb', and 'AnnotationFilter' packages. + + Args: + db_file: Path to the input EnsemblDB SQLite file. + output_tsv: Path for the output TSV file. + filter_gene_id: Optional filter by Ensembl gene ID. + filter_tx_id: Optional filter by Ensembl transcript ID. + filter_exon_id: Optional filter by Ensembl exon ID. + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if not output_tsv.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}") + + r_script = _build_query_script("exons") + + args = [f"--db={db_file}", f"--outfile={output_tsv}"] + if filter_gene_id: + args.append(f"--filter_gene_id={filter_gene_id}") + if filter_tx_id: + args.append(f"--filter_tx_id={filter_tx_id}") + if filter_exon_id: + args.append(f"--filter_exon_id={filter_exon_id}") + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_tsv)] + return result + +@mcp.tool +def query_promoters( + db_file: Path, + output_tsv: Path, + upstream: int = 2000, + downstream: int = 200, + filter_gene_id: Optional[str] = None, + filter_tx_id: Optional[str] = None, +) -> Dict[str, Any]: + """ + Extracts promoter regions for transcripts from an EnsemblDB. + + This tool wraps the `promoters` function from 'ensembldb'. It requires R, + 'ensembldb', and 'AnnotationFilter' packages. + + Args: + db_file: Path to the input EnsemblDB SQLite file. + output_tsv: Path for the output TSV file. + upstream: The number of bases upstream of the TSS to include. + downstream: The number of bases downstream of the TSS to include. + filter_gene_id: Optional filter by Ensembl gene ID. + filter_tx_id: Optional filter by Ensembl transcript ID. + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if not output_tsv.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}") + if upstream < 0 or downstream < 0: + raise ValueError("upstream and downstream values must be non-negative.") + + # The 'promoters' function takes upstream/downstream as direct arguments, + # so we modify the R script generation slightly. + extra_r_code = textwrap.dedent(f""" + up <- as.numeric(params$upstream) + down <- as.numeric(params$downstream) + results <- promoters(edb, upstream = up, downstream = down, filter = final_filter) + """) + + # We remove the final `results <- ...` line from the base template + base_script = _build_query_script("", extra_r_code) + + args = [ + f"--db={db_file}", + f"--outfile={output_tsv}", + f"--upstream={upstream}", + f"--downstream={downstream}" + ] + if filter_gene_id: + args.append(f"--filter_gene_id={filter_gene_id}") + if filter_tx_id: + args.append(f"--filter_tx_id={filter_tx_id}") + + result = _run_r_script(base_script, args) + result["output_files"] = [str(output_tsv)] + return result \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..67a1b108df2ac14e8925596faa0a1a32cdc4fa6a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_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-ensembldb/app/bioconductor-ensembldb_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_ensembldb' + + +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/Biomni/mcp_generated/mcp_bioconductor-ensembldb/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-ensembldb/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..fa827e40424fd2e2a65cbddc7f4cf3a3492f6067 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ensembldb: + build: . + image: mcp-bioconductor-ensembldb:latest + container_name: mcp-bioconductor-ensembldb + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ensembldb + 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/Biomni/mcp_generated/mcp_bioconductor-ensembldb/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..62a1c11177e8cff952ab7e45ef6a86420acc5fff --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ensembldb + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ensembldb/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ensembldb/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-erma/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-erma/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1f7b43050805f6bea8ccb79abf39b082b62f9ad5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-erma/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-erma via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-erma -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-erma_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-erma_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-erma_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-erma/app/bioconductor-erma_server.py b/Biomni/mcp_generated/mcp_bioconductor-erma/app/bioconductor-erma_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc6e10255c5255707cc4fdfdfd58264f485c6a8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-erma/app/bioconductor-erma_server.py @@ -0,0 +1,116 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Optional + +# Configure basic logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# 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(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_erma' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_erma_script( + script_path: Path, + output_dir: Path, + args: Optional[List[str]] = None, +): + """ + Executes a user-provided R script in an environment with bioconductor-erma. + + The 'bioconductor-erma' package is an R library for epigenomic data analysis + and does not provide a direct command-line interface. This tool serves as a + generic wrapper to execute R scripts that utilize the 'erma' library. The + user's script is responsible for implementing the analysis logic and writing + any output files to the specified directory. + + Args: + script_path: The path to the R script to be executed. + output_dir: The path to the directory where the R script is expected to + write its output files. This directory will be created if it + does not exist. + args: An optional list of command-line arguments to be passed to the + R script. + """ + # 1. Input Validation + if not script_path.is_file(): + raise FileNotFoundError(f"The specified R script does not exist: {script_path}") + + # 2. File Path Handling + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + logging.error(f"Failed to create output directory {output_dir}: {e}") + raise + + # 3. Command Construction + command = ["Rscript", "--vanilla", str(script_path)] + if args: + command.extend([str(arg) for arg in args]) + + command_executed = " ".join(command) + logging.info(f"Executing command: {command_executed}") + + # 4. Subprocess Execution and Error Handling + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=output_dir, # Execute the script from the output directory + ) + stdout = result.stdout + stderr = result.stderr + logging.info("R script executed successfully.") + + 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) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_message, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + logging.error(f"R script failed with exit code {e.returncode}.") + logging.error(f"STDOUT: {e.stdout}") + logging.error(f"STDERR: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 5. Structured Result Return + try: + output_files = [str(f) for f in output_dir.iterdir() if f.is_file()] + except OSError as e: + logging.error(f"Error listing output files in {output_dir}: {e}") + # Append this error to stderr to inform the user about the issue + stderr += f"\n[MCP Wrapper Error] Could not list output files: {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/Biomni/mcp_generated/mcp_bioconductor-erma/app/bioconductor-erma_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-erma/app/bioconductor-erma_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e31a98746165b03bf8eca2876ec3c91e84c9051c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-erma/app/bioconductor-erma_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-erma/app/bioconductor-erma_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_erma' + + +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/Biomni/mcp_generated/mcp_bioconductor-erma/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-erma/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-erma/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-erma/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-erma/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..782d3f8e2e0c9fa5dcda40aff6c86fe72ffa05ae --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-erma/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-erma: + build: . + image: mcp-bioconductor-erma:latest + container_name: mcp-bioconductor-erma + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-erma + 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/Biomni/mcp_generated/mcp_bioconductor-erma/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-erma/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e6edd0dc0eba1149262c0edeed5f97fce8950fde --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-erma/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-erma + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-erma/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-erma/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-erma/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-escher/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-escher/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..058e2e690efb46b0d54a80923d71a0f11fec4ddc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-escher/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-escher via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-escher -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-escher_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-escher_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-escher_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-escher/app/bioconductor-escher_server.py b/Biomni/mcp_generated/mcp_bioconductor-escher/app/bioconductor-escher_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8f16db287ba4c33707592189c6ead92040062753 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-escher/app/bioconductor-escher_server.py @@ -0,0 +1,287 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP-decorated functions for the 'escher' command-line tool. +# Note: This implementation is for the Python 'escher' package, which provides a +# command-line interface. The 'bioconductor-escher' package is an R wrapper +# and does not have a corresponding command-line tool. It is assumed the +# Python tool was the intended target. + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_escher' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def escher_convert( + input_files: List[Path], + output: Optional[Path] = None, + format: Optional[str] = None, +): + """ + Converts Escher maps (JSON) to SVG or PNG formats. + + This tool wraps the 'escher convert' command. + + Args: + input_files: A list of one or more Escher map files (JSON) to convert. + output: The output file or directory. If not provided, output is saved + next to the input files. If multiple inputs are given, this must + be a directory. + format: The output format ('svg' or 'png'). Overrides the output file + extension. Defaults to 'svg' if not determinable from output path. + """ + # Input validation + if not input_files: + raise ValueError("At least one input 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}") + + if format and format not in ["svg", "png"]: + raise ValueError("Invalid format. Must be 'svg' or 'png'.") + + if len(input_files) > 1 and output and output.is_file(): + raise ValueError( + "When multiple input files are provided, the output path must be a directory, not a file." + ) + + command = ["escher", "convert"] + command.extend(["--input", *[str(p) for p in input_files]]) + + output_format = "svg" + if format: + command.extend(["--format", format]) + output_format = format + elif output and output.suffix in [".svg", ".png"]: + output_format = output.suffix[1:] + + output_paths = [] + if output: + command.extend(["--output", str(output)]) + # Check if output is intended to be a directory + if output.is_dir() or (len(input_files) > 1) or (not output.suffix): + output.mkdir(parents=True, exist_ok=True) + for in_file in input_files: + output_paths.append(output / f"{in_file.stem}.{output_format}") + else: + # Output is a file + output.parent.mkdir(parents=True, exist_ok=True) + output_paths.append(output) + else: + # No output specified, save next to input + for in_file in input_files: + output_paths.append(in_file.with_suffix(f".{output_format}")) + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(p) for p in output_paths if p.exists()], + } + except FileNotFoundError: + raise RuntimeError( + "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH." + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + +@mcp.tool() +def escher_clear_cache(): + """ + Clears the Escher cache of downloaded maps and models. + + This tool wraps the 'escher clear-cache' command. + """ + command = ["escher", "clear-cache"] + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError( + "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH." + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + } + + +@mcp.tool() +def escher_run( + port: int = 7778, + host: str = "127.0.0.1", + no_cache: bool = False, + timeout: int = 30, +): + """ + Runs a new Escher server. + + Warning: This command starts a long-running server process. The 'timeout' + parameter is used to terminate the server after a specified duration. + This tool is primarily for interactive use and may have limited utility + in an automated MCP environment. The --no-browser flag is always used. + + Args: + port: The port to run the server on. + host: The host for the server. + no_cache: If True, do not cache Escher resources. + timeout: The maximum time in seconds to run the server before terminating. + """ + if timeout <= 0: + raise ValueError("Timeout must be a positive integer.") + + command = ["escher", "run", "--no-browser"] + command.extend(["--port", str(port)]) + command.extend(["--host", host]) + if no_cache: + command.append("--no-cache") + + try: + process = subprocess.run( + command, capture_output=True, text=True, timeout=timeout + ) + # This block is unlikely to be reached as the server runs indefinitely + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError( + "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH." + ) + except subprocess.TimeoutExpired as e: + # This is the expected outcome for this tool in an MCP environment + return { + "command_executed": " ".join(command), + "stdout": e.stdout or "", + "stderr": e.stderr or f"Process terminated after {timeout}s timeout.", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + } + + +@mcp.tool() +def escher_launch( + map_name: Optional[str] = None, + map_json: Optional[Path] = None, + model_name: Optional[str] = None, + model_json: Optional[Path] = None, + port: int = 7779, + host: str = "127.0.0.1", + no_cache: bool = False, + never_ask_before_quit: bool = False, + timeout: int = 30, +): + """ + Launches an Escher instance in a server, optionally loading a map/model. + + Warning: This command starts a long-running server process. The 'timeout' + parameter is used to terminate the server after a specified duration. + This tool is primarily for interactive use and may have limited utility + in an automated MCP environment. The --no-browser flag is always used. + + Args: + map_name: The name of the map to load from the Escher server. + map_json: A local JSON file for the map. + model_name: The name of the model to load from the Escher server. + model_json: A local JSON file for the model. + port: The port to run the server on. + host: The host for the server. + no_cache: If True, do not cache Escher resources. + never_ask_before_quit: If True, never ask "Are you sure you want to quit?". + timeout: The maximum time in seconds to run the server before terminating. + """ + # Input validation + if map_name and map_json: + raise ValueError("'map_name' and 'map_json' are mutually exclusive.") + if model_name and model_json: + raise ValueError("'model_name' and 'model_json' are mutually exclusive.") + if map_json and not map_json.is_file(): + raise FileNotFoundError(f"Map JSON file not found: {map_json}") + if model_json and not model_json.is_file(): + raise FileNotFoundError(f"Model JSON file not found: {model_json}") + if timeout <= 0: + raise ValueError("Timeout must be a positive integer.") + + command = ["escher", "launch", "--no-browser"] + + if map_name: + command.extend(["--map_name", map_name]) + if map_json: + command.extend(["--map_json", str(map_json)]) + if model_name: + command.extend(["--model_name", model_name]) + if model_json: + command.extend(["--model_json", str(model_json)]) + + command.extend(["--port", str(port)]) + command.extend(["--host", host]) + + if no_cache: + command.append("--no-cache") + if never_ask_before_quit: + command.append("--never_ask_before_quit") + + try: + process = subprocess.run( + command, capture_output=True, text=True, timeout=timeout + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError( + "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH." + ) + except subprocess.TimeoutExpired as e: + # This is the expected outcome for this tool in an MCP environment + return { + "command_executed": " ".join(command), + "stdout": e.stdout or "", + "stderr": e.stderr or f"Process terminated after {timeout}s timeout.", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-escher/app/bioconductor-escher_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-escher/app/bioconductor-escher_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..743535470a4c4107256dea9309cc4b650421068e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-escher/app/bioconductor-escher_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-escher/app/bioconductor-escher_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_escher' + + +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/Biomni/mcp_generated/mcp_bioconductor-escher/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-escher/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-escher/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-escher/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-escher/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..de7a0181d2217e0800a6feab0783313d926346ec --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-escher/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-escher: + build: . + image: mcp-bioconductor-escher:latest + container_name: mcp-bioconductor-escher + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-escher + 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/Biomni/mcp_generated/mcp_bioconductor-escher/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-escher/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33e3ee7e3a9ca4625e9cc78d2ba5d7a00c40015d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-escher/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-escher + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-escher/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-escher/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-escher/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8efe558b37798abdb85fea94e1317a5793f49e90 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/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-experimentsubset via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-experimentsubset -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-experimentsubset_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-experimentsubset_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-experimentsubset_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ff38c3c8341a70661b2b13c828baafe6ef9b60 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py @@ -0,0 +1,186 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': mcp_tool_placeholder}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_experimentsubset' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def manage_experiment_subset( + input_rds: Path, + output_rds: Path, + subset_name: str = "mcp_subset", + row_subset: Optional[str] = None, + col_subset: Optional[str] = None, + row_subset_file: Optional[Path] = None, + col_subset_file: Optional[Path] = None, +) -> Dict[str, any]: + """ + Provides a command-line interface to the R/Bioconductor 'ExperimentSubset' package. + + This tool subsets a Bioconductor experiment object (e.g., SummarizedExperiment, + SingleCellExperiment) stored in an RDS file based on provided row (e.g., genes) + or column (e.g., cells) identifiers. + + Args: + input_rds: Path to the input RDS file containing a Bioconductor experiment object. + output_rds: Path to save the output subsetted RDS file. + subset_name: A name to assign to the created subset. + row_subset: A comma-separated string of row names to include in the subset. + col_subset: A comma-separated string of column names to include in the subset. + row_subset_file: Path to a file containing row names to include (one per line). + col_subset_file: Path to a file containing column names to include (one per line). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + + if row_subset and row_subset_file: + raise ValueError("Cannot specify both 'row_subset' and 'row_subset_file'.") + + if col_subset and col_subset_file: + raise ValueError("Cannot specify both 'col_subset' and 'col_subset_file'.") + + if not any([row_subset, col_subset, row_subset_file, col_subset_file]): + raise ValueError("At least one subsetting criterion must be provided " + "('row_subset', 'col_subset', 'row_subset_file', or 'col_subset_file').") + + if not output_rds.parent.exists(): + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_content = f""" + # Load required libraries + if (!require("optparse", quietly = TRUE)) install.packages("optparse", repos = "http://cran.us.r-project.org") + if (!require("ExperimentSubset", quietly = TRUE)) {{ + if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos = "http://cran.us.r-project.org") + BiocManager::install("ExperimentSubset", update=FALSE) + }} + library(optparse) + library(ExperimentSubset) + + # Define and parse command-line options + option_list <- list( + make_option(c("-i", "--input"), type="character", help="Input RDS file path"), + make_option(c("-o", "--output"), type="character", help="Output RDS file path"), + make_option(c("-n", "--name"), type="character", default="mcp_subset", help="Name for the subset"), + make_option(c("-r", "--rows"), type="character", default=NULL, help="Comma-separated row names"), + make_option(c("-c", "--cols"), type="character", default=NULL, help="Comma-separated column names"), + make_option(c("--row_file"), type="character", default=NULL, help="File with row names"), + make_option(c("--col_file"), type="character", default=NULL, help="File with column names") + ) + + opt_parser <- OptionParser(option_list=option_list) + opt <- parse_args(opt_parser) + + if (is.null(opt$input) || is.null(opt$output)) {{ + print_help(opt_parser) + stop("Input and output files must be supplied.", call.=FALSE) + }} + + # Load the experiment object + cat("Loading input RDS file:", opt$input, "\\n") + exp_obj <- readRDS(opt$input) + + # Create ExperimentSubset object + es <- ExperimentSubset(exp_obj) + + # Determine row and column subsets + row_indices <- NULL + if (!is.null(opt$rows)) {{ + row_indices <- trimws(strsplit(opt$rows, ",")[[1]]) + }} else if (!is.null(opt$row_file)) {{ + row_indices <- readLines(opt$row_file) + }} + + col_indices <- NULL + if (!is.null(opt$cols)) {{ + col_indices <- trimws(strsplit(opt$cols, ",")[[1]]) + }} else if (!is.null(opt$col_file)) {{ + col_indices <- readLines(opt$col_file) + }} + + # Create the subset using the subsetData function + cat("Creating subset '", opt$name, "'...\\n", sep="") + es <- subsetData(es, subsetName = opt$name, rows = row_indices, cols = col_indices) + + # Retrieve the actual subsetted object from the container + subset_obj <- getSubset(es, subsetName = opt$name) + + # Save the subsetted object + cat("Saving subsetted object to:", opt$output, "\\n") + saveRDS(subset_obj, file = opt$output) + + cat("Successfully created subset.\\n") + """ + + # --- Subprocess Execution --- + cmd: List[str] = [] + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = [ + "Rscript", r_script_path, + "--input", str(input_rds), + "--output", str(output_rds), + "--name", subset_name + ] + + if row_subset: + cmd.extend(["--rows", row_subset]) + if col_subset: + cmd.extend(["--cols", col_subset]) + if row_subset_file: + cmd.extend(["--row_file", str(row_subset_file)]) + if col_subset_file: + cmd.extend(["--col_file", str(col_subset_file)]) + + 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_rds)] + } + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + # Clean up the temporary R script + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ae87527afb42101280e6c6d561d87f319ca7c0d6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_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-experimentsubset/app/bioconductor-experimentsubset_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_experimentsubset' + + +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/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..14db9f06094e56cfbc89047242ced0ca6d097862 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-experimentsubset: + build: . + image: mcp-bioconductor-experimentsubset:latest + container_name: mcp-bioconductor-experimentsubset + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-experimentsubset + 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/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0522c599fba65423c66bcf93f421921e6df214cf --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-experimentsubset + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-experimentsubset/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-fgsea/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-fgsea/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3f58f161cd9693a95e4de36814275152fecf9f5d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-fgsea/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-fgsea via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-fgsea -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-fgsea_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-fgsea_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-fgsea_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py b/Biomni/mcp_generated/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dc6a101c05d024954b5ebd6419a895049b97690d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py @@ -0,0 +1,429 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# This is a dummy decorator for development. +# In a real MCP environment, 'mcp' would be an imported module. +class MCP: + def tool(self): + def decorator(f): + return f + return decorator +mcp = MCP() + +R_DEPENDENCIES_NOTE = """ +NOTE: This tool requires R to be installed and in the system's PATH. +It also requires the following R packages to be installed: +- BiocManager +- fgsea (from Bioconductor) +- data.table +- argparse +- ggplot2 +- grid +You can install them in R with: +install.packages(c("data.table", "argparse", "ggplot2")) +if (!require("BiocManager", quietly = TRUE)) + install.packages("BiocManager") +BiocManager::install("fgsea") +""" + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_fgsea' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def fgsea_run( + pathways_file: Path, + stats_file: Path, + min_size: int = 1, + max_size: Optional[int] = None, + eps: float = 1e-10, + score_type: str = "std", + n_proc: int = 0, + gsea_param: float = 1.0, + n_perm_simple: int = 1000, + abs_eps: Optional[float] = None, + seed: int = 42, +) -> dict: + """ + Runs Fast Gene Set Enrichment Analysis (fgsea). + + This tool performs GSEA using the fgsea R package. It requires a pathways file + in GMT format and a file with pre-ranked gene-level statistics. The stats + file must be a two-column TSV/CSV with no header, containing gene IDs in the + first column and numeric stats in the second. + + Args: + pathways_file: Path to the pathways file in GMT format. + stats_file: Path to the gene-level stats file (2-column, no header). + min_size: Minimal size of a pathway to be considered. + max_size: Maximal size of a pathway to be considered. + eps: Boundary for calculating p-values. + score_type: Type of score for multilevel GSEA ('std', 'pos', 'neg'). + n_proc: Number of processors to use. 0 means automatic detection. + gsea_param: GSEA parameter (enrichment score weight). + n_perm_simple: Number of permutations for fgseaSimple. + abs_eps: Absolute epsilon for p-value calculation. + seed: Random seed for reproducibility. + + Returns: + A dictionary containing the execution command, stdout, stderr, and + a path to the resulting TSV file. + """ + # --- Input Validation --- + if not pathways_file.is_file(): + raise FileNotFoundError(f"Pathways file not found: {pathways_file}") + if not stats_file.is_file(): + raise FileNotFoundError(f"Stats file not found: {stats_file}") + + if min_size < 0: + raise ValueError("min_size must be a non-negative integer.") + if max_size is not None and max_size < min_size: + raise ValueError("max_size must be greater than or equal to min_size.") + if eps <= 0: + raise ValueError("eps must be a positive float.") + if score_type not in ["std", "pos", "neg"]: + raise ValueError("score_type must be one of 'std', 'pos', or 'neg'.") + if n_proc < 0: + raise ValueError("n_proc must be a non-negative integer.") + if n_perm_simple <= 0: + raise ValueError("n_perm_simple must be a positive integer.") + if abs_eps is not None and abs_eps <= 0: + raise ValueError("abs_eps must be a positive float if provided.") + + # --- R Script Definition --- + r_script_content = """ +#!/usr/bin/env Rscript +library(argparse) +library(fgsea) +library(data.table) + +parser <- ArgumentParser(description="Run fgsea analysis") +parser$add_argument("--pathways", type="character", required=TRUE) +parser$add_argument("--stats", type="character", required=TRUE) +parser$add_argument("--output", type="character", required=TRUE) +parser$add_argument("--minSize", type="integer", default=1) +parser$add_argument("--maxSize", type="integer", default=NULL) +parser$add_argument("--eps", type="double", default=1e-10) +parser$add_argument("--scoreType", type="character", default="std", choices=c("std", "pos", "neg")) +parser$add_argument("--nproc", type="integer", default=0) +parser$add_argument("--gseaParam", type="double", default=1.0) +parser$add_argument("--nPermSimple", type="integer", default=1000) +parser$add_argument("--absEps", type="double", default=NULL) +parser$add_argument("--seed", type="integer", default=42) +args <- parser$parse_args() + +set.seed(args$seed) + +pathways <- gmtPathways(args$pathways) + +stats_df <- fread(args$stats, header=FALSE) +if (ncol(stats_df) != 2) { + stop("Stats file must have exactly two columns (gene, stat) with no header.") +} +stats <- setNames(stats_df[[2]], stats_df[[1]]) +stats <- stats[!is.na(stats)] +stats <- sort(stats, decreasing=TRUE) + +maxSize <- if (is.null(args$maxSize)) Inf else args$maxSize + +fgseaRes <- fgsea( + pathways = pathways, + stats = stats, + minSize = args$minSize, + maxSize = maxSize, + eps = args$eps, + scoreType = args$scoreType, + nproc = args$nproc, + gseaParam = args$gseaParam, + nPermSimple = args$nPermSimple, + absEps = args$absEps +) + +fwrite(fgseaRes, file=args$output, sep="\\t", quote=FALSE, row.names=FALSE) +cat("fgsea analysis completed successfully.\\n") + """ + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "run_fgsea.R" + r_script_path.write_text(r_script_content) + + output_file = temp_path / "fgsea_results.tsv" + + cmd = [ + "Rscript", str(r_script_path), + "--pathways", str(pathways_file.resolve()), + "--stats", str(stats_file.resolve()), + "--output", str(output_file.resolve()), + "--minSize", str(min_size), + "--eps", str(eps), + "--scoreType", score_type, + "--nproc", str(n_proc), + "--gseaParam", str(gsea_param), + "--nPermSimple", str(n_perm_simple), + "--seed", str(seed), + ] + + if max_size is not None: + cmd.extend(["--maxSize", str(max_size)]) + if abs_eps is not None: + cmd.extend(["--absEps", str(abs_eps)]) + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + except FileNotFoundError: + raise RuntimeError(f"Rscript not found. Please ensure R is installed and in your PATH. {R_DEPENDENCIES_NOTE}") + except subprocess.CalledProcessError as e: + error_message = ( + f"fgsea execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}\n" + f"{R_DEPENDENCIES_NOTE}" + ) + raise RuntimeError(error_message) from e + + # --- Structured Result Return --- + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"results_table": str(output_file)} + } + +@mcp.tool() +def fgsea_plot_enrichment( + pathways_file: Path, + stats_file: Path, + pathway_name: str, + gsea_param: float = 1.0, +) -> dict: + """ + Plots the GSEA enrichment score profile for a specific pathway. + + Args: + pathways_file: Path to the pathways file in GMT format. + stats_file: Path to the gene-level stats file (2-column, no header). + pathway_name: Name of the specific pathway to plot. + gsea_param: GSEA parameter (enrichment score weight). + + Returns: + A dictionary containing the execution command, stdout, stderr, and + a path to the resulting PDF plot. + """ + # --- Input Validation --- + if not pathways_file.is_file(): + raise FileNotFoundError(f"Pathways file not found: {pathways_file}") + if not stats_file.is_file(): + raise FileNotFoundError(f"Stats file not found: {stats_file}") + if not pathway_name: + raise ValueError("pathway_name cannot be empty.") + + # --- R Script Definition --- + r_script_content = """ +#!/usr/bin/env Rscript +library(argparse) +library(fgsea) +library(data.table) +library(ggplot2) + +parser <- ArgumentParser(description="Plot fgsea enrichment score") +parser$add_argument("--pathways", type="character", required=TRUE) +parser$add_argument("--stats", type="character", required=TRUE) +parser$add_argument("--pathway_name", type="character", required=TRUE) +parser$add_argument("--output", type="character", required=TRUE) +parser$add_argument("--gseaParam", type="double", default=1.0) +args <- parser$parse_args() + +pathways <- gmtPathways(args$pathways) +stats_df <- fread(args$stats, header=FALSE) +if (ncol(stats_df) != 2) { + stop("Stats file must have exactly two columns (gene, stat) with no header.") +} +stats <- setNames(stats_df[[2]], stats_df[[1]]) +stats <- stats[!is.na(stats)] + +if (!args$pathway_name %in% names(pathways)) { + stop(paste("Pathway '", args$pathway_name, "' not found in the pathways file.", sep="")) +} +selected_pathway <- pathways[[args$pathway_name]] + +p <- plotEnrichment(pathway=selected_pathway, stats=stats, gseaParam=args$gseaParam) + + labs(title=args$pathway_name) + +ggsave(args$output, plot=p, device="pdf") +cat("Enrichment plot saved to", args$output, "\\n") + """ + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "plot_enrichment.R" + r_script_path.write_text(r_script_content) + + safe_pathway_name = "".join(c for c in pathway_name if c.isalnum() or c in ('_', '-')).rstrip() + output_plot_file = temp_path / f"enrichment_plot_{safe_pathway_name}.pdf" + + cmd = [ + "Rscript", str(r_script_path), + "--pathways", str(pathways_file.resolve()), + "--stats", str(stats_file.resolve()), + "--pathway_name", pathway_name, + "--output", str(output_plot_file.resolve()), + "--gseaParam", str(gsea_param), + ] + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + except FileNotFoundError: + raise RuntimeError(f"Rscript not found. Please ensure R is installed and in your PATH. {R_DEPENDENCIES_NOTE}") + except subprocess.CalledProcessError as e: + error_message = ( + f"fgsea plot enrichment failed with return code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}\n" + f"{R_DEPENDENCIES_NOTE}" + ) + raise RuntimeError(error_message) from e + + # --- Structured Result Return --- + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"enrichment_plot": str(output_plot_file)} + } + +@mcp.tool() +def fgsea_plot_gsea_table( + pathways_file: Path, + stats_file: Path, + fgsea_results_file: Path, + top_n: int = 10, + gsea_param: float = 1.0, +) -> dict: + """ + Plots a table of top GSEA results. + + Args: + pathways_file: Path to the pathways file in GMT format. + stats_file: Path to the gene-level stats file (2-column, no header). + fgsea_results_file: Path to the results TSV from a previous fgsea_run. + top_n: Number of top pathways (both up- and down-regulated) to plot. + gsea_param: GSEA parameter (enrichment score weight). + + Returns: + A dictionary containing the execution command, stdout, stderr, and + a path to the resulting PDF plot. + """ + # --- Input Validation --- + if not pathways_file.is_file(): + raise FileNotFoundError(f"Pathways file not found: {pathways_file}") + if not stats_file.is_file(): + raise FileNotFoundError(f"Stats file not found: {stats_file}") + if not fgsea_results_file.is_file(): + raise FileNotFoundError(f"fgsea results file not found: {fgsea_results_file}") + if top_n <= 0: + raise ValueError("top_n must be a positive integer.") + + # --- R Script Definition --- + r_script_content = """ +#!/usr/bin/env Rscript +library(argparse) +library(fgsea) +library(data.table) +library(grid) + +parser <- ArgumentParser(description="Plot fgsea results table") +parser$add_argument("--pathways", type="character", required=TRUE) +parser$add_argument("--stats", type="character", required=TRUE) +parser$add_argument("--results", type="character", required=TRUE) +parser$add_argument("--output", type="character", required=TRUE) +parser$add_argument("--top_n", type="integer", default=10) +parser$add_argument("--gseaParam", type="double", default=1.0) +args <- parser$parse_args() + +pathways <- gmtPathways(args$pathways) +stats_df <- fread(args$stats, header=FALSE) +if (ncol(stats_df) != 2) { + stop("Stats file must have exactly two columns (gene, stat) with no header.") +} +stats <- setNames(stats_df[[2]], stats_df[[1]]) +stats <- stats[!is.na(stats)] +fgseaRes <- fread(args$results) + +topPathwaysUp <- fgseaRes[ES > 0][head(order(pval), n=args$top_n), pathway] +topPathwaysDown <- fgseaRes[ES < 0][head(order(pval), n=args$top_n), pathway] +topPathways <- c(topPathwaysUp, rev(topPathwaysDown)) + +if (length(topPathways) == 0) { + stop("No significant pathways found to plot.") +} + +p <- plotGseaTable( + pathways = pathways[topPathways], + stats = stats, + fgseaRes = fgseaRes, + gseaParam = args$gseaParam +) + +pdf(args$output, width=10, height=max(2, 0.5 * length(topPathways))) +grid::grid.draw(p) +dev.off() + +cat("GSEA table plot saved to", args$output, "\\n") + """ + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "plot_gsea_table.R" + r_script_path.write_text(r_script_content) + + output_plot_file = temp_path / "gsea_table_plot.pdf" + + cmd = [ + "Rscript", str(r_script_path), + "--pathways", str(pathways_file.resolve()), + "--stats", str(stats_file.resolve()), + "--results", str(fgsea_results_file.resolve()), + "--output", str(output_plot_file.resolve()), + "--top_n", str(top_n), + "--gseaParam", str(gsea_param), + ] + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + except FileNotFoundError: + raise RuntimeError(f"Rscript not found. Please ensure R is installed and in your PATH. {R_DEPENDENCIES_NOTE}") + except subprocess.CalledProcessError as e: + error_message = ( + f"fgsea plot table failed with return code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}\n" + f"{R_DEPENDENCIES_NOTE}" + ) + raise RuntimeError(error_message) from e + + # --- Structured Result Return --- + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"gsea_table_plot": str(output_plot_file)} + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-fgsea/app/bioconductor-fgsea_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-fgsea/app/bioconductor-fgsea_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a4acdc1ef0e08213e7f38b4c95cd161037ba62a3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-fgsea/app/bioconductor-fgsea_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-fgsea/app/bioconductor-fgsea_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_fgsea' + + +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/Biomni/mcp_generated/mcp_bioconductor-fgsea/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-fgsea/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-fgsea/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-fgsea/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-fgsea/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d9e0484b15b6a435468866e3995fb77b3dacdd6b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-fgsea/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-fgsea: + build: . + image: mcp-bioconductor-fgsea:latest + container_name: mcp-bioconductor-fgsea + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-fgsea + 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/Biomni/mcp_generated/mcp_bioconductor-fgsea/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-fgsea/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..110d3aced27b25d56e28db04a1eba7d50ffa67ba --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-fgsea/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-fgsea + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-fgsea/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-fgsea/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-fgsea/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-genefilter/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-genefilter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dc85663f20f55f0012a7e7ede03831c347bd098c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genefilter/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-genefilter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genefilter -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-genefilter_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-genefilter_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-genefilter_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py b/Biomni/mcp_generated/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..63f36db3be307a8eded744c36c4199d3e8268690 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py @@ -0,0 +1,319 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# Mock decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def genefilter_nsfilter( + expression_data: Path, + output_prefix: str, + feature_data: Optional[Path] = None, + require_entrez: bool = False, + require_symbol: bool = False, + remove_dup_entrez: bool = True, + var_func: str = "IQR", + var_filter: bool = True, + var_cutoff: float = 0.5, + var_by_quantile: bool = True, +) -> dict: + """ + Performs non-specific filtering of genes using the nsFilter function. + + This tool wraps the nsFilter function from the R genefilter package. It is designed + to remove genes/probes that are unlikely to be informative, such as those with low + variance across samples or those lacking proper annotation. + + Args: + expression_data: Path to the input expression data file (CSV format). + Rows should be genes and columns should be samples. + The first column should contain gene identifiers. + output_prefix: Prefix for the output files. + feature_data: Optional path to a feature data file (CSV format) with annotations. + The first column must match the gene identifiers in expression_data. + require_entrez: If True, requires features to have an Entrez Gene ID. + require_symbol: If True, requires features to have a gene symbol. + remove_dup_entrez: If True, removes duplicated Entrez IDs. + var_func: The function to calculate variance ('IQR', 'sd', 'mad'). + var_filter: If True, applies the variance filter. + var_cutoff: The quantile cutoff for variance. + var_by_quantile: If True, the var.cutoff is treated as a quantile; otherwise, + it's a fixed threshold. + + Returns: + A dictionary containing the command executed, stdout, stderr, and paths to + the filtered expression data and the filter summary. + """ + # Input validation + if not expression_data.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_data}") + if feature_data and not feature_data.is_file(): + raise FileNotFoundError(f"Feature data file not found: {feature_data}") + if var_func not in ["IQR", "sd", "mad"]: + raise ValueError("var_func must be one of 'IQR', 'sd', or 'mad'.") + + output_filtered_eset = Path(f"{output_prefix}_filtered_expression.csv") + output_filter_stats = Path(f"{output_prefix}_filter_stats.csv") + + r_script_content = f""" + # Load necessary libraries + library(genefilter) + library(Biobase) + + # Read data + exprs_data <- as.matrix(read.csv("{expression_data}", row.names=1, check.names=FALSE)) + + # Create a minimal ExpressionSet object + eset <- ExpressionSet(assayData=exprs_data) + + # Add feature data if provided + if (!is.null("{feature_data}")) {{ + pdata <- read.csv("{feature_data}", row.names=1, check.names=FALSE) + # Ensure order matches + pdata <- pdata[rownames(exprs(eset)), , drop=FALSE] + phenoData(eset) <- new("AnnotatedDataFrame", data=pdata) + }} + + # Perform non-specific filtering + # Note: require.entrez and require.symbol need corresponding columns in featureData + # We will simulate this if not present for the logic to run + if (is.null(fvarLabels(eset))) {{ + fvarLabels(eset) <- "ID" + }} + if ({str(require_entrez).upper()} && !("EntrezId" %in% fvarLabels(eset))) {{ + fData(eset)$EntrezId <- rownames(fData(eset)) + }} + if ({str(require_symbol).upper()} && !("Symbol" %in% fvarLabels(eset))) {{ + fData(eset)$Symbol <- rownames(fData(eset)) + }} + + filter_result <- nsFilter( + eset, + require.entrez = {str(require_entrez).upper()}, + require.symbol = {str(require_symbol).upper()}, + remove.dupEntrez = {str(remove_dup_entrez).upper()}, + var.func = {var_func}, + var.filter = {str(var_filter).upper()}, + var.cutoff = {var_cutoff}, + varByQuantile = {str(var_by_quantile).upper()} + ) + + # Save results + write.csv(exprs(filter_result$eset), file="{output_filtered_eset}") + write.csv(as.data.frame(filter_result$filter.log), file="{output_filter_stats}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + 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, + "output_files": { + "filtered_expression": str(output_filtered_eset), + "filter_stats": str(output_filter_stats) + } + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() + + +@mcp.tool +def genefilter_rowttests( + expression_data: Path, + factor_levels: str, + output_file: Path, + t_statistic_only: bool = False, +) -> dict: + """ + Computes two-sample t-tests for each row of a matrix-like object. + + This tool wraps the rowttests function from the R genefilter package. It is useful + for differential expression analysis between two groups. + + Args: + expression_data: Path to the input expression data file (CSV format). + Rows should be genes, columns should be samples. + The first column should contain gene identifiers. + factor_levels: A comma-separated string defining the two groups for the t-test. + Example: "groupA,groupA,groupB,groupB,groupA". The number of + elements must match the number of columns in expression_data. + output_file: Path to save the t-test results (CSV format). + t_statistic_only: If True, returns only the t-statistic for each row. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to + the output results file. + """ + # Input validation + if not expression_data.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_data}") + + r_script_content = f""" + library(genefilter) + + # Read data + data_matrix <- as.matrix(read.csv("{expression_data}", row.names=1, check.names=FALSE)) + + # Create factor from input string + factor_vector <- c({factor_levels}) + if (length(factor_vector) != ncol(data_matrix)) {{ + stop("The number of factor levels must match the number of columns in the expression data.") + }} + fac <- factor(factor_vector) + if (nlevels(fac) != 2) {{ + stop("The factor must have exactly two levels (groups) for a two-sample t-test.") + }} + + # Perform row-wise t-tests + ttest_results <- rowttests(data_matrix, fac, tstatOnly={str(t_statistic_only).upper()}) + + # Save results + write.csv(ttest_results, file="{output_file}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + 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, + "output_files": {"results": str(output_file)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() + + +@mcp.tool +def genefilter_k_over_a( + expression_data: Path, + k: int, + A: float, + output_prefix: str, +) -> dict: + """ + Filters genes where at least 'k' samples have expression values over 'A'. + + This tool uses the kOverA filter function with the main genefilter engine. + It's a common filtering step to remove genes with consistently low expression. + + Args: + expression_data: Path to the input expression data file (CSV format). + Rows should be genes, columns should be samples. + The first column should contain gene identifiers. + k: The minimum number of samples that must be above the threshold 'A'. + A: The expression level threshold. + output_prefix: Prefix for the output files. + + Returns: + A dictionary containing the command executed, stdout, stderr, and paths to + the filtered data and a list of passing gene IDs. + """ + # Input validation + if not expression_data.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_data}") + if k < 0: + raise ValueError("k must be a non-negative integer.") + + output_filtered_data = Path(f"{output_prefix}_filtered_data.csv") + output_passing_genes = Path(f"{output_prefix}_passing_genes.txt") + + r_script_content = f""" + library(genefilter) + + # Read data + data_matrix <- as.matrix(read.csv("{expression_data}", row.names=1, check.names=FALSE)) + + # Define the kOverA filter function + kOverA_filter <- kOverA(k={k}, A={A}) + + # Apply the filter using genefilter + passing_indices <- genefilter(data_matrix, kOverA_filter) + + # Subset the data to keep only the passing genes + filtered_matrix <- data_matrix[passing_indices, ] + passing_gene_ids <- rownames(filtered_matrix) + + # Save the results + write.csv(filtered_matrix, file="{output_filtered_data}") + write.table(passing_gene_ids, file="{output_passing_genes}", row.names=FALSE, col.names=FALSE, quote=FALSE) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + 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, + "output_files": { + "filtered_data": str(output_filtered_data), + "passing_genes": str(output_passing_genes) + } + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genefilter/app/bioconductor-genefilter_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-genefilter/app/bioconductor-genefilter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3e765f3d8bad2f04ef330ec468539ff7b966d0c0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genefilter/app/bioconductor-genefilter_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-genefilter/app/bioconductor-genefilter_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_genefilter' + + +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/Biomni/mcp_generated/mcp_bioconductor-genefilter/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genefilter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genefilter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-genefilter/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-genefilter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8e8117174138cbb23e50012e6aebca949f11ffa --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genefilter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genefilter: + build: . + image: mcp-bioconductor-genefilter:latest + container_name: mcp-bioconductor-genefilter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genefilter + 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/Biomni/mcp_generated/mcp_bioconductor-genefilter/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-genefilter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..312740a65e928231eccc1ea6ad5aa3f5d906f6ab --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genefilter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genefilter + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genefilter/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genefilter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genefilter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-geneplotter/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9d0c94a2a986994b11bf5544d2ed47deb4078e57 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/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-geneplotter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-geneplotter -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-geneplotter_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-geneplotter_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-geneplotter_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ef6dfcc0ec4c0900ae2ecde3121d5f1e6f66341a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py @@ -0,0 +1,442 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, Dict, Any, List + +# Mock decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def geneplotter_plot_ma( + expression_file: Path, + output_file: Path, + main_title: str = "MA Plot", + xlab: str = "A (Average Log Intensity)", + ylab: str = "M (Log Ratio)", + point_color: str = "blue", + point_size: float = 0.5, + add_abline: bool = True, + file_separator: str = "tab", +) -> Dict[str, Any]: + """ + Generates an M-A plot from a two-column expression file. + + This tool takes a file with two columns of expression data (e.g., two + samples or conditions), calculates M (log-ratio) and A (average log-intensity), + and generates a scatter plot. It is a common visualization for differential + expression analysis. + + Args: + expression_file: Path to the input data file. Must contain at least two + numeric columns representing two conditions. A header is expected. + output_file: Path to save the output PNG image. + main_title: The main title for the plot. + xlab: Label for the x-axis (A-values). + ylab: Label for the y-axis (M-values). + point_color: Color of the points in the plot. + point_size: Size of the points (cex in R). + add_abline: If True, adds a horizontal red line at y=0. + file_separator: The separator used in the input file ('tab' or 'comma'). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + list with the path to the output plot file. + """ + # --- Input Validation --- + if not expression_file.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_file}") + if output_file.suffix.lower() != ".png": + raise ValueError("output_file must have a .png extension.") + if point_size <= 0: + raise ValueError("point_size must be a positive number.") + if file_separator not in ["tab", "comma"]: + raise ValueError("file_separator must be 'tab' or 'comma'.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + sep_char = "\t" if file_separator == "tab" else "," + + # --- R Script --- + r_script_content = f""" + library(geneplotter) + library(methods) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + mainTitle <- args[3] + xLab <- args[4] + yLab <- args[5] + pointColor <- args[6] + pointSize <- as.numeric(args[7]) + addAbline <- as.logical(args[8]) + + data <- read.csv(inputFile, header = TRUE, sep = "{sep_char}") + + if (ncol(data) < 2) {{ + stop("Input file must have at least two numeric columns.") + }} + + offset <- 1e-6 + col1 <- as.numeric(data[,1]) + col2 <- as.numeric(data[,2]) + + M <- log2(col1 + offset) - log2(col2 + offset) + A <- 0.5 * (log2(col1 + offset) + log2(col2 + offset)) + ma_data <- data.frame(A = A, M = M) + + png(outputFile, width = 800, height = 600) + + plot(ma_data, + main = mainTitle, + xlab = xLab, + ylab = yLab, + col = pointColor, + cex = pointSize, + pch = 16) + + if (addAbline) {{ + abline(h = 0, col = "red", lwd = 2) + }} + + dev.off() + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + # --- Subprocess Execution --- + command: List[str] = [ + "Rscript", + script_path, + str(expression_file), + str(output_file), + main_title, + xlab, + ylab, + point_color, + str(point_size), + str(add_abline).upper(), + ] + + command_str = " ".join(command) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) + finally: + os.remove(script_path) + + +@mcp.tool +def geneplotter_plot_densities( + expression_file: Path, + output_file: Path, + main_title: str = "Density of log2(intensities)", + xlab: str = "log2(intensity)", + log_transform: bool = True, + legend_position: str = "topright", + line_width: int = 2, + file_separator: str = "tab", +) -> Dict[str, Any]: + """ + Plots density estimates of expression values for each sample. + + This tool is useful for quality control, allowing visual inspection of the + distribution of expression values across multiple samples to check for + batch effects or normalization issues. + + Args: + expression_file: Path to the input data file. Columns should be samples + and rows should be features (e.g., genes). A header row + with sample names and a first column with feature names + are expected. + output_file: Path to save the output PNG image. + main_title: The main title for the plot. + xlab: Label for the x-axis. + log_transform: If True, log2-transforms the data before plotting. + legend_position: Position of the legend (e.g., "topright", "bottomleft"). + line_width: Width of the density lines. + file_separator: The separator used in the input file ('tab' or 'comma'). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + list with the path to the output plot file. + """ + # --- Input Validation --- + if not expression_file.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_file}") + if output_file.suffix.lower() != ".png": + raise ValueError("output_file must have a .png extension.") + if line_width <= 0: + raise ValueError("line_width must be a positive integer.") + if file_separator not in ["tab", "comma"]: + raise ValueError("file_separator must be 'tab' or 'comma'.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + sep_char = "\t" if file_separator == "tab" else "," + + # --- R Script --- + r_script_content = f""" + library(geneplotter) + library(methods) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + mainTitle <- args[3] + xLab <- args[4] + logTransform <- as.logical(args[5]) + legendPos <- args[6] + lineWidth <- as.numeric(args[7]) + + data <- read.csv(inputFile, header = TRUE, sep = "{sep_char}", row.names = 1) + + data_matrix <- as.matrix(data) + if(!is.numeric(data_matrix)) {{ + stop("Input data must be numeric after the first column.") + }} + + if (logTransform) {{ + offset <- 1e-6 + data_matrix[data_matrix <= 0] <- offset + data_matrix <- log2(data_matrix) + }} + + png(outputFile, width = 800, height = 600) + + plotDensities(data_matrix, + main = mainTitle, + xlab = xLab, + legend = legendPos, + lwd = lineWidth) + + dev.off() + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + # --- Subprocess Execution --- + command: List[str] = [ + "Rscript", + script_path, + str(expression_file), + str(output_file), + main_title, + xlab, + str(log_transform).upper(), + legend_position, + str(line_width), + ] + + command_str = " ".join(command) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) + finally: + os.remove(script_path) + + +@mcp.tool +def geneplotter_plot_pca( + expression_file: Path, + output_file: Path, + metadata_file: Optional[Path] = None, + grouping_column: Optional[str] = None, + pc_x: int = 1, + pc_y: int = 2, + main_title: str = "PCA Plot", + scale_data: bool = True, + center_data: bool = True, + point_size: float = 3.0, + file_separator: str = "tab", +) -> Dict[str, Any]: + """ + Performs PCA on expression data and generates a 2D scatter plot. + + This tool is used for exploratory data analysis to visualize sample + relationships. Points can be colored by providing a metadata file. + Requires R packages 'ggplot2' and 'RColorBrewer'. + + Args: + expression_file: Path to the expression data. Columns should be samples, + rows should be features. A header with sample names and + a first column with feature names are expected. + output_file: Path to save the output PNG image. + metadata_file: Optional. Path to a metadata file. The first column must + contain sample names matching the expression file's header. + grouping_column: The column name in metadata_file to use for coloring points. + Required if metadata_file is provided. + pc_x: The principal component to plot on the x-axis. + pc_y: The principal component to plot on the y-axis. + main_title: The main title for the plot. + scale_data: If True, scale variables to have unit variance before PCA. + center_data: If True, center variables to have mean zero before PCA. + point_size: Size of the points in the plot. + file_separator: The separator used in the input and metadata files ('tab' or 'comma'). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + list with the path to the output plot file. + """ + # --- Input Validation --- + if not expression_file.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_file}") + if metadata_file and not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if metadata_file and not grouping_column: + raise ValueError("grouping_column is required when metadata_file is provided.") + if not metadata_file and grouping_column: + raise ValueError("metadata_file is required when grouping_column is provided.") + if pc_x <= 0 or pc_y <= 0 or pc_x == pc_y: + raise ValueError("pc_x and pc_y must be different positive integers.") + if output_file.suffix.lower() != ".png": + raise ValueError("output_file must have a .png extension.") + if file_separator not in ["tab", "comma"]: + raise ValueError("file_separator must be 'tab' or 'comma'.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + sep_char = "\t" if file_separator == "tab" else "," + + # --- R Script --- + r_script_content = f""" + library(ggplot2) + library(RColorBrewer) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + metadataFile <- args[3] + groupingColumn <- args[4] + pcX <- as.integer(args[5]) + pcY <- as.integer(args[6]) + mainTitle <- args[7] + scaleData <- as.logical(args[8]) + centerData <- as.logical(args[9]) + pointSize <- as.numeric(args[10]) + + expr_data <- read.csv(inputFile, header = TRUE, sep = "{sep_char}", row.names = 1) + data_for_pca <- t(expr_data) + + pca_result <- prcomp(data_for_pca, center = centerData, scale. = scaleData) + pca_summary <- summary(pca_result) + variance_explained <- pca_summary$importance[2, ] * 100 + xlab_text <- sprintf("PC%d (%.2f%% variance)", pcX, variance_explained[pcX]) + ylab_text <- sprintf("PC%d (%.2f%% variance)", pcY, variance_explained[pcY]) + + plot_data <- as.data.frame(pca_result$x) + + p <- ggplot(plot_data, aes_string(x = paste0("PC", pcX), y = paste0("PC", pcY))) + + if (metadataFile != "NULL") {{ + metadata <- read.csv(metadataFile, header = TRUE, sep = "{sep_char}", row.names = 1) + + if(!all(rownames(data_for_pca) %in% rownames(metadata))) {{ + stop("Not all samples in expression data are present in metadata file.") + }} + metadata_sorted <- metadata[rownames(data_for_pca), , drop = FALSE] + + if (!(groupingColumn %in% colnames(metadata_sorted))) {{ + stop(paste("Grouping column '", groupingColumn, "' not found in metadata file.", sep="")) + }} + plot_data$Group <- factor(metadata_sorted[[groupingColumn]]) + p <- p + geom_point(aes(color = Group), size = pointSize) + scale_color_brewer(palette = "Set1") + }} else {{ + p <- p + geom_point(size = pointSize) + }} + + p <- p + labs(title = mainTitle, x = xlab_text, y = ylab_text) + theme_bw() + ggsave(outputFile, plot = p, width = 8, height = 6, units = "in", dpi = 300) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + # --- Subprocess Execution --- + command: List[str] = [ + "Rscript", + script_path, + str(expression_file), + str(output_file), + str(metadata_file) if metadata_file else "NULL", + str(grouping_column) if grouping_column else "NULL", + str(pc_x), + str(pc_y), + main_title, + str(scale_data).upper(), + str(center_data).upper(), + str(point_size), + ] + + command_str = " ".join(command) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) + finally: + os.remove(script_path) \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2124b1b63a61f7ce6a28d47760765da3493ee0fd --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_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-geneplotter/app/bioconductor-geneplotter_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_geneplotter' + + +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/Biomni/mcp_generated/mcp_bioconductor-geneplotter/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-geneplotter/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..026bcda856f99b635b1b6d84ba99f4b936d948d7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-geneplotter: + build: . + image: mcp-bioconductor-geneplotter:latest + container_name: mcp-bioconductor-geneplotter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-geneplotter + 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/Biomni/mcp_generated/mcp_bioconductor-geneplotter/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..140b2e80539603f5b9039b3b6fdfde9efa0c3d43 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-geneplotter + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-geneplotter/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geneplotter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..da1928863b64adf79436afc2d7c96a25511e3b41 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/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-genomeinfodb via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomeinfodb -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-genomeinfodb_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-genomeinfodb_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-genomeinfodb_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_server.py new file mode 100644 index 0000000000000000000000000000000000000000..247ad74c244354ac05b0ea362a4966374284ace9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_server.py @@ -0,0 +1,325 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Dict +import sys +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Mock the mcp.tool decorator for standalone execution +class mcp: + def tool(func): + return func + +def _check_rscript(): + """Checks if Rscript is available in the system PATH.""" + if not shutil.which("Rscript"): + raise EnvironmentError( + "Rscript not found in PATH. R and the GenomeInfoDb Bioconductor " + "package are required to run these tools." + ) + +@mcp.tool +def genomeinfodb_list_styles(species: str) -> Dict: + """ + Lists the available chromosome naming styles (e.g., UCSC, NCBI) for a given species. + + This tool wraps the `genomeStyles()` function from the R/Bioconductor GenomeInfoDb package. + + Args: + species: The scientific name of the species (e.g., "Homo sapiens", "Mus musculus"). + + Returns: + A dictionary containing the command executed, stdout (with the list of styles), + stderr, and a list of available styles. + """ + _check_rscript() + if not species: + raise ValueError("The 'species' argument cannot be empty.") + + r_script_content = f""" + suppressPackageStartupMessages(library(GenomeInfoDb)) + tryCatch({{ + styles <- genomeStyles('{species}') + if (length(styles) == 0) {{ + cat("No styles found for species: {species}\\n", file=stderr()) + }} else {{ + cat(paste(names(styles), collapse='\\n')) + }} + }}, error = function(e) {{ + cat(paste("Error:", e$message, "\\n"), file=stderr()) + quit(status = 1) + }}) + """ + + command = ["Rscript", "-e", r_script_content] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + styles_list = result.stdout.strip().split('\n') if result.stdout.strip() else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "styles": styles_list, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing GenomeInfoDb R script: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to list genome styles. Check if the species name is correct and GenomeInfoDb is installed.", + } + +@mcp.tool +def genomeinfodb_map_seqlevels( + target_style: str, + species: str, + input_file: Path, + output_file: Path, +) -> Dict: + """ + Maps chromosome names from an input file to a specified naming convention (style). + + This tool wraps the `mapSeqlevels()` function from the R/Bioconductor GenomeInfoDb package. + It produces a two-column TSV file: 'original' and 'mapped'. + + Args: + target_style: The target naming style (e.g., "UCSC", "NCBI", "Ensembl"). + species: The scientific name of the species (e.g., "Homo sapiens"). + input_file: Path to a file containing one chromosome name per line. + output_file: Path to write the output TSV file with original and mapped names. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output file. + """ + _check_rscript() + if not target_style: + raise ValueError("The 'target_style' argument cannot be empty.") + if not species: + raise ValueError("The 'species' argument cannot be empty.") + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(GenomeInfoDb)) + args <- commandArgs(trailingOnly=TRUE) + inputFile <- args[1] + targetStyle <- args[2] + species <- args[3] + outputFile <- args[4] + + tryCatch({{ + seqs <- readLines(inputFile) + if (length(seqs) == 0) {{ + stop("Input file is empty.") + }} + mapped_seqs <- mapSeqlevels(seqs, style=targetStyle, species=species) + output_df <- data.frame(original=seqs, mapped=mapped_seqs) + write.table(output_df, file=outputFile, sep='\\t', row.names=FALSE, col.names=TRUE, quote=FALSE) + }}, error = function(e) {{ + cat(paste("Error:", e$message, "\\n"), file=stderr()) + quit(status = 1) + }}) + """ + + command = [ + "Rscript", + "-e", + r_script_content, + str(input_file), + target_style, + species, + str(output_file), + ] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"mapped_seqlevels": str(output_file)}, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing GenomeInfoDb R script: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to map seqlevels. Check parameters and ensure input file is correctly formatted.", + } + +@mcp.tool +def genomeinfodb_get_seqinfo( + genome: str, + output_file: Path, +) -> Dict: + """ + Fetches sequence information (lengths, circularity) for a given genome assembly. + + This tool wraps the `Seqinfo()` constructor from the R/Bioconductor GenomeInfoDb package. + It produces a TSV file containing seqnames, seqlengths, isCircular, and genome. + + Args: + genome: The genome assembly identifier (e.g., "hg19", "hg38", "mm10"). + output_file: Path to write the output TSV file with sequence information. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output file. + """ + _check_rscript() + if not genome: + raise ValueError("The 'genome' argument cannot be empty.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(GenomeInfoDb)) + args <- commandArgs(trailingOnly=TRUE) + genome_id <- args[1] + outputFile <- args[2] + + tryCatch({{ + si <- Seqinfo(genome=genome_id) + si_df <- as.data.frame(si) + write.table(si_df, file=outputFile, sep='\\t', row.names=TRUE, col.names=NA, quote=FALSE) + }}, error = function(e) {{ + cat(paste("Error:", e$message, "\\n"), file=stderr()) + quit(status = 1) + }}) + """ + + command = ["Rscript", "-e", r_script_content, genome, str(output_file)] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"seqinfo": str(output_file)}, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing GenomeInfoDb R script: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to get seqinfo. Check if the genome identifier is correct.", + } + +@mcp.tool +def genomeinfodb_rename_seqlevels( + input_file: Path, + mapping_file: Path, + output_file: Path, +) -> Dict: + """ + Renames chromosome names from an input file based on a provided mapping file. + + This tool wraps the `renameSeqlevels()` function from the R/Bioconductor GenomeInfoDb package. + It produces a two-column TSV file: 'original' and 'renamed'. + + Args: + input_file: Path to a file containing one chromosome name per line. + mapping_file: Path to a two-column TSV file (old_namenew_name) without a header. + output_file: Path to write the output TSV file with original and renamed names. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output file. + """ + _check_rscript() + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not mapping_file.is_file(): + raise FileNotFoundError(f"Mapping file not found: {mapping_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(GenomeInfoDb)) + args <- commandArgs(trailingOnly=TRUE) + inputFile <- args[1] + mappingFile <- args[2] + outputFile <- args[3] + + tryCatch({{ + seqs <- readLines(inputFile) + if (length(seqs) == 0) {{ + stop("Input file is empty.") + }} + mapping_df <- read.table(mappingFile, sep='\\t', header=FALSE, stringsAsFactors=FALSE, col.names=c("old", "new")) + if (nrow(mapping_df) == 0) {{ + stop("Mapping file is empty.") + }} + value <- setNames(mapping_df$new, mapping_df$old) + renamed_seqs <- renameSeqlevels(seqs, value) + output_df <- data.frame(original=seqs, renamed=renamed_seqs) + write.table(output_df, file=outputFile, sep='\\t', row.names=FALSE, col.names=TRUE, quote=FALSE) + }}, error = function(e) {{ + cat(paste("Error:", e$message, "\\n"), file=stderr()) + quit(status = 1) + }}) + """ + + command = [ + "Rscript", + "-e", + r_script_content, + str(input_file), + str(mapping_file), + str(output_file), + ] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"renamed_seqlevels": str(output_file)}, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing GenomeInfoDb R script: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to rename seqlevels. Check file formats and content.", + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f38a077fe622112b1e7640568dec0e444b5abc9c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_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-genomeinfodb/app/bioconductor-genomeinfodb_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_genomeinfodb' + + +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/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f45008fc4f9db6ed1b6aafd4d5c65aa0c5ac8c66 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomeinfodb: + build: . + image: mcp-bioconductor-genomeinfodb:latest + container_name: mcp-bioconductor-genomeinfodb + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomeinfodb + 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/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9340ec8e0823c9ed7de8c928916c2c625108234e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomeinfodb + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodb/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dc26f6e5aed612e1d00f134418a4dfb7f9cfe0cb --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/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-genomeinfodbdata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomeinfodbdata -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-genomeinfodbdata_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-genomeinfodbdata_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-genomeinfodbdata_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..01172e946bbc296476712c464e9a98a8dd117e2b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py @@ -0,0 +1,180 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Set up a logger for better debugging and information +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# This is a placeholder for the actual MCP decorator. +# The final code will be compatible with the MCP framework. +class mcp: + @staticmethod + def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + # In a real MCP environment, this would register the function. + # For this standalone script, it just acts as a pass-through. + wrapper.__doc__ = func.__doc__ + wrapper.__annotations__ = func.__annotations__ + return wrapper + +@mcp.tool +def rscript_runner( + 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 general-purpose wrapper for Rscript, allowing for the execution + of either a specified R script file or a list of R expressions. + + Args: + script_file: Path to the R script file to execute. 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. + verbose: If True, enables verbose output from Rscript. + default_packages: A comma-separated list 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" R session. + save: If True, the workspace is saved at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, site and user environment files are not read. Ignored if 'vanilla' is True. + no_site_file: If True, the site-wide Rprofile is not read. Ignored if 'vanilla' is True. + no_init_file: If True, the user's R profile is not read. Ignored if 'vanilla' is True. + restore: If True, previously saved objects are restored at startup. Ignored if 'vanilla' is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of potential output files. + """ + # --- Input Validation --- + if not script_file and not expressions: + raise ValueError("You must provide either 'script_file' or 'expressions'.") + if script_file and expressions: + raise ValueError("'script_file' and 'expressions' are mutually exclusive.") + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # --- Command Construction --- + command = ["Rscript"] + + 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.extend(["--default-packages", default_packages]) + + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + + if script_file: + command.append(str(script_file)) + + if script_args: + command.extend(script_args) + + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + logging.info("Rscript executed successfully.") + + except FileNotFoundError: + logging.error("Rscript not found. Please ensure R is installed and in your system's PATH.") + raise + except subprocess.CalledProcessError as e: + logging.error(f"Rscript execution failed with return code {e.returncode}") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + # Note: Predicting output files from a generic script runner is not feasible. + # The user of this tool is responsible for knowing what files their script creates. + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } + +@mcp.tool +def rscript_version() -> Dict[str, Any]: + """ + Retrieves the version of the Rscript interpreter and the R language. + + This is equivalent to running 'Rscript --version' on the command line. + + Returns: + A dictionary containing the executed command and the version information + captured from stderr (as Rscript prints version info to stderr). + """ + command = ["Rscript", "--version"] + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + try: + # Rscript prints version information to stderr, so we capture it. + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # The primary output is in stderr for the --version flag + version_info = result.stderr + + except FileNotFoundError: + logging.error("Rscript not found. Please ensure R is installed and in your system's PATH.") + raise + except subprocess.CalledProcessError as e: + logging.error(f"Rscript --version failed with return code {e.returncode}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + } + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": version_info, + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8d2836573f15274e20fa51b92e3cca091d50182f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_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-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_genomeinfodbdata' + + +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/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..417a651e07b0490b797620fdf758562f52d5a1cb --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomeinfodbdata: + build: . + image: mcp-bioconductor-genomeinfodbdata:latest + container_name: mcp-bioconductor-genomeinfodbdata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomeinfodbdata + 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/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e178851c0df5db898851d3336adcacfea12f5cad --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomeinfodbdata + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomeinfodbdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1df8854d574f92a14aab64756ce0ad45c64c831b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/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-genomicalignments via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomicalignments -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-genomicalignments_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-genomicalignments_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-genomicalignments_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e811700f205898119c69efbfbeb9177c46e9baf4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py @@ -0,0 +1,247 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import List, Dict, Any + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# R script template to be executed. This script is a self-contained wrapper +# for the summarizeOverlaps function. +R_SCRIPT_TEMPLATE = """ +# Load required libraries quietly +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(GenomicAlignments)) +suppressPackageStartupMessages(library(Rsamtools)) +suppressPackageStartupMessages(library(rtracklayer)) +suppressPackageStartupMessages(library(GenomicFeatures)) + +# Define command-line options +option_list <- list( + make_option("--features", type="character", help="Path to features file (GFF/GTF/BED)"), + make_option("--reads", type="character", help="Path to alignment file (BAM)"), + make_option("--output", type="character", help="Path to output count matrix file (TSV)"), + make_option("--mode", type="character", default="Union", help="Counting mode [Union, IntersectionStrict, IntersectionNotEmpty]"), + make_option("--single_end", type="logical", default=FALSE, help="Set TRUE for single-end reads"), + make_option("--ignore_strand", type="logical", default=FALSE, help="Set TRUE to ignore strand information"), + make_option("--fragments", type="logical", default=FALSE, help="Count fragments (pairs) instead of reads for paired-end data"), + make_option("--inter_feature", type="logical", default=TRUE, help="If TRUE, reads overlapping multiple features are dropped"), + make_option("--mapq_filter", type="integer", default=0, help="Minimum mapping quality (MAPQ)"), + make_option("--filter_secondary", type="logical", default=TRUE, help="If TRUE, filter out secondary alignments"), + make_option("--filter_unmapped", type="logical", default=TRUE, help="If TRUE, filter out unmapped reads"), + make_option("--filter_improper", type="logical", default=TRUE, help="If TRUE, filter out reads not in a proper pair (for PE data)") +) + +# Parse options +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +# Check for required arguments +if (is.null(opt$features) || is.null(opt$reads) || is.null(opt$output)) { + print_help(opt_parser) + stop("Input features, reads, and output files must be supplied.", call.=FALSE) +} + +# Read features from GFF/GTF/BED +tryCatch({ + cat("INFO: Reading features from:", opt$features, "\\n") + features <- rtracklayer::import(opt$features) +}, error = function(e) { + stop(paste("Failed to read features file:", opt$features, "\\nError:", e$message)) +}) + +# Create BamFile object to stream the BAM file +bam_file <- BamFile(opt$reads, asMates=!opt$single_end) + +# Construct ScanBamParam for filtering alignments +# Note: Rsamtools flags specify what to KEEP. +# So, filter_secondary=TRUE (Python) means isSecondaryAlignment=FALSE (R). +flag <- scanBamFlag( + isNotPrimaryAlignment = FALSE, # Always keep primary alignments + isSecondaryAlignment = !opt$filter_secondary, + isUnmappedQuery = !opt$filter_unmapped, + isProperPair = if (opt$single_end) NA else !opt$filter_improper, + isDuplicate = FALSE # We are not filtering duplicates by default in this wrapper +) +param <- ScanBamParam(mapqFilter = opt$mapq_filter, flag = flag) + +# Run the core function: summarizeOverlaps +cat("INFO: Running summarizeOverlaps with mode '", opt$mode, "'...\\n", sep="") +se <- summarizeOverlaps( + features = features, + reads = bam_file, + mode = opt$mode, + singleEnd = opt$single_end, + ignore.strand = opt$ignore_strand, + fragments = opt$fragments, + inter.feature = opt$inter_feature, + param = param +) + +# Extract and write the count matrix +cat("INFO: Writing counts to:", opt$output, "\\n") +counts <- assay(se) +counts_df <- as.data.frame(counts) + +# Attempt to get meaningful feature IDs from the GRanges object +feature_ids <- names(features) +if (is.null(feature_ids)) { + # Fallback to metadata columns if names are not set + if ("ID" %in% colnames(mcols(features))) { + feature_ids <- mcols(features)$ID + } else if ("gene_id" %in% colnames(mcols(features))) { + feature_ids <- mcols(features)$gene_id + } else { + feature_ids <- paste0("feature_", seq_len(nrow(counts_df))) + } +} +# Ensure feature IDs are unique to prevent row name conflicts +feature_ids <- make.unique(as.character(feature_ids)) + +# Combine feature IDs with the count data +output_df <- cbind(feature_id = feature_ids, counts_df) + +# Write to a tab-separated file +write.table( + output_df, + file = opt$output, + sep = "\\t", + quote = FALSE, + row.names = FALSE, + col.names = TRUE +) + +cat("INFO: Process completed successfully.\\n") +""" + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_genomicalignments' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def summarize_overlaps( + features_file: Path, + reads_file: Path, + output_file: Path, + mode: str = "Union", + single_end: bool = False, + ignore_strand: bool = False, + fragments: bool = False, + inter_feature: bool = True, + mapq_filter: int = 0, + filter_secondary_alignments: bool = True, + filter_unmapped_reads: bool = True, + filter_improper_pairs: bool = True, +) -> Dict[str, Any]: + """ + Generates a feature count matrix from alignment and annotation files. + + This tool is a wrapper for the `summarizeOverlaps` function from the + R/Bioconductor package 'GenomicAlignments'. It quantifies reads from a + BAM file that overlap with genomic features defined in a GFF, GTF, or BED file. + + **Prerequisites**: The execution environment must have R installed, along with + the Bioconductor packages: GenomicAlignments, Rsamtools, rtracklayer, + GenomicFeatures, and the CRAN package optparse. + + Args: + features_file: Path to the input genomic features file (e.g., GFF, GTF, BED). + reads_file: Path to the input alignments file (BAM format). + output_file: Path for the output count matrix (will be saved as a TSV file). + mode: The counting mode. Must be one of 'Union', 'IntersectionStrict', + or 'IntersectionNotEmpty'. Defaults to 'Union'. + single_end: Set to True if the sequencing data is single-end. Defaults to False (paired-end). + ignore_strand: Set to True to perform non-strand-specific counting. Defaults to False. + fragments: For paired-end data, count fragments (read pairs) instead of individual + reads. Defaults to False. + inter_feature: If True, reads that overlap multiple features are not counted. + If False, they are counted for each feature they overlap. Defaults to True. + mapq_filter: Minimum mapping quality (MAPQ) score for a read to be included. + Defaults to 0 (no filtering). + filter_secondary_alignments: If True, secondary alignments are excluded from counting. + Defaults to True. + filter_unmapped_reads: If True, unmapped reads are excluded. Defaults to True. + filter_improper_pairs: For paired-end data, if True, reads that are not part of a + proper pair are excluded. Defaults to True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of output files. + """ + # --- Input Validation --- + if not features_file.exists(): + raise FileNotFoundError(f"Features file not found: {features_file}") + if not reads_file.exists(): + raise FileNotFoundError(f"Reads file not found: {reads_file}") + if not output_file.parent.exists(): + raise FileNotFoundError(f"Output directory does not exist: {output_file.parent}") + + valid_modes = ["Union", "IntersectionStrict", "IntersectionNotEmpty"] + if mode not in valid_modes: + raise ValueError(f"Invalid mode '{mode}'. Must be one of {valid_modes}.") + + if mapq_filter < 0: + raise ValueError("mapq_filter must be a non-negative integer.") + + if fragments and single_end: + logger.warning("'fragments' is set to True but 'single_end' is also True. 'fragments' is only applicable to paired-end data.") + + # --- R Script and Command Preparation --- + r_script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as fp: + fp.write(R_SCRIPT_TEMPLATE) + r_script_path = fp.name + + cmd = [ + "Rscript", r_script_path, + "--features", str(features_file), + "--reads", str(reads_file), + "--output", str(output_file), + "--mode", mode, + "--mapq_filter", str(mapq_filter), + "--single_end", str(single_end).upper(), + "--ignore_strand", str(ignore_strand).upper(), + "--fragments", str(fragments).upper(), + "--inter_feature", str(inter_feature).upper(), + "--filter_secondary", str(filter_secondary_alignments).upper(), + "--filter_unmapped", str(filter_unmapped_reads).upper(), + "--filter_improper", str(filter_improper_pairs).upper(), + ] + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + 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 FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in your system's PATH.") + raise + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}.") + logger.error(f"Stderr:\n{e.stderr}") + logger.error(f"Stdout:\n{e.stdout}") + raise + finally: + # --- Cleanup --- + 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/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b7e7d5288f03802f7bc90706884dc8aa4066fac1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_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-genomicalignments/app/bioconductor-genomicalignments_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_genomicalignments' + + +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/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..abb740c24ddfef04f23dc41a049518a7b7c7e21f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomicalignments: + build: . + image: mcp-bioconductor-genomicalignments:latest + container_name: mcp-bioconductor-genomicalignments + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomicalignments + 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/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d43bf092a97ea39850977042b15a1c8a2d642c7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomicalignments + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicalignments/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ce330750f20d1fec8196e0bc3c8a1de5fbd3e99 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py new file mode 100644 index 0000000000000000000000000000000000000000..363bdf78d73781b0dd864e5ad440d07ec8286ac6 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1a1da4f2d1e41d1807c9abd124c323c7e5bad914 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ed64c15246a6e42f3ed448bcf13f62762db3b12 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..077be5894b7e52c31a6f405538213f1090d401b7 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicfeatures/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomicranges/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-genomicranges/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a783e9fd7d22fd481ab343307f3a69bcaebf197c --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6a8dacf47d1f5bce76ea29000a24a5a0f451fc1a --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b0134b18102fe7dffc1443017be3b9790144ddfb --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicranges/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomicranges/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicranges/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-genomicranges/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-genomicranges/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e81d4f5f098f9b6f1bc4fc6a0ce0235bf53b0514 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicranges/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-genomicranges/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ffc91febb91701103946099d3bc44d0d4de7675 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-genomicranges/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-genomicranges/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-genomicranges/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-geomxtools/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e7d23553fd16ce1626a84fcd3ab533e663d65307 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/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-geomxtools via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-geomxtools -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-geomxtools_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-geomxtools_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-geomxtools_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_server.py b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..97379910779be165f55c0de66b7f61a0ff000a24 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_server.py @@ -0,0 +1,688 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# In a real MCP environment, this would be imported. +# from mcp import tool as mcp_tool +# For this exercise, we assume the decorator @mcp.tool() is available. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_geomxtools' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def read_nanostring_geomx_set( + dcc_files_dir: Path, + pkc_files: List[Path], + pheno_data_file: Path, + output_rds_path: Path, + pheno_data_sheet: Optional[str] = None, + pheno_data_dcc_col_name: str = "Sample_ID", + protocol_data_col_names: Optional[List[str]] = None, + experiment_data_col_names: Optional[List[str]] = None, +) -> dict: + """ + Reads NanoString GeoMx files (DCC, PKC, annotation) and creates a NanoStringGeomxSet object. + + This tool is a wrapper around the `readNanoStringGeoMxSet` function from the + R/Bioconductor package `GeomxTools`. It processes raw data into a structured + R object for downstream analysis. + + Args: + dcc_files_dir: Path to the directory containing DCC files. + pkc_files: A list of paths to PKC files. + pheno_data_file: Path to the sample annotation file (e.g., an Excel file). + output_rds_path: Path for the output RDS file which will contain the NanoStringGeomxSet object. + pheno_data_sheet: Optional name of the worksheet in the Excel annotation file. + pheno_data_dcc_col_name: Column name in the annotation file that matches DCC file names. + protocol_data_col_names: Optional list of column names in annotation to be added to protocolData. + experiment_data_col_names: Optional list of column names in annotation to be added to experimentData. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not dcc_files_dir.is_dir(): + raise ValueError(f"DCC files directory not found: {dcc_files_dir}") + if not pkc_files: + raise ValueError("At least one PKC file must be provided.") + for pkc_file in pkc_files: + if not pkc_file.is_file(): + raise ValueError(f"PKC file not found: {pkc_file}") + if not pheno_data_file.is_file(): + raise ValueError(f"Phenotype data file not found: {pheno_data_file}") + + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + # Safely create R vectors from Python lists + r_protocol_cols = f'c({", ".join(f"{col}" for col in protocol_data_col_names)})' if protocol_data_col_names else "NULL" + r_experiment_cols = f'c({", ".join(f"{col}" for col in experiment_data_col_names)})' if experiment_data_col_names else "NULL" + r_pheno_sheet = f'"{pheno_data_sheet}"' if pheno_data_sheet else "NULL" + pkc_files_r_vector = f'c({", ".join(f"{str(p)}" for p in pkc_files)})' + + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + dcc_dir <- "{dcc_files_dir}" + pkc_files_vec <- {pkc_files_r_vector} + pheno_file <- "{pheno_data_file}" + output_path <- "{output_rds_path}" + pheno_dcc_col <- "{pheno_data_dcc_col_name}" + + dcc_files <- list.files(dcc_dir, pattern = "\\\\.dcc$", full.names = TRUE, recursive = TRUE) + if (length(dcc_files) == 0) {{ + stop("No .dcc files found in the specified directory.") + }} + + geomx_data <- readNanoStringGeoMxSet( + dccFiles = dcc_files, + pkcFiles = pkc_files_vec, + phenoDataFile = pheno_file, + phenoDataSheet = {r_pheno_sheet}, + phenoDataDccColName = pheno_dcc_col, + protocolDataColNames = {r_protocol_cols}, + experimentDataColNames = {r_experiment_cols} + ) + + saveRDS(geomx_data, file = output_path) + cat("Successfully created NanoStringGeomxSet object and saved to", output_path, "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + 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 + + cmd = ["Rscript", r_script_path] + 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_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript 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": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def set_segment_qc_flags( + input_rds_path: Path, + output_rds_path: Path, + min_segment_reads: Optional[int] = 1000, + percent_aligned: Optional[float] = 80, + percent_saturation: Optional[float] = 50, + min_negative_count: Optional[int] = 10, + max_ntc_count: Optional[int] = 1000, + min_nuclei: Optional[int] = 200, + min_area: Optional[int] = 16000, +) -> dict: + """ + Sets segment QC flags in a NanoStringGeomxSet object based on specified cutoffs. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output RDS file with QC flags applied. + min_segment_reads: Minimum number of reads in a segment. + percent_aligned: Minimum percentage of reads aligned. + percent_saturation: Minimum percentage of reads saturated. + min_negative_count: Minimum negative probe counts. + max_ntc_count: Maximum counts observed in NTC wells. + min_nuclei: Minimum number of nuclei in a segment. + min_area: Minimum area of a segment. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + input_rds <- "{input_rds_path}" + output_rds <- "{output_rds_path}" + + geomx_data <- readRDS(input_rds) + + qc_cutoffs <- list() + if (!is.null({min_segment_reads or 'NULL'})) {{ qc_cutoffs$minSegmentReads <- {min_segment_reads} }} + if (!is.null({percent_aligned or 'NULL'})) {{ qc_cutoffs$percentAligned <- {percent_aligned} }} + if (!is.null({percent_saturation or 'NULL'})) {{ qc_cutoffs$percentSaturation <- {percent_saturation} }} + if (!is.null({min_negative_count or 'NULL'})) {{ qc_cutoffs$minNegativeCount <- {min_negative_count} }} + if (!is.null({max_ntc_count or 'NULL'})) {{ qc_cutoffs$maxNTCCount <- {max_ntc_count} }} + if (!is.null({min_nuclei or 'NULL'})) {{ qc_cutoffs$minNuclei <- {min_nuclei} }} + if (!is.null({min_area or 'NULL'})) {{ qc_cutoffs$minArea <- {min_area} }} + + geomx_data_qc <- setSegmentQCFlags(geomx_data, qcCutoffs = qc_cutoffs) + + saveRDS(geomx_data_qc, file = output_rds) + cat("Successfully applied segment QC flags and saved to", output_rds, "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + 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 + + cmd = ["Rscript", r_script_path] + 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_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript 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": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def set_bioprobe_qc_flags( + input_rds_path: Path, + output_rds_path: Path, + min_probe_ratio: float = 0.1, + percent_fail_grubbs: float = 20, + remove_local_outliers: bool = True, +) -> dict: + """ + Sets probe QC flags in a NanoStringGeomxSet object. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output RDS file with QC flags applied. + min_probe_ratio: Minimum ratio of probes to the geometric mean of all probes. + percent_fail_grubbs: Percentage of segments that must fail Grubbs test for a probe to be flagged. + remove_local_outliers: If TRUE, local outliers will be removed. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + input_rds <- "{input_rds_path}" + output_rds <- "{output_rds_path}" + + geomx_data <- readRDS(input_rds) + + qc_cutoffs <- list( + minProbeRatio = {min_probe_ratio}, + percentFailGrubbs = {percent_fail_grubbs} + ) + + geomx_data_qc <- setBioProbeQCFlags( + geomx_data, + qcCutoffs = qc_cutoffs, + removeLocalOutliers = {str(remove_local_outliers).upper()} + ) + + saveRDS(geomx_data_qc, file = output_rds) + cat("Successfully applied bioprobe QC flags and saved to", output_rds, "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + 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 + + cmd = ["Rscript", r_script_path] + 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_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript 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": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def subset_geomx_set( + input_rds_path: Path, + output_rds_path: Path, + subset_by_pdata: bool = True, + subset_column: Optional[str] = None, + subset_values: Optional[List[str]] = None, +) -> dict: + """ + Subsets a NanoStringGeomxSet object based on phenotype (pData) or feature (fData) annotations. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output subsetted RDS file. + subset_by_pdata: If True, subset by sample annotations (pData). If False, subset by feature annotations (fData). + subset_column: The column name in pData or fData to use for subsetting. + subset_values: A list of values to keep from the subset_column. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + if not subset_column or not subset_values: + raise ValueError("subset_column and subset_values must be provided for subsetting.") + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + subset_values_r = f'c({", ".join(f"{v}" for v in subset_values)})' + + r_script_content = f""" + library(GeomxTools) + library(Biobase) + + tryCatch({{ + object <- readRDS("{input_rds_path}") + subset_col <- "{subset_column}" + subset_vals <- {subset_values_r} + + if ({str(subset_by_pdata).upper()}) {{ + logic <- pData(object)[[subset_col]] %in% subset_vals + logic[is.na(logic)] <- FALSE + subset_object <- object[, logic] + }} else {{ + logic <- fData(object)[[subset_col]] %in% subset_vals + logic[is.na(logic)] <- FALSE + subset_object <- object[logic, ] + }} + + saveRDS(subset_object, file = "{output_rds_path}") + cat("Successfully subset object and saved to", "{output_rds_path}", "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + 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 + + cmd = ["Rscript", r_script_path] + 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_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript 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": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def aggregate_counts( + input_rds_path: Path, + output_rds_path: Path, + elt: str = "exprs", +) -> dict: + """ + Aggregates probe-level counts to the target level in a NanoStringGeomxSet object. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output RDS file with aggregated counts. + elt: The name of the assay data element to aggregate. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + geomx_data <- readRDS("{input_rds_path}") + aggregated_data <- aggregateCounts(geomx_data, elt = "{elt}") + + saveRDS(aggregated_data, file = "{output_rds_path}") + cat("Successfully aggregated counts and saved to", "{output_rds_path}", "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + 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 + + cmd = ["Rscript", r_script_path] + 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_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript 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": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def normalize_geomx( + input_rds_path: Path, + output_rds_path: Path, + norm_method: str, + from_elt: str = "exprs", + to_elt: str = "exprs_norm", + housekeepers: Optional[List[str]] = None, +) -> dict: + """ + Normalizes the count data in a NanoStringGeomxSet object. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output RDS file with normalized data. + norm_method: Normalization method. Must be one of 'quant', 'neg', 'hk'. + from_elt: The assay data element to use for normalization. + to_elt: The name of the new assay data element to store normalized values. + housekeepers: A list of housekeeper gene names, required if norm_method is 'hk'. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + + valid_methods = ["quant", "neg", "hk"] + if norm_method not in valid_methods: + raise ValueError(f"Invalid norm_method '{norm_method}'. Must be one of {valid_methods}.") + + if norm_method == "hk" and not housekeepers: + raise ValueError("Housekeeper genes must be provided for 'hk' normalization.") + + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + housekeepers_r = f'c({", ".join(f"{hk}" for hk in housekeepers)})' if housekeepers else "NULL" + + # --- R Script Generation --- + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + geomx_data <- readRDS("{input_rds_path}") + + normalized_data <- normalize( + geomx_data, + norm.method = "{norm_method}", + fromElt = "{from_elt}", + toElt = "{to_elt}", + housekeepers = {housekeepers_r} + ) + + saveRDS(normalized_data, file = "{output_rds_path}") + cat("Successfully normalized data and saved to", "{output_rds_path}", "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + 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 + + cmd = ["Rscript", r_script_path] + 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_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript 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": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def mixed_model_de( + input_rds_path: Path, + output_csv_path: Path, + elt: str, + model_formula_fixed: str, + group_var: str, + model_formula_random: Optional[str] = None, + contrasts: Optional[List[str]] = None, + n_cores: int = 1, +) -> dict: + """ + Performs differential expression analysis using a linear mixed model. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_csv_path: Path for the output CSV file with DE results. + elt: The assay data element to use for the analysis (e.g., 'exprs_norm'). + model_formula_fixed: The fixed effects part of the model formula (e.g., 'region + diseaseStatus'). + group_var: The main variable of interest for testing (e.g., 'diseaseStatus'). + model_formula_random: The random effects part of the model formula (e.g., '(1|slideName)'). + contrasts: A list of contrasts to test (e.g., ['diseaseA - diseaseB', 'diseaseC - diseaseB']). + n_cores: Number of cores to use for parallel processing. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output CSV file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + if n_cores < 1: + raise ValueError("n_cores must be at least 1.") + output_csv_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + formula_str = f"~ {model_formula_fixed}" + if model_formula_random: + formula_str += f" + {model_formula_random}" + + contrasts_r = "NULL" + if contrasts: + contrasts_r = f'c({", ".join(f"{c}" for c in contrasts)})' + + r_script_content = f""" + library(GeomxTools) + library(limma) + library(Biobase) + + tryCatch({{ + object <- readRDS("{input_rds_path}") + + model_formula <- as.formula("{formula_str}") + + contrast_matrix <- NULL + if (!is.null({contrasts_r})) {{ + contrast_matrix <- makeContrasts(contrasts = {contrasts_r}, levels = unique(pData(object)[["{group_var}"]])) + }} + + results <- mixedModelDE( + object, + elt = "{elt}", + modelFormula = model_formula, + groupVar = "{group_var}", + nCores = {n_cores}, + multiCore = {str(n_cores > 1).upper()}, + contrasts = contrast_matrix + ) + + write.csv(results, file = "{output_csv_path}", row.names = FALSE) + cat("Successfully performed DE analysis and saved results to", "{output_csv_path}", "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + 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 + + cmd = ["Rscript", r_script_path] + 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_csv_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript 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": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ac19b536a5e35603ff15fe67ea1bd8e59da203 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_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-geomxtools/app/bioconductor-geomxtools_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_geomxtools' + + +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/Biomni/mcp_generated/mcp_bioconductor-geomxtools/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ddcec77dc3ef15c0699109b8924d12c4ccb1737e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-geomxtools: + build: . + image: mcp-bioconductor-geomxtools:latest + container_name: mcp-bioconductor-geomxtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-geomxtools + 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/Biomni/mcp_generated/mcp_bioconductor-geomxtools/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b21e8a4370c5f03f287e02d6c98afab673d9cd6b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-geomxtools + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-geomxtools/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-geomxtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggsc/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-ggsc/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e4385ba0e7fd397a459e7260eff11f045abdb1a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggsc/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-ggsc via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ggsc -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-ggsc_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-ggsc_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-ggsc_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py b/Biomni/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be9b1a9963625fc0cc3c808a70155fc8972db3e9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py @@ -0,0 +1,368 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# This script assumes the presence of a companion R script (e.g., 'run_ggsc.R') +# that acts as a command-line interface for the 'ggsc' R package. +# The R environment must have 'ggsc', 'SingleCellExperiment', 'ggplot2', +# and an argument parser like 'optparse' installed. +R_SCRIPT_EXECUTABLE = "run_ggsc.R" + +# Per instructions, the @mcp.tool decorator is used. +# A dummy decorator is defined here for syntax validity in a standalone context. +# In a true MCP environment, this would be provided by the MCP framework. +def tool(func): + """Dummy decorator to match the required syntax.""" + return func + +class MCP: + """Dummy class to hold the tool decorator.""" + tool = staticmethod(tool) + +mcp = MCP() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_ggsc' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def plot_reduced_dim( + input_rds: Path, + output_plot: Path, + dim_red: str, + color_by: str, + facet_by: Optional[str] = None, + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 7 +) -> dict: + """ + Generates a reduced dimension plot (e.g., UMAP, t-SNE) from a SingleCellExperiment object. + + This tool wraps the `plot_reduced_dim_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image (e.g., plot.png). + dim_red: Name of the dimension reduction to use (e.g., "UMAP", "TSNE"). + color_by: Variable in colData to color the points by (e.g., "label", "cluster"). + facet_by: Optional variable in colData to facet the plot by. + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + # Ensure output directory exists + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "reduced_dim", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--dim_red", dim_red, + "--color_by", color_by, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if facet_by: + cmd.extend(["--facet_by", facet_by]) + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for reduced_dim plot.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + + +@mcp.tool() +def plot_gene_expression( + input_rds: Path, + output_plot: Path, + gene: str, + dim_red: str, + assay: str = "logcounts", + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 7 +) -> dict: + """ + Plots the expression of a single gene on a reduced dimension plot. + + This tool wraps the `plot_gene_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image. + gene: The name of the gene to plot. + dim_red: Name of the dimension reduction to use (e.g., "UMAP"). + assay: The assay to use for expression values (default: "logcounts"). + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not gene: + raise ValueError("A gene name must be provided.") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "gene_plot", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--gene", gene, + "--dim_red", dim_red, + "--assay", assay, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for gene expression plot.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + + +@mcp.tool() +def plot_expression_heatmap( + input_rds: Path, + output_plot: Path, + genes: List[str], + annotation_col: str, + assay: str = "logcounts", + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 10 +) -> dict: + """ + Generates a heatmap of gene expression for a set of genes. + + This tool wraps the `plot_heatmap_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image. + genes: A list of gene names to include in the heatmap. + annotation_col: Column in colData to use for cell annotation. + assay: The assay to use for expression values (default: "logcounts"). + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not genes: + raise ValueError("At least one gene must be provided in the list.") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + genes_str = ",".join(genes) + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "heatmap", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--genes", genes_str, + "--annotation_col", annotation_col, + "--assay", assay, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for expression heatmap.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + + +@mcp.tool() +def plot_expression_violin( + input_rds: Path, + output_plot: Path, + gene: str, + group_by: str, + assay: str = "logcounts", + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 5 +) -> dict: + """ + Generates a violin plot of gene expression across different groups. + + This tool wraps the `plot_violin_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image. + gene: The name of the gene to plot. + group_by: Variable in colData to group the violins by (e.g., "cluster"). + assay: The assay to use for expression values (default: "logcounts"). + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not gene: + raise ValueError("A gene name must be provided.") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "violin", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--gene", gene, + "--group_by", group_by, + "--assay", assay, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for expression violin plot.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6c7540ba933f6b2bb52b9fd62d2c66bdddb619a0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_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-ggsc/app/bioconductor-ggsc_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_ggsc' + + +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/Biomni/mcp_generated/mcp_bioconductor-ggsc/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-ggsc/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..66d94a739f2052f5fb7c429bf4b4e1aec1181186 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggsc/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ggsc: + build: . + image: mcp-bioconductor-ggsc:latest + container_name: mcp-bioconductor-ggsc + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ggsc + 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/Biomni/mcp_generated/mcp_bioconductor-ggsc/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-ggsc/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..179d5ec77128b05773abab6ecc408a5b49d85d51 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggsc/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ggsc + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggsc/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ggsc/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggsc/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggspavis/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cce68a8789108203349e557d81008954a56da088 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/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-ggspavis via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ggspavis -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-ggspavis_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-ggspavis_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-ggspavis_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_server.py b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f9ea5025816106c39ac370357d544a8e318c4a81 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_server.py @@ -0,0 +1,403 @@ +import subprocess +import tempfile +import json +import shlex +from pathlib import Path +from typing import Optional, List, Literal + +# This R script acts as a generic command-line wrapper for ggspavis functions. +# It is written to a temporary file and executed by the Python functions below. +# It dynamically installs required R packages, making the tool self-contained. +R_SCRIPT = """ +# ggspavis_runner.R +# A generic runner for ggspavis functions + +# Suppress startup messages for cleaner output +suppressPackageStartupMessages({ + # Check if packages are installed, install if not + if (!requireNamespace("argparse", quietly = TRUE)) install.packages("argparse", repos = "http://cran.us.r-project.org") + if (!requireNamespace("jsonlite", quietly = TRUE)) install.packages("jsonlite", repos = "http://cran.us.r-project.org") + if (!requireNamespace("ggplot2", quietly = TRUE)) install.packages("ggplot2", repos = "http://cran.us.r-project.org") + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos = "http://cran.us.r-project.org") + + # Use BiocManager to install Bioconductor packages + if (!requireNamespace("SpatialExperiment", quietly = TRUE)) BiocManager::install("SpatialExperiment", update = FALSE, ask = FALSE) + if (!requireNamespace("ggspavis", quietly = TRUE)) BiocManager::install("ggspavis", update = FALSE, ask = FALSE) +}) + +library(argparse) +library(jsonlite) +library(ggplot2) +library(SpatialExperiment) +library(ggspavis) + +# Main function to parse arguments and call the appropriate ggspavis function +main <- function() { + parser <- ArgumentParser(description = "A command-line wrapper for ggspavis functions.") + + parser$add_argument("func", help = "The ggspavis function to call (e.g., plotSpots, plotFeature).") + parser$add_argument("--spe_path", required = TRUE, help = "Path to the SpatialExperiment object (.rds file).") + parser$add_argument("--output_path", required = TRUE, help = "Path to save the output plot.") + parser$add_argument("--width", type = "double", default = 7, help = "Width of the output plot in inches.") + parser$add_argument("--height", type = "double", default = 7, help = "Height of the output plot in inches.") + parser$add_argument("--json_args", type = "character", default = "{}", help = "A JSON string of arguments for the ggspavis function.") + + args <- parser$parse_args() + + # Load SpatialExperiment object + if (!file.exists(args$spe_path)) { + stop("Input SPE file not found: ", args$spe_path) + } + spe <- readRDS(args$spe_path) + + # Parse JSON arguments for the target function + func_args <- fromJSON(args$json_args) + + # Add the main 'spe' object to the arguments list + func_args <- c(list(spe = spe), func_args) + + # Check if the requested function exists in the ggspavis package + if (!exists(args$func, where = "package:ggspavis", mode = "function")) { + stop("Function '", args$func, "' not found in ggspavis package.") + } + + # Dynamically call the ggspavis function with the parsed arguments + plot_obj <- do.call(args$func, func_args) + + # Save the generated plot to the specified output file + ggsave( + filename = args$output_path, + plot = plot_obj, + width = args$width, + height = args$height, + dpi = 300 + ) + + cat("Plot successfully saved to", args$output_path, "\\n") +} + +# Execute the main function and handle potential errors +tryCatch({ + main() +}, error = function(e) { + message("Error: ", e$message) + quit(status = 1) +}) +""" + +def _run_ggspavis( + function_name: str, + spe_path: Path, + output_path: Path, + plot_width: float, + plot_height: float, + json_args: dict, +) -> dict: + """ + Helper function to execute the ggspavis R script wrapper. + + Args: + function_name: The ggspavis function to execute (e.g., 'plotSpots'). + spe_path: Path to the input SpatialExperiment RDS file. + output_path: Path to save the output plot image. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + json_args: A dictionary of arguments for the ggspavis function. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Ensure output directory exists + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Use a temporary file to store and execute the R script + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_path = Path(r_script_file.name) + r_script_file.write(R_SCRIPT) + + command = [ + "Rscript", + str(r_script_path), + function_name, + "--spe_path", str(spe_path), + "--output_path", str(output_path), + "--width", str(plot_width), + "--height", str(plot_height), + "--json_args", json.dumps(json_args), + ] + + command_executed = " ".join(shlex.quote(c) for c in command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + output_files = {"plot": str(output_path)} if output_path.exists() else {} + + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + 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: + # This error occurs if the R script returns a non-zero exit code + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {}, + } + finally: + # Clean up the temporary R script file + r_script_path.unlink() + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_ggspavis' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def ggspavis_plot_spots( + spe_path: Path, + output_filename: str, + fill: Optional[str] = None, + highlight: Optional[str] = None, + facet_by: Optional[str] = None, + assay: str = "logcounts", + palette: str = "viridis", + point_size: float = 1.5, + point_alpha: float = 1.0, + plot_width: float = 7.0, + plot_height: float = 7.0, +): + """ + Generates a spatial plot of spots/capture locations using ggspavis::plotSpots. + + Args: + spe_path: Path to the input SpatialExperiment object (.rds file). + output_filename: Name of the output plot file (e.g., 'plot.png'). + fill: Column name in colData or a feature name to use for spot fill color. + highlight: Column name in colData to use for highlighting spots. + facet_by: Column name in colData to use for faceting the plot. + assay: Name of the assay to use if 'fill' is a feature name. + palette: Color palette for continuous values (e.g., 'viridis', 'magma'). + point_size: Size of the points representing spots. + point_alpha: Alpha transparency of the points. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + """ + # Input validation + if not spe_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_path}") + if point_size <= 0: + raise ValueError("point_size must be positive.") + if not (0.0 <= point_alpha <= 1.0): + raise ValueError("point_alpha must be between 0.0 and 1.0.") + + # Prepare arguments for the R function + json_args = { + "fill": fill, + "highlight": highlight, + "facet_by": facet_by, + "assay": assay, + "palette": palette, + "point_size": point_size, + "point_alpha": point_alpha, + } + # Filter out None values so they are not passed in the JSON + json_args = {k: v for k, v in json_args.items() if v is not None} + + output_path = Path(output_filename) + + return _run_ggspavis( + function_name="plotSpots", + spe_path=spe_path, + output_path=output_path, + plot_width=plot_width, + plot_height=plot_height, + json_args=json_args, + ) + + +@mcp.tool() +def ggspavis_plot_feature( + spe_path: Path, + output_filename: str, + feature: str, + assay: str = "logcounts", + platform: Literal["Visium", "ST", "VisiumHD", "mIF", "seqFISH", "MERFISH", "Xenium"] = "Visium", + palette: str = "viridis", + point_size: float = 1.5, + plot_width: float = 7.0, + plot_height: float = 7.0, +): + """ + Visualizes the expression of a single feature (e.g., gene) in spatial context using ggspavis::plotFeature. + + Args: + spe_path: Path to the input SpatialExperiment object (.rds file). + output_filename: Name of the output plot file (e.g., 'feature_plot.png'). + feature: Name of the feature (gene) to plot from the specified assay. + assay: Name of the assay containing the feature. + platform: The spatial transcriptomics platform. + palette: Color palette for continuous expression values. + point_size: Size of the points. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + """ + # Input validation + if not spe_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_path}") + if not feature: + raise ValueError("A feature name must be provided.") + + # Prepare arguments for the R function + json_args = { + "feature": feature, + "assay": assay, + "platform": platform, + "palette": palette, + "point_size": point_size, + } + json_args = {k: v for k, v in json_args.items() if v is not None} + + output_path = Path(output_filename) + + return _run_ggspavis( + function_name="plotFeature", + spe_path=spe_path, + output_path=output_path, + plot_width=plot_width, + plot_height=plot_height, + json_args=json_args, + ) + + +@mcp.tool() +def ggspavis_plot_dim_red( + spe_path: Path, + output_filename: str, + reduction_type: str, + x_axis: Optional[str] = None, + y_axis: Optional[str] = None, + color_by: Optional[str] = None, + shape_by: Optional[str] = None, + assay: str = "logcounts", + point_size: float = 1.5, + plot_width: float = 7.0, + plot_height: float = 7.0, +): + """ + Plots dimensionality reduction results (e.g., UMAP, PCA) using ggspavis::plotDimRed. + + Args: + spe_path: Path to the input SpatialExperiment object (.rds file). + output_filename: Name of the output plot file (e.g., 'umap.png'). + reduction_type: Name of the dimensionality reduction result in reducedDims(spe). + x_axis: Column name for the x-axis (e.g., 'UMAP_1'). Defaults to type_1. + y_axis: Column name for the y-axis (e.g., 'UMAP_2'). Defaults to type_2. + color_by: Column name in colData or feature name to use for point color. + shape_by: Column name in colData to use for point shape. + assay: Name of assay to use if 'color_by' is a feature name. + point_size: Size of the points. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + """ + # Input validation + if not spe_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_path}") + if not reduction_type: + raise ValueError("A reduction_type must be provided.") + + # Prepare arguments for the R function + json_args = { + "type": reduction_type, + "x_axis": x_axis, + "y_axis": y_axis, + "color_by": color_by, + "shape_by": shape_by, + "assay": assay, + "point_size": point_size, + } + json_args = {k: v for k, v in json_args.items() if v is not None} + + output_path = Path(output_filename) + + return _run_ggspavis( + function_name="plotDimRed", + spe_path=spe_path, + output_path=output_path, + plot_width=plot_width, + plot_height=plot_height, + json_args=json_args, + ) + + +@mcp.tool() +def ggspavis_plot_label( + spe_path: Path, + output_filename: str, + label: str, + platform: Literal["Visium", "ST", "VisiumHD", "mIF", "seqFISH", "MERFISH", "Xenium"] = "Visium", + palette: Optional[str] = None, + point_size: float = 1.5, + plot_width: float = 7.0, + plot_height: float = 7.0, +): + """ + Visualizes spatial clusters or other categorical labels using ggspavis::plotLabel. + + Args: + spe_path: Path to the input SpatialExperiment object (.rds file). + output_filename: Name of the output plot file (e.g., 'clusters.png'). + label: Column name in colData containing the labels to plot. + platform: The spatial transcriptomics platform. + palette: Optional color palette for labels. If None, ggplot2 default is used. + point_size: Size of the points. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + """ + # Input validation + if not spe_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_path}") + if not label: + raise ValueError("A label column name must be provided.") + + # Prepare arguments for the R function + json_args = { + "label": label, + "platform": platform, + "palette": palette, + "point_size": point_size, + } + json_args = {k: v for k, v in json_args.items() if v is not None} + + output_path = Path(output_filename) + + return _run_ggspavis( + function_name="plotLabel", + spe_path=spe_path, + output_path=output_path, + plot_width=plot_width, + plot_height=plot_height, + json_args=json_args, + ) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e2e48c22659a19491db77b7dbe62b14178cfbf2d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_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-ggspavis/app/bioconductor-ggspavis_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_ggspavis' + + +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/Biomni/mcp_generated/mcp_bioconductor-ggspavis/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggspavis/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..941920ed4e6d089e1a71dab40598b95cf6239402 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ggspavis: + build: . + image: mcp-bioconductor-ggspavis:latest + container_name: mcp-bioconductor-ggspavis + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ggspavis + 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/Biomni/mcp_generated/mcp_bioconductor-ggspavis/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..282746043f724ae679e2f7e8ad158a7cb4b97be5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ggspavis + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggspavis/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggspavis/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggtree/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-ggtree/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0399891b152181e15ed14a44c4e515af571b78aa --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggtree/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-ggtree via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ggtree -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-ggtree_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-ggtree_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-ggtree_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggtree/app/bioconductor-ggtree_server.py b/Biomni/mcp_generated/mcp_bioconductor-ggtree/app/bioconductor-ggtree_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e0b6b9a9c93df09d826c53c202b9b1dbc33801 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggtree/app/bioconductor-ggtree_server.py @@ -0,0 +1,216 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any +import os + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_ggtree' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_ggtree_script( + r_script_content: str, + input_tree_file: Optional[Path] = None, + input_annotation_file: Optional[Path] = None, + output_image_format: str = "png", + image_width: int = 800, + image_height: int = 600, + output_filename_prefix: str = "ggtree_plot", +) -> Dict[str, Any]: + """ + Executes a custom R script using the bioconductor-ggtree package for phylogenetic tree visualization. + + This tool provides a flexible way to leverage ggtree's capabilities by allowing + users to provide arbitrary R code. It also facilitates common tasks like + loading tree and annotation files and saving plots. + + Note: The 'bioconductor-ggtree' package is an R library and does not expose + direct command-line functions or subcommands. This MCP tool provides a + generic R script execution environment where 'ggtree' and its dependencies + are available. Users are expected to provide R code that utilizes 'ggtree' + functions. + + Args: + r_script_content: A string containing the R code to execute. This script + should assume 'ggtree', 'treeio', 'ggplot2', and 'dplyr' + are loaded. It can access input files via variables + `input_tree_file` and `input_annotation_file` (which + will contain the POSIX paths as strings). The script + should write any desired output files to the current + working directory. + input_tree_file: Optional path to a phylogenetic tree file (e.g., Newick, Nexus). + If provided, its POSIX path will be available as the + `input_tree_file` variable in the R script. + input_annotation_file: Optional path to an annotation data file (e.g., CSV, TSV). + If provided, its POSIX path will be available as the + `input_annotation_file` variable in the R script. + output_image_format: The desired format for the output image. Supported: "png", "pdf", "svg", "jpeg", "tiff", "bmp". + This format will be used for the default `ggsave` call + if a ggplot object `p` is found and not explicitly saved + by `r_script_content`. + image_width: Width of the output image. For raster formats (png, jpeg, etc.), + this is in pixels. For vector formats (pdf, svg), this is + converted to inches (assuming 96 DPI for conversion from pixels). + image_height: Height of the output image. Similar to `image_width`. + output_filename_prefix: A prefix for the output image file. The full filename + will be '{prefix}.{format}'. This is used for the + default `ggsave` call. + + Returns: + A dictionary containing: + - command_executed: The Rscript command that was run. + - stdout: Standard output from the R script. + - stderr: Standard error from the R script. + - output_files: A list of paths to any generated output files. + - error: An error message if the R script execution failed. + """ + # Input validation + if not r_script_content.strip(): + raise ValueError("r_script_content cannot be empty.") + + if input_tree_file: + if not input_tree_file.is_file(): + raise FileNotFoundError(f"Input tree file not found: {input_tree_file}") + input_tree_file_posix = input_tree_file.as_posix() + else: + input_tree_file_posix = "" + + if input_annotation_file: + if not input_annotation_file.is_file(): + raise FileNotFoundError(f"Input annotation file not found: {input_annotation_file}") + input_annotation_file_posix = input_annotation_file.as_posix() + else: + input_annotation_file_posix = "" + + supported_formats = {"png", "pdf", "svg", "jpeg", "tiff", "bmp"} + if output_image_format.lower() not in supported_formats: + raise ValueError(f"Unsupported output image format: {output_image_format}. " + f"Supported formats are: {', '.join(supported_formats)}") + + if image_width <= 0: + raise ValueError("Image width must be a positive integer.") + if image_height <= 0: + raise ValueError("Image height must be a positive integer.") + if not output_filename_prefix: + raise ValueError("Output filename prefix cannot be empty.") + + with tempfile.TemporaryDirectory() as tmpdir: + work_dir = Path(tmpdir) + + # Define output image path for default ggsave + output_image_name = f"{output_filename_prefix}.{output_image_format.lower()}" + + # Construct the R script + r_code = f""" + # Load necessary libraries + suppressPackageStartupMessages(library(ggtree)) + suppressPackageStartupMessages(library(treeio)) + suppressPackageStartupMessages(library(ggplot2)) + suppressPackageStartupMessages(library(dplyr)) # Often useful for data manipulation + + # Set working directory for outputs + setwd("{work_dir.as_posix()}") + + # Make input file paths available as R variables + input_tree_file <- if ("{input_tree_file_posix}" != "") {{ + "{input_tree_file_posix}" + }} else {{ + NULL + }} + input_annotation_file <- if ("{input_annotation_file_posix}" != "") {{ + "{input_annotation_file_posix}" + }} else {{ + NULL + }} + + # Parameters for default ggsave + output_image_name_param <- "{output_image_name}" + image_width_param <- {image_width} + image_height_param <- {image_height} + output_image_format_param <- "{output_image_format.lower()}" + + # Determine units and DPI for ggsave based on format + units_val <- "in" # Default for vector graphics + dpi_val <- NULL # Default for vector graphics + + if (output_image_format_param %in% c("png", "jpeg", "tiff", "bmp")) {{ + units_val <- "px" + dpi_val <- 300 # Common DPI for raster images + }} else {{ # pdf, svg, etc. + # Convert pixels to inches for vector formats if input was in pixels + # Assuming 96 DPI for screen pixels to inches conversion if no specific DPI is given + image_width_param <- image_width_param / 96 + image_height_param <- image_height_param / 96 + }} + + # User-provided R script content + # This is where the user's custom ggtree logic should go. + # The user's script can use 'input_tree_file', 'input_annotation_file', + # 'output_image_name_param', 'image_width_param', 'image_height_param', + # 'units_val', 'dpi_val' if they wish to override or extend the default + # saving behavior. + {r_script_content} + + # Attempt to save the last ggplot object 'p' if it exists and + # the user's script hasn't explicitly saved a plot with the default name. + # This provides a fallback for simple plotting tasks. + if (exists("p") && inherits(p, "ggplot")) {{ + if (!file.exists(output_image_name_param)) {{ # Only save if user script didn't already save to this name + message(paste0("Saving ggplot object 'p' to ", output_image_name_param, " using default parameters.")) + ggsave(output_image_name_param, plot = p, width = image_width_param, height = image_height_param, units = units_val, dpi = dpi_val) + }} else {{ + message(paste0("File '", output_image_name_param, "' already exists. Skipping default ggsave.")) + }} + }} else {{ + message("No 'p' (ggplot object) found or saved by user script. No default image output will be generated.") + }} + """ + + r_script_file = work_dir / "run_ggtree.R" + r_script_file.write_text(r_code) + + command = ["Rscript", r_script_file.as_posix()] + + # Execute the R script + try: + process = subprocess.run( + command, + cwd=work_dir, + capture_output=True, + text=True, + check=True, + env=os.environ # Inherit environment to ensure R is found + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Rscript execution failed with exit code {e.returncode}", + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Rscript command not found. Is R installed and in PATH?", + "output_files": [], + "error": "Rscript executable not found.", + } + + # Collect output files + output_files = [f.as_posix() for f in work_dir.iterdir() if f.is_file() and f != r_script_file] + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggtree/app/bioconductor-ggtree_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-ggtree/app/bioconductor-ggtree_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..110bd5c5960a4a016806eec7461988b2a17f973f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggtree/app/bioconductor-ggtree_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-ggtree/app/bioconductor-ggtree_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_ggtree' + + +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/Biomni/mcp_generated/mcp_bioconductor-ggtree/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ggtree/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggtree/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggtree/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-ggtree/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b26bd3cd63d1531de3d839f1af8f1c8289770276 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggtree/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ggtree: + build: . + image: mcp-bioconductor-ggtree:latest + container_name: mcp-bioconductor-ggtree + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ggtree + 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/Biomni/mcp_generated/mcp_bioconductor-ggtree/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-ggtree/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f86f271d340f923d10117919ff269c0123223824 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggtree/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ggtree + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-ggtree/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-ggtree/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-ggtree/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1c5f58d07fa6b4051eee2ddb17e438690e1642f2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/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-glmgampoi via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-glmgampoi -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-glmgampoi_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-glmgampoi_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-glmgampoi_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_server.py b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9d9fc68e8654bac59056b457a5b56c02c254c7ce --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_server.py @@ -0,0 +1,270 @@ +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_glmgampoi' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def fit_glm_gp( + data_path: str, + output_rds: str, + design_formula: str = "~1", + col_data_path: Optional[str] = None, + size_factors: str = "normed_sum", + overdispersion_shrinkage: bool = True, + on_disk: bool = False, +) -> Dict[str, Any]: + """ + Fit a Gamma-Poisson Generalized Linear Model (GLM) to count data. + Designed for large datasets like single-cell RNA-seq. + + Args: + data_path: Path to the input count matrix (CSV or TSV). Rows are genes, columns are samples. + output_rds: Path where the fitted model object (RDS format) will be saved. + design_formula: R-style formula string (e.g., '~ condition'). + col_data_path: Optional path to sample metadata (CSV or TSV). Rows must match columns in data_path. + size_factors: Method for normalization. Options: 'normed_sum', 'poscounts', 'median', or 'none'. + overdispersion_shrinkage: Whether to shrink overdispersion estimates towards a global trend. + on_disk: If True, uses HDF5-backed matrices to minimize memory usage for very large datasets. + """ + # Input validation + input_p = Path(data_path) + if not input_p.exists(): + raise FileNotFoundError(f"Input data file not found: {data_path}") + + output_p = Path(output_rds) + output_p.parent.mkdir(parents=True, exist_ok=True) + + col_data_arg = "NULL" + if col_data_path: + col_p = Path(col_data_path) + if not col_p.exists(): + raise FileNotFoundError(f"Metadata file not found: {col_data_path}") + col_data_arg = f"read_data('{col_data_path}')" + + # Map size_factors string to R logic + sf_val = f"'{size_factors}'" + if size_factors.lower() == "none": + sf_val = "FALSE" + + # Construct R script + r_script = f""" + library(glmGamPoi) + + read_data <- function(path) {{ + if (grepl('\\\\.tsv$', path, ignore.case = TRUE)) {{ + return(read.delim(path, row.names = 1, check.names = FALSE)) + }} else {{ + return(read.csv(path, row.names = 1, check.names = FALSE)) + }} + }} + + counts <- as.matrix(read_data('{data_path}')) + col_data <- {col_data_arg} + + fit <- glm_gp( + data = counts, + design = as.formula('{design_formula}'), + col_data = col_data, + size_factors = {sf_val}, + overdispersion_shrinkage = {str(overdispersion_shrinkage).upper()}, + on_disk = {str(on_disk).upper()} + ) + + saveRDS(fit, '{output_rds}') + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"glm_gp on {data_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def test_differential_expression( + fit_rds_path: str, + output_csv: str, + contrast: Optional[str] = None, + reduced_design: Optional[str] = None, +) -> Dict[str, Any]: + """ + Perform differential expression (DE) testing using a fitted glmGamPoi model. + + Args: + fit_rds_path: Path to the RDS file generated by fit_glm_gp. + output_csv: Path where the DE results (CSV) will be saved. + contrast: String specifying the contrast to test (e.g., 'condition_B - condition_A'). + reduced_design: Optional R-style formula for a reduced model to perform a Likelihood Ratio Test. + """ + fit_p = Path(fit_rds_path) + if not fit_p.exists(): + raise FileNotFoundError(f"Fitted model file not found: {fit_rds_path}") + + output_p = Path(output_csv) + output_p.parent.mkdir(parents=True, exist_ok=True) + + contrast_arg = "NULL" + if contrast: + # If it looks like a simple string, wrap in quotes; if it's complex, R handles it + contrast_arg = f"'{contrast}'" + + reduced_arg = "NULL" + if reduced_design: + reduced_arg = f"as.formula('{reduced_design}')" + + r_script = f""" + library(glmGamPoi) + fit <- readRDS('{fit_rds_path}') + res <- test_de( + fit, + contrast = {contrast_arg}, + reduced_design = {reduced_arg} + ) + write.csv(res, '{output_csv}', row.names = TRUE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"test_de on {fit_rds_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def get_overdispersion_estimates( + fit_rds_path: str, + output_csv: str +) -> Dict[str, Any]: + """ + Extract overdispersion estimates for each gene from a fitted glmGamPoi model. + + Args: + fit_rds_path: Path to the RDS file generated by fit_glm_gp. + output_csv: Path where the overdispersion estimates (CSV) will be saved. + """ + fit_p = Path(fit_rds_path) + if not fit_p.exists(): + raise FileNotFoundError(f"Fitted model file not found: {fit_rds_path}") + + r_script = f""" + library(glmGamPoi) + fit <- readRDS('{fit_rds_path}') + # Extract overdispersion and gene names + df <- data.frame( + gene = rownames(fit$Beta), + overdispersion = fit$overdispersions + ) + write.csv(df, '{output_csv}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Extract overdispersion from {fit_rds_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def predict_glm_gp( + fit_rds_path: str, + output_csv: str, + newdata_path: Optional[str] = None, + type: str = "link" +) -> Dict[str, Any]: + """ + Predict values (e.g., log-counts or counts) from a fitted glmGamPoi model. + + Args: + fit_rds_path: Path to the RDS file generated by fit_glm_gp. + output_csv: Path where the predictions (CSV) will be saved. + newdata_path: Optional path to new sample metadata (CSV/TSV). If NULL, uses original data. + type: Type of prediction. 'link' (log-scale) or 'response' (original count scale). + """ + fit_p = Path(fit_rds_path) + if not fit_p.exists(): + raise FileNotFoundError(f"Fitted model file not found: {fit_rds_path}") + + newdata_arg = "NULL" + if newdata_path: + if not Path(newdata_path).exists(): + raise FileNotFoundError(f"New data file not found: {newdata_path}") + newdata_arg = f"read.csv('{newdata_path}', row.names = 1)" + + r_script = f""" + library(glmGamPoi) + fit <- readRDS('{fit_rds_path}') + newdata <- {newdata_arg} + preds <- predict(fit, newdata = newdata, type = '{type}') + write.csv(preds, '{output_csv}') + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"predict on {fit_rds_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9d4c42f8a02e1aed515e42770354c7b4b6aaa516 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_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-glmgampoi/app/bioconductor-glmgampoi_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_glmgampoi' + + +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/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7e864b31d24f33ded903f987db861839ba126d44 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-glmgampoi: + build: . + image: mcp-bioconductor-glmgampoi:latest + container_name: mcp-bioconductor-glmgampoi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-glmgampoi + 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/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1515ec182b974acd906df6c00c468fa2ebab7a98 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-glmgampoi + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-glmgampoi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-go.db/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-go.db/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2069a4e8592c1da90c7837bb6d4c45e57bd872d8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-go.db/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-go.db via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-go.db -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-go.db_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-go.db_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-go.db_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py b/Biomni/mcp_generated/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0820278a2907da2e80f7584bd0470baaf5dd3694 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py @@ -0,0 +1,196 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# MCP decorator is not imported as per instructions. +# It is assumed to be available in the execution environment. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_go_db' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def list_go_db_columns() -> Dict[str, Any]: + """ + Lists all available columns for querying in the Bioconductor GO.db. + + This function executes an R script to load the GO.db package and + extract the names of all queryable columns. It is useful for discovering + what data can be retrieved using the `query_go_db` function. + + Requirements: + - R must be installed and in the system's PATH. + - The R packages 'BiocManager', 'AnnotationDbi', and 'GO.db' must be installed. + (e.g., in R: BiocManager::install(c("AnnotationDbi", "GO.db"))) + """ + r_script = "library(GO.db); cat(columns(GO.db), sep='\\n')" + command = ["Rscript", "-e", r_script] + command_executed = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # The columns are returned as a newline-separated string + columns_list = result.stdout.strip().split('\n') + return { + "command_executed": command_executed, + "stdout": f"Available columns: {', '.join(columns_list)}", + "stderr": result.stderr, + "columns": columns_list, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' not found. Please ensure R is installed and in your PATH.", + "error": "Dependency not found" + } + except subprocess.CalledProcessError as e: + stderr = e.stderr + if "there is no package called" in stderr: + stderr += "\n\nHint: Please ensure the 'GO.db' and 'AnnotationDbi' R packages are installed." + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": stderr, + "error": "R script execution failed" + } + +@mcp.tool() +def query_go_db( + go_ids: List[str], + columns: Optional[List[str]] = None, + output_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Query the Bioconductor GO.db to retrieve information about Gene Ontology terms. + + This tool uses R/Bioconductor's GO.db annotation package to fetch details + for a given list of GO IDs. You can specify which columns of data to retrieve. + + Requirements: + - R must be installed and in the system's PATH. + - The R packages 'BiocManager', 'AnnotationDbi', and 'GO.db' must be installed. + (e.g., in R: BiocManager::install(c("AnnotationDbi", "GO.db"))) + + Args: + go_ids: A list of Gene Ontology (GO) IDs to query (e.g., ['GO:0005575', 'GO:0008150']). + columns: A list of columns to retrieve. Defaults to ['GOID', 'TERM', 'DEFINITION', 'ONTOLOGY']. + Use the `list_go_db_columns` tool to see all available columns. + output_file: Optional path to save the output as a tab-separated (TSV) file. + If not provided, the output is returned in stdout. + """ + # --- Input Validation --- + if not go_ids: + raise ValueError("The 'go_ids' list cannot be empty.") + + for go_id in go_ids: + if not isinstance(go_id, str) or not go_id.startswith("GO:"): + raise ValueError(f"Invalid GO ID format: '{go_id}'. Expected format is 'GO:#######'.") + + if columns is None: + # Default columns provide the most common information + columns_to_query = ["GOID", "TERM", "DEFINITION", "ONTOLOGY"] + else: + if not isinstance(columns, list) or not all(isinstance(c, str) for c in columns): + raise TypeError("The 'columns' parameter must be a list of strings.") + columns_to_query = columns + + # --- R Script Construction --- + # Convert Python lists to R vector syntax: c("item1", "item2") + r_go_ids = 'c({})'.format(','.join(f'"{gid}"' for gid in go_ids)) + r_columns = 'c({})'.format(','.join(f'"{col}"' for col in columns_to_query)) + + # Using a temporary file for the output if no output_file is specified by the user + # This avoids complex stdout redirection and ensures clean capture + temp_dir = tempfile.TemporaryDirectory() + final_output_path = Path(output_file) if output_file else Path(temp_dir.name) / "go_query_results.tsv" + + r_script = f""" + # Suppress package startup messages for cleaner output + suppressPackageStartupMessages(library(AnnotationDbi)) + suppressPackageStartupMessages(library(GO.db)) + + go_keys <- {r_go_ids} + cols_to_get <- {r_columns} + output_path <- "{str(final_output_path)}" + + # Perform the query + results <- tryCatch( + AnnotationDbi::select(GO.db, keys=go_keys, columns=cols_to_get, keytype="GOID"), + error = function(e) {{ + write(paste("Error during AnnotationDbi::select:", e$message), stderr()) + return(NULL) + }} + ) + + # Write results to the specified output file + if (!is.null(results)) {{ + write.table( + results, + file=output_path, + sep="\\t", + row.names=FALSE, + quote=FALSE + ) + }} + """ + + command = ["Rscript", "-e", r_script] + command_executed = " ".join(command) + output_files_list = [] + + try: + # --- Subprocess Execution --- + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + + stdout_content = "" + if final_output_path.exists() and final_output_path.stat().st_size > 0: + output_files_list.append(str(final_output_path)) + # If no output file was requested by the user, read the temp file content for stdout + if not output_file: + stdout_content = final_output_path.read_text() + else: + # Handle cases where the R script runs but produces no output (e.g., no matches) + stdout_content = "Query executed successfully, but no results were found for the given GO IDs." + + return { + "command_executed": command_executed, + "stdout": stdout_content, + "stderr": result.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' not found. Please ensure R is installed and in your PATH.", + "error": "Dependency not found" + } + except subprocess.CalledProcessError as e: + stderr = e.stderr + if "there is no package called" in stderr: + stderr += "\n\nHint: Please ensure the 'GO.db' and 'AnnotationDbi' R packages are installed." + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": stderr, + "error": "R script execution failed" + } + finally: + # Clean up the temporary directory + temp_dir.cleanup() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-go.db/app/bioconductor-go.db_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-go.db/app/bioconductor-go.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b4e43362caa03c90be682b9ccb66f63a80104a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-go.db/app/bioconductor-go.db_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-go.db/app/bioconductor-go.db_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_go_db' + + +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/Biomni/mcp_generated/mcp_bioconductor-go.db/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-go.db/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-go.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-go.db/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-go.db/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bcb222a73c2f27a64f265287d9ff4aa040928e68 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-go.db/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-go.db: + build: . + image: mcp-bioconductor-go.db:latest + container_name: mcp-bioconductor-go.db + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-go.db + 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/Biomni/mcp_generated/mcp_bioconductor-go.db/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-go.db/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0607214ee0c410fe2635325e9264b0cba5fd89bb --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-go.db/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-go.db + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-go.db/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-go.db/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-go.db/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-gosemsim/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..79759355a85d632d7922ea3c56930957dd4d59fa --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/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-gosemsim via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-gosemsim -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-gosemsim_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-gosemsim_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-gosemsim_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fedd4cfb08b6f46924b77ac989fabe3318468caa --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py @@ -0,0 +1,281 @@ +import subprocess +import json +import tempfile +from pathlib import Path +from typing import List, Optional, Literal, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_gosemsim' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def go_similarity( + term1: str, + term2: str, + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity between two GO terms using GOSemSim. + + Args: + term1: First GO term ID (e.g., 'GO:0004022'). + term2: Second GO term ID (e.g., 'GO:0005515'). + org_db: The annotation OrgDb package (e.g., 'org.Hs.eg.db' for human). + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method ("Resnik", "Lin", "Rel", "Jiang", or "Wang"). + keytype: Key type of the gene identifiers in the OrgDb. + """ + if not term1.startswith("GO:") or not term2.startswith("GO:"): + return {"error": "GO terms must start with 'GO:' prefix."} + + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim <- goSim('{term1}', '{term2}', semData=hsGO, measure='{measure}') + cat(sim) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def mgo_similarity( + terms: List[str], + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity matrix for a list of GO terms. + + Args: + terms: List of GO term IDs. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + keytype: Key type of the gene identifiers. + """ + terms_r = 'c("' + '","'.join(terms) + '")' + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim_matrix <- mgoSim({terms_r}, semData=hsGO, measure='{measure}', combine=NULL) + write.csv(sim_matrix, row.names=TRUE) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def gene_similarity( + gene1: str, + gene2: str, + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity between two genes based on their GO annotations. + + Args: + gene1: First gene ID. + gene2: Second gene ID. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + combine: Strategy to combine similarities of multiple GO terms ("max", "avg", "rcmax", "BMA"). + keytype: Key type of the gene identifiers (e.g., 'ENTREZID', 'SYMBOL'). + """ + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim <- geneSim('{gene1}', '{gene2}', semData=hsGO, measure='{measure}', combine='{combine}') + print(sim) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def mgene_similarity( + genes: List[str], + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity matrix for a list of genes. + + Args: + genes: List of gene IDs. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + combine: Strategy to combine similarities. + keytype: Key type of the gene identifiers. + """ + genes_r = 'c("' + '","'.join(genes) + '")' + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim_matrix <- mgeneSim({genes_r}, semData=hsGO, measure='{measure}', combine='{combine}') + write.csv(sim_matrix, row.names=TRUE) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def cluster_similarity( + cluster1: List[str], + cluster2: List[str], + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity between two clusters (sets) of genes. + + Args: + cluster1: List of gene IDs in the first cluster. + cluster2: List of gene IDs in the second cluster. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + combine: Strategy to combine similarities. + keytype: Key type of the gene identifiers. + """ + c1_r = 'c("' + '","'.join(cluster1) + '")' + c2_r = 'c("' + '","'.join(cluster2) + '")' + + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim <- clusterSim({c1_r}, {c2_r}, semData=hsGO, measure='{measure}', combine='{combine}') + cat(sim) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def mcluster_similarity( + clusters_json: str, + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity matrix between multiple clusters of genes. + + Args: + clusters_json: A JSON string representing a dictionary where keys are cluster names + and values are lists of gene IDs. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + combine: Strategy to combine similarities. + keytype: Key type of the gene identifiers. + """ + try: + clusters_dict = json.loads(clusters_json) + except json.JSONDecodeError: + return {"error": "Invalid JSON format for clusters_json."} + + # Construct R list of character vectors + r_list_elements = [] + for name, genes in clusters_dict.items(): + genes_str = 'c("' + '","'.join(genes) + '")' + r_list_elements.append(f'"{name}" = {genes_str}') + + clusters_r = "list(" + ", ".join(r_list_elements) + ")" + + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + clusters <- {clusters_r} + sim_matrix <- mclusterSim(clusters, semData=hsGO, measure='{measure}', combine='{combine}') + write.csv(sim_matrix, row.names=TRUE) + """ + + return _execute_r_script(r_script) + +def _execute_r_script(script_content: str): + """ + Internal helper to execute R code via Rscript. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(script_content) + tmp_path = tmp.name + + try: + # Note: We assume Rscript is in the PATH and GOSemSim is installed. + # If using a specific conda environment, the user should run the MCP server within it. + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R execution failed. Ensure R and GOSemSim are installed and the OrgDb package is available.", + "status": "error" + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def list_supported_orgdbs(): + """ + Returns a list of commonly used Bioconductor OrgDb packages for GOSemSim. + """ + org_dbs = { + "human": "org.Hs.eg.db", + "mouse": "org.Mm.eg.db", + "rat": "org.Rn.eg.db", + "fly": "org.Dm.eg.db", + "zebrafish": "org.Dr.eg.db", + "yeast": "org.Sc.sgd.db", + "arabidopsis": "org.At.tair.db", + "chicken": "org.Gg.eg.db", + "bovine": "org.Bt.eg.db", + "worm": "org.Ce.eg.db", + "pig": "org.Ss.eg.db", + "rhesus": "org.Mmu.eg.db" + } + return {"supported_org_dbs": org_dbs} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ec2c6a3ac8dc257a5833f2d70b3a4cc04a0ac677 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_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-gosemsim/app/bioconductor-gosemsim_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_gosemsim' + + +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/Biomni/mcp_generated/mcp_bioconductor-gosemsim/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-gosemsim/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e0264312aed56c58603128d118ddb6f05d42616d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-gosemsim: + build: . + image: mcp-bioconductor-gosemsim:latest + container_name: mcp-bioconductor-gosemsim + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-gosemsim + 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/Biomni/mcp_generated/mcp_bioconductor-gosemsim/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f13aa43e05a5c4edac218b82b7b0981931e9030 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-gosemsim + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-gosemsim/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gosemsim/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-graph/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-graph/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d094aacd7f9cef99a6c0332a22fdfeb4a493e2f8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-graph/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-graph via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-graph -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-graph_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-graph_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-graph_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-graph/app/bioconductor-graph_server.py b/Biomni/mcp_generated/mcp_bioconductor-graph/app/bioconductor-graph_server.py new file mode 100644 index 0000000000000000000000000000000000000000..43a48a38c2eb82db6221e7d6fddbe6069effec36 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-graph/app/bioconductor-graph_server.py @@ -0,0 +1,135 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List + +# Assuming mcp is available in the environment +# import mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_graph' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def rscript( + script_file: Optional[Path] = None, + expression: Optional[str] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[List[str]] = None, + slave: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + save: bool = False, + no_renviron: bool = False, +): + """ + Executes an R script or a given R expression using the Rscript front-end. + + This tool serves as a wrapper around the command-line Rscript utility, + allowing for non-interactive execution of R code. You must provide either + a path to an R script file or an R expression string. + + Args: + script_file: Path to the R script file to be executed. + expression: A string containing one or more R expressions to be evaluated. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, prints more information on progress. Corresponds to --verbose. + default_packages: A list of R packages to be attached on startup. + Defaults to 'datasets,utils,grDevices,graphics,stats,methods'. + slave: If True, makes R run as quietly as possible. Corresponds to --slave. + no_environ: If True, does not read the site and user environment files. + no_site_file: If True, does not read the site-wide Rprofile. + no_init_file: If True, does not read the user Rprofile. + restore: If True, restores the previously saved workspace. + save: If True, saves the workspace at the end of the session. + no_renviron: If True, does not read the site or user Renviron files. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not (script_file or expression): + raise ValueError("You must provide either 'script_file' or 'expression'.") + if script_file and expression: + raise ValueError("You cannot provide both 'script_file' and 'expression'.") + + 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 slave: + cmd.append("--slave") + 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 save: + cmd.append("--save") + if no_renviron: + cmd.append("--no-Renviron") + + if default_packages: + packages_str = ",".join(default_packages) + cmd.append(f"--default-packages={packages_str}") + + if expression: + cmd.extend(["-e", expression]) + elif script_file: + cmd.append(str(script_file)) + + if script_args: + cmd.extend(script_args) + + command_executed = shlex.join(cmd) + + # 3. Subprocess Execution + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=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, + "output_files": [] + } + + # 4. Structured Result Return + # Rscript itself doesn't have a dedicated output file parameter. + # Any files created are the result of the script's own logic. + # We return an empty list here, as the tool wrapper cannot know what files the script might create. + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-graph/app/bioconductor-graph_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-graph/app/bioconductor-graph_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b7cd5f1f2ed4d2640cf6c937ec980cdde5cac4a2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-graph/app/bioconductor-graph_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-graph/app/bioconductor-graph_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_graph' + + +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/Biomni/mcp_generated/mcp_bioconductor-graph/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-graph/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-graph/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-graph/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-graph/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e381d6f96261f88e640b44f179e11c5daaf6a92d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-graph/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-graph: + build: . + image: mcp-bioconductor-graph:latest + container_name: mcp-bioconductor-graph + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-graph + 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/Biomni/mcp_generated/mcp_bioconductor-graph/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-graph/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bf5c6395ba1581a2cb6bfed8ca295707e071d324 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-graph/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-graph + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-graph/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-graph/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-graph/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-gsva/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-gsva/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8ebd79da057998281de6f71ad1cfb659acc1f297 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gsva/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-gsva via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-gsva -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-gsva_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-gsva_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-gsva_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-gsva/app/bioconductor-gsva_server.py b/Biomni/mcp_generated/mcp_bioconductor-gsva/app/bioconductor-gsva_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2555bb4db6ab89d74deae5f95321f35648cee8e1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gsva/app/bioconductor-gsva_server.py @@ -0,0 +1,215 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Literal, List +import sys + +# MCP decorator placeholder, as per the instructions. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_gsva' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def gsva( + expr_file: Path, + gene_sets_file: Path, + output_file: Optional[Path] = None, + method: Literal["gsva", "ssgsea", "zscore", "plage"] = "gsva", + kcdf: Literal["Gaussian", "Poisson", "none"] = "Gaussian", + abs_ranking: bool = False, + min_sz: int = 1, + max_sz: Optional[int] = None, + parallel_sz: int = 1, + mx_diff: bool = True, + tau: float = 1.0, + ssgsea_norm: bool = True, + verbose: bool = True, +) -> dict: + """ + Performs Gene Set Variation Analysis (GSVA) on gene expression data. + + This tool is a wrapper around the `gsva` function from the Bioconductor GSVA package. + It calculates sample-wise gene set enrichment scores as a function of genes inside and + outside the gene set, respectively. The tool requires R and the 'Rscript' + executable to be in the system's PATH. + + Args: + expr_file: Path to the gene expression data file (e.g., TSV, CSV). + The file should have genes as rows and samples as columns. + The first column must contain unique gene identifiers. + gene_sets_file: Path to the gene sets file in GMT format. + output_file: Optional path for the output TSV file. If not provided, a file + named 'gsva_results.tsv' will be created in a temporary directory + and its path will be returned. + method: The GSVA method to use. + kcdf: Character string denoting the kernel to use during the non-parametric + estimation of the cumulative distribution function of expression + levels across samples. 'Gaussian' is recommended for continuous data, + 'Poisson' for integer counts. + abs_ranking: For 'gsva' method, whether to use absolute values of rankings. + min_sz: Minimum size of the gene sets to be considered. + max_sz: Maximum size of the gene sets to be considered. If None, no maximum size is enforced. + parallel_sz: Number of parallel processes to use (cores). + mx_diff: For 'gsva' and 'ssgsea' methods, whether to calculate enrichment scores + as the difference between the largest positive and negative deviations + from the random walk. + tau: Exponent defining the weight of the tail in the random walk score. + Only used for the 'gsva' method. + ssgsea_norm: For 'ssgsea' method, whether to normalize enrichment scores. + verbose: If True, the R script will print progress messages to stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not expr_file.exists(): + raise FileNotFoundError(f"Expression file not found: {expr_file}") + if not gene_sets_file.exists(): + raise FileNotFoundError(f"Gene sets file not found: {gene_sets_file}") + if min_sz < 0: + raise ValueError("min_sz must be a non-negative integer.") + if max_sz is not None and max_sz < min_sz: + raise ValueError("max_sz must be greater than or equal to min_sz.") + if parallel_sz < 1: + raise ValueError("parallel_sz must be at least 1.") + if tau <= 0 and method == "gsva": + raise ValueError("tau must be a positive number for the 'gsva' method.") + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + + # Define output file path + if output_file: + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + final_output_path = output_file + else: + final_output_path = temp_path / "gsva_results.tsv" + + r_script_path = temp_path / "run_gsva.R" + + # Convert Python types to R-compatible strings + r_abs_ranking = "TRUE" if abs_ranking else "FALSE" + r_mx_diff = "TRUE" if mx_diff else "FALSE" + r_ssgsea_norm = "TRUE" if ssgsea_norm else "FALSE" + r_verbose = "TRUE" if verbose else "FALSE" + r_max_sz = "Inf" if max_sz is None else str(max_sz) + + # --- R Script Generation --- + r_script_content = f""" + # This script automatically installs required Bioconductor packages. + if (!requireNamespace("BiocManager", quietly = TRUE)) + install.packages("BiocManager", repos="http://cran.us.r-project.org") + + packages <- c("GSVA", "GSEABase") + for (pkg in packages) {{ + if (!require(pkg, character.only = TRUE)) {{ + cat(paste("Installing", pkg, "...\\n")) + BiocManager::install(pkg, update=FALSE, ask=FALSE) + library(pkg, character.only = TRUE) + }} + }} + + # --- Arguments --- + expr_file <- "{expr_file.resolve()}" + gene_sets_file <- "{gene_sets_file.resolve()}" + output_file <- "{final_output_path.resolve()}" + method <- "{method}" + kcdf <- "{kcdf}" + abs_ranking <- {r_abs_ranking} + min_sz <- {min_sz} + max_sz <- {r_max_sz} + parallel_sz <- {parallel_sz} + mx_diff <- {r_mx_diff} + tau <- {tau} + ssgsea_norm <- {r_ssgsea_norm} + verbose <- {r_verbose} + + # --- Data Loading --- + if (verbose) cat("Loading expression data from:", expr_file, "\\n") + # Assuming a standard tab-separated file with a header and row names (gene IDs) + expr_data <- tryCatch({{ + as.matrix(read.table(expr_file, header=TRUE, row.names=1, sep='\\t', check.names=FALSE, quote="")) + }}, error = function(e) {{ + # Try with comma separator if tab fails + if (verbose) cat("Failed to read as TSV, trying CSV...\\n") + as.matrix(read.table(expr_file, header=TRUE, row.names=1, sep=',', check.names=FALSE, quote="")) + }}) + + if (verbose) cat("Loading gene sets from:", gene_sets_file, "\\n") + gene_sets <- getGmt(gene_sets_file) + + # --- Run GSVA --- + if (verbose) cat("Running GSVA with method:", method, "\\n") + gsva_results <- gsva( + expr = expr_data, + gset.idx.list = gene_sets, + method = method, + kcdf = kcdf, + abs.ranking = abs_ranking, + min.sz = min_sz, + max.sz = max_sz, + parallel.sz = parallel_sz, + mx.diff = mx_diff, + tau = tau, + ssgsea.norm = ssgsea_norm, + verbose = verbose + ) + + # --- Save Results --- + if (verbose) cat("Saving results to:", output_file, "\\n") + write.table(gsva_results, file=output_file, sep='\\t', quote=FALSE, col.names=NA) + + if (verbose) cat("GSVA analysis completed successfully.\\n") + """ + + with open(r_script_path, "w") as f: + f.write(r_script_content) + + # --- Subprocess Execution --- + command = ["Rscript", str(r_script_path)] + command_str = " ".join(map(str, command)) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=temp_path, + ) + + output_files_list = [str(final_output_path)] if final_output_path.exists() else [] + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + # This happens 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.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-gsva/app/bioconductor-gsva_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-gsva/app/bioconductor-gsva_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bad91b0d57ac3dc54b19222cdfdfee08d8e86414 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gsva/app/bioconductor-gsva_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-gsva/app/bioconductor-gsva_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_gsva' + + +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/Biomni/mcp_generated/mcp_bioconductor-gsva/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-gsva/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b4964f9f87d7439fea449eca0d8b3eb185825066 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gsva/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-gsva: + build: . + image: mcp-bioconductor-gsva:latest + container_name: mcp-bioconductor-gsva + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-gsva + 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/Biomni/mcp_generated/mcp_bioconductor-gsva/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-gsva/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..198d9d117bd9b55b6abc459e12bbedf2ab5a8b35 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gsva/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-gsva + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-gsva/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-gsva/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-gsva/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a2e06873042488f4adf3a3d6e09eb83fc0f670cc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/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-hcatonsildata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-hcatonsildata -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-hcatonsildata_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-hcatonsildata_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-hcatonsildata_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_server.py b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ce33bf01581e3e6c0e78a678a98fb41e2d2097da --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_server.py @@ -0,0 +1,155 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Mock decorator for standalone execution +class mcp: + def tool(func): + return func + +@mcp.tool +def hcatonsildata_load( + output_file: Path, + version: str = "3.1.3", + ensembl: bool = False, + location: bool = True, + output_format: str = "h5ad", +) -> Dict[str, Any]: + """ + Loads the HCATonsilData object from Bioconductor and saves it to a specified file format. + + This tool acts as a wrapper around the R/Bioconductor HCATonsilData package, + which provides access to a SingleCellExperiment object of human tonsil data from the + Human Cell Atlas project. Since the package itself is not a command-line tool, this + function generates and executes an R script to load the data and export it. + + Args: + output_file: The path to the output file where the data object will be saved. + version: The version of the dataset to load. Must be either "3.1.3" or "2.0.0". + ensembl: A boolean indicating whether to use Ensembl identifiers for gene annotation. + If False, gene symbols are used. + location: A boolean indicating whether to download the data to a default + ExperimentHub cache location. + output_format: The format for the output file. Must be either "h5ad" (for AnnData) + or "rds" (for an R Data Serialization file). + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and the path to the output file. + """ + # 1. Input Validation + allowed_versions = ["3.1.3", "2.0.0"] + if version not in allowed_versions: + raise ValueError(f"Invalid version '{version}'. Must be one of {allowed_versions}.") + + allowed_formats = ["h5ad", "rds"] + if output_format not in allowed_formats: + raise ValueError(f"Invalid output_format '{output_format}'. Must be one of {allowed_formats}.") + + if not shutil.which("Rscript"): + raise FileNotFoundError("Rscript executable not found in PATH. R is required to run this tool.") + + # 2. File Path Handling + output_file = Path(output_file).resolve() + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Convert Python bools to R's TRUE/FALSE strings + ensembl_r = str(ensembl).upper() + location_r = str(location).upper() + + # 3. R Script Generation + r_script_content = f""" + # Ensure all required packages are available + if (!requireNamespace("BiocManager", quietly = TRUE)) {{ + install.packages("BiocManager", repos = "http://cran.us.r-project.org") + }} + if (!requireNamespace("HCATonsilData", quietly = TRUE)) {{ + BiocManager::install("HCATonsilData", update=FALSE, ask=FALSE) + }} + + if ("{output_format}" == "h5ad") {{ + if (!requireNamespace("zellkonverter", quietly = TRUE)) {{ + BiocManager::install("zellkonverter", update=FALSE, ask=FALSE) + }} + library(zellkonverter) + }} + + library(HCATonsilData) + library(SingleCellExperiment) + + cat("Loading HCATonsilData version {version}...\\n") + + # Load the data object + sce <- HCATonsilData( + version = "{version}", + ensembl = {ensembl_r}, + location = {location_r} + ) + + cat("Saving data object to {str(output_file)} in {output_format} format...\\n") + + # Save the object in the specified format + if ("{output_format}" == "h5ad") {{ + writeH5AD(sce, file = "{str(output_file)}", overwrite = TRUE) + }} else if ("{output_format}" == "rds") {{ + saveRDS(sce, file = "{str(output_file)}") + }} + + cat("Process complete.\\n") + """ + + # 4. Subprocess Execution + command = [] + stdout_str = "" + stderr_str = "" + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + command = ["Rscript", script_path] + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except subprocess.CalledProcessError as e: + # 5. Error Handling + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "R script execution failed.", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Rscript executable not found. Please ensure R is installed and in your system's PATH.", + "return_code": 1, + "error": "Dependency not found.", + "output_files": [] + } + finally: + # Clean up the temporary R script + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + # 6. Structured Result Return + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_file)] + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..51d48458664ac8e9d8ad723b1a03850dd92bf27a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_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-hcatonsildata/app/bioconductor-hcatonsildata_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_hcatonsildata' + + +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/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..26b78c36f0c42e04db4de93abfa037953221a302 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-hcatonsildata: + build: . + image: mcp-bioconductor-hcatonsildata:latest + container_name: mcp-bioconductor-hcatonsildata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-hcatonsildata + 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/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0fb5f539e7d8c659bb01c6cc21fdc219a3330885 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-hcatonsildata + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hcatonsildata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-hdf5array/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-hdf5array/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f2c0510d772e52fc655c301f1f3fd7380e937f81 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py b/Biomni/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a4048de346ad70d73d03a0fc0339fb993b097ab8 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c526f717b855e99523f2e5f0f4750bdb38529269 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-hdf5array/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-hdf5array/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hdf5array/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-hdf5array/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-hdf5array/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..97bfa9f0817812b9b034da837a26e1ca56d332f8 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-hdf5array/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-hdf5array/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d5fae2ca90a31c0f18e23fab27e79852206c4dc --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-hdf5array/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-hdf5array/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hdf5array/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aec6ef0262e5e91545dd92f443010da377b15b4d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/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-hoodscanr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-hoodscanr -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-hoodscanr_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-hoodscanr_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-hoodscanr_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_server.py b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9daf9003889c21e63bae23c5aacba5b25faf025d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_server.py @@ -0,0 +1,340 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_hoodscanr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def hoodscanr_estimate_radius( + input_spe_path: str, + k: int = 6, + method: str = "mean", +) -> Dict[str, Any]: + """ + Estimate the search radius for neighborhood scanning based on the k-nearest neighbors + of cells in a SpatialExperiment object. + + Args: + input_spe_path: Path to the input SpatialExperiment object saved as an RDS file. + k: Number of nearest neighbors to consider for radius estimation. Default is 6. + method: Method to summarize distances ('mean' or 'median'). Default is 'mean'. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + if k <= 0: + return {"error": "Parameter 'k' must be a positive integer."} + + if method not in ["mean", "median"]: + return {"error": "Parameter 'method' must be either 'mean' or 'median'."} + + # R script to estimate radius + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + spe <- readRDS('{input_spe_path}') + radius <- estimate_radius(spe, k = {k}, method = '{method}') + cat(radius) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"hoodscanR::estimate_radius(spe, k={k}, method='{method}')", + "estimated_radius": float(result.stdout.strip()), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + except ValueError: + return { + "error": "Could not parse radius from R output", + "stdout": result.stdout + } + +@mcp.tool() +def hoodscanr_hoodscan( + input_spe_path: str, + output_spe_path: str, + radius: float, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, +) -> Dict[str, Any]: + """ + Perform cellular neighborhood scanning on a SpatialExperiment object. + + Args: + input_spe_path: Path to the input SpatialExperiment RDS file. + output_spe_path: Path where the updated SpatialExperiment RDS file will be saved. + radius: The search radius for identifying neighbors. + focal_cell_type: Optional; specific cell type to act as the center of neighborhoods. + neighbor_cell_type: Optional; specific cell type to look for in the neighborhood. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + if radius <= 0: + return {"error": "Radius must be a positive number."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + spe <- readRDS('{input_spe_path}') + spe <- hoodscan(spe, radius = {radius}, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + saveRDS(spe, '{output_spe_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"hoodscanR::hoodscan(spe, radius={radius})", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_spe_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def hoodscanr_calc_colocalisation( + input_spe_path: str, + output_csv_path: str, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, +) -> Dict[str, Any]: + """ + Calculate the colocalisation matrix between cell types based on neighborhood scanning results. + + Args: + input_spe_path: Path to the SpatialExperiment RDS file (must have been processed by hoodscan). + output_csv_path: Path to save the colocalisation matrix as a CSV file. + focal_cell_type: Optional; filter for specific focal cell types. + neighbor_cell_type: Optional; filter for specific neighbor cell types. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + spe <- readRDS('{input_spe_path}') + coloc_mat <- calc_colocalisation(spe, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + write.csv(as.matrix(coloc_mat), '{output_csv_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "hoodscanR::calc_colocalisation(spe)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def hoodscanr_calc_spatial_correlation( + input_spe_path: str, + output_csv_path: str, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, +) -> Dict[str, Any]: + """ + Calculate the spatial correlation between cell types. + + Args: + input_spe_path: Path to the SpatialExperiment RDS file. + output_csv_path: Path to save the spatial correlation matrix as a CSV file. + focal_cell_type: Optional; filter for specific focal cell types. + neighbor_cell_type: Optional; filter for specific neighbor cell types. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + spe <- readRDS('{input_spe_path}') + corr_mat <- calc_spatial_correlation(spe, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + write.csv(as.matrix(corr_mat), '{output_csv_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "hoodscanR::calc_spatial_correlation(spe)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def hoodscanr_plot_colocalisation( + input_spe_path: str, + output_plot_path: str, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, + width: int = 8, + height: int = 6, +) -> Dict[str, Any]: + """ + Generate a heatmap of the colocalisation matrix. + + Args: + input_spe_path: Path to the SpatialExperiment RDS file. + output_plot_path: Path to save the plot (e.g., 'plot.png' or 'plot.pdf'). + focal_cell_type: Optional; filter for specific focal cell types. + neighbor_cell_type: Optional; filter for specific neighbor cell types. + width: Width of the output plot in inches. Default is 8. + height: Height of the output plot in inches. Default is 6. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + library(ggplot2) + spe <- readRDS('{input_spe_path}') + p <- plot_colocalisation(spe, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + ggsave('{output_plot_path}', plot = p, width = {width}, height = {height}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "hoodscanR::plot_colocalisation(spe)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_plot_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def hoodscanr_plot_spatial_correlation( + input_spe_path: str, + output_plot_path: str, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, + width: int = 8, + height: int = 6, +) -> Dict[str, Any]: + """ + Generate a heatmap of the spatial correlation matrix. + + Args: + input_spe_path: Path to the SpatialExperiment RDS file. + output_plot_path: Path to save the plot (e.g., 'plot.png' or 'plot.pdf'). + focal_cell_type: Optional; filter for specific focal cell types. + neighbor_cell_type: Optional; filter for specific neighbor cell types. + width: Width of the output plot in inches. Default is 8. + height: Height of the output plot in inches. Default is 6. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + library(ggplot2) + spe <- readRDS('{input_spe_path}') + p <- plot_spatial_correlation(spe, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + ggsave('{output_plot_path}', plot = p, width = {width}, height = {height}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "hoodscanR::plot_spatial_correlation(spe)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_plot_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/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..90b783133bc48ad25e3a770ac9055f1a1043897b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_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-hoodscanr/app/bioconductor-hoodscanr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_hoodscanr' + + +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/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0426723e9abd2c36b5abba66ed9c683241551437 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-hoodscanr: + build: . + image: mcp-bioconductor-hoodscanr:latest + container_name: mcp-bioconductor-hoodscanr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-hoodscanr + 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/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8b491acfe93cc48db6a171302ddf659bd416dfe --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-hoodscanr + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-hoodscanr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..657d5caae0f47ddd16435cd28d8d155ca109ca3a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/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-humanhippocampus2024 via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-humanhippocampus2024 -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-humanhippocampus2024_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-humanhippocampus2024_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-humanhippocampus2024_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_server.py b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2bcb153ca1d1b94b829166163264fa5b32a486ec --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_server.py @@ -0,0 +1,205 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Note: mcp is not imported as per instructions. +# The @mcp.tool decorator is assumed to be available in the environment. + +def _run_r_script(r_script_content: str, env: Optional[Dict[str, str]] = None) -> Dict[str, Any]: + """ + Helper function to execute an R script. + + Args: + r_script_content: The R script as a string. + env: A dictionary of environment variables to pass to the R process. + + Returns: + A dictionary containing stdout, stderr, and the executed command. + + Raises: + subprocess.CalledProcessError: If the R script execution fails. + """ + 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)] + + # Merge current environment with provided environment variables + full_env = os.environ.copy() + if env: + full_env.update(env) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + env=full_env + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + os.remove(temp_r_script_path) + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}" + } + finally: + os.remove(temp_r_script_path) + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_humanhippocampus2024' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def list_humanhippocampus2024_datasets() -> Dict[str, Any]: + """ + Lists available datasets provided by the bioconductor-humanhippocampus2024 R package. + + This tool queries the ExperimentHub for datasets associated with the + humanHippocampus2024 package, providing their IDs, titles, and descriptions. + """ + r_script = """ + # Ensure BiocManager is installed + if (!requireNamespace("BiocManager", quietly = TRUE)) { + install.packages("BiocManager", repos="https://cloud.r-project.org") + } + # Ensure humanHippocampus2024 is installed + if (!requireNamespace("humanHippocampus2024", quietly = TRUE)) { + BiocManager::install("humanHippocampus2024", update=FALSE, ask=FALSE) + } + + library(ExperimentHub) + library(humanHippocampus2024) # Load to ensure package data is registered with EH + + eh <- ExperimentHub() + + # Query for datasets specifically from humanHippocampus2024 + # We use the package name as a query term, which ExperimentHub often uses for tagging. + records <- mcols(query(eh, "humanHippocampus2024")) + + if (nrow(records) > 0) { + cat("Available datasets from humanHippocampus2024:\\n") + for (i in 1:nrow(records)) { + cat(sprintf(" ID: %s\\n", records$eh_id[i])) + cat(sprintf(" Title: %s\\n", records$title[i])) + cat(sprintf(" Description: %s\\n", records$description[i])) + if (!is.null(records$tags[[i]])) { + cat(sprintf(" Tags: %s\\n", paste(records$tags[[i]], collapse=", "))) + } + cat("---\\n") + } + } else { + cat("No datasets found for humanHippocampus2024.\\n") + } + """ + + try: + result = _run_r_script(r_script) + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except Exception as e: + return { + "command_executed": "Rscript ...", + "stdout": "", + "stderr": str(e), + "error": "Failed to list datasets." + } + + +@mcp.tool() +def get_humanhippocampus2024_dataset( + eh_id: str, + output_file: Path, +) -> Dict[str, Any]: + """ + Retrieves a specific dataset from the bioconductor-humanhippocampus2024 R package + via its ExperimentHub ID and saves it as an R RDS file. + + Args: + eh_id: The ExperimentHub ID of the dataset to retrieve (e.g., "EHXXXX"). + output_file: The path where the retrieved R object will be saved as an RDS file. + The file will contain the R object (e.g., SpatialExperiment or SummarizedExperiment). + """ + if not eh_id: + raise ValueError("ExperimentHub ID (eh_id) cannot be empty.") + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + # Ensure BiocManager is installed + if (!requireNamespace("BiocManager", quietly = TRUE)) {{ + install.packages("BiocManager", repos="https://cloud.r-project.org") + }} + # Ensure humanHippocampus2024 is installed + if (!requireNamespace("humanHippocampus2024", quietly = TRUE)) {{ + BiocManager::install("humanHippocampus2024", update=FALSE, ask=FALSE) + }} + + library(ExperimentHub) + library(humanHippocampus2024) # Load to ensure package data is registered with EH + + eh <- ExperimentHub() + + eh_id <- Sys.getenv("MCP_EH_ID") + output_file <- Sys.getenv("MCP_OUTPUT_FILE") + + if (is.null(eh_id) || eh_id == "") {{ + stop("ExperimentHub ID (MCP_EH_ID) not provided.") + }} + if (is.null(output_file) || output_file == "") {{ + stop("Output file path (MCP_OUTPUT_FILE) not provided.") + }} + + # Retrieve the dataset + data_object <- eh[[eh_id]] + + # Save the R object to an RDS file + saveRDS(data_object, file = output_file) + cat(sprintf("Dataset '%s' saved to '%s'\\n", eh_id, output_file)) + """ + + env_vars = { + "MCP_EH_ID": eh_id, + "MCP_OUTPUT_FILE": str(output_file) + } + + try: + result = _run_r_script(r_script, env=env_vars) + if "error" in result: + raise RuntimeError(result["error"] + "\n" + result["stderr"]) + + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [str(output_file)] + } + except Exception as e: + return { + "command_executed": "Rscript ...", + "stdout": "", + "stderr": str(e), + "error": f"Failed to retrieve dataset '{eh_id}'." + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9e05f0061491af4dd830c4fff835c92e5e198404 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_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-humanhippocampus2024/app/bioconductor-humanhippocampus2024_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_humanhippocampus2024' + + +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/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f6c04c4f39989e3f24678d3ea5957ba1b5fc8606 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-humanhippocampus2024: + build: . + image: mcp-bioconductor-humanhippocampus2024:latest + container_name: mcp-bioconductor-humanhippocampus2024 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-humanhippocampus2024 + 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/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..682a932cbf75e6be5805bde576d31c0ff961bc1f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-humanhippocampus2024 + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-humanhippocampus2024/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bee303f346ca8a9a652ec42afbe739b3498c6f29 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/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-imcdatasets via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-imcdatasets -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-imcdatasets_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-imcdatasets_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-imcdatasets_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_server.py b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_server.py new file mode 100644 index 0000000000000000000000000000000000000000..edf3a66ff67101f83ccc226fb68b027c3998fb5a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_server.py @@ -0,0 +1,214 @@ +import subprocess +import tempfile +from pathlib import Path +import logging +from typing import Literal, List, Dict, Any, Optional + +# Setup logging +logging.basicConfig(level=logging.INFO) +log = logging.getLogger(__name__) + +# Mock the mcp.tool decorator for standalone execution +def mcp_tool_mock(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': mcp_tool_mock}) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_imcdatasets' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def download_imcdataset( + dataset: Literal[ + "Damond_2016_IMdata", + "Damond_2019_hyperion", + "JacksonFischer_2020_squamous", + "Zanotelli_2020_SCLC", + "Kuett_2022_TMA", + ], + output_dir: Path, + save_sce: bool = True, + save_images: bool = True, + save_masks: bool = True, +) -> Dict[str, Any]: + """ + Downloads and processes a specified Imaging Mass Cytometry (IMC) dataset from the imcdatasets Bioconductor package. + + This tool fetches a dataset, which typically consists of a SingleCellExperiment object, + multichannel images, and cell masks. It saves these components into standard file formats. + + Args: + dataset: The name of the IMC dataset to download. + output_dir: The directory where the output files will be saved. + save_sce: If True, saves the SingleCellExperiment object as an AnnData (.h5ad) file. + save_images: If True, saves the multichannel images as multi-page TIFF files. + save_masks: If True, saves the cell segmentation masks as multi-page TIFF files. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # 1. Input Validation + if not (save_sce or save_images or save_masks): + raise ValueError("At least one of 'save_sce', 'save_images', or 'save_masks' must be True.") + + try: + output_dir.mkdir(parents=True, exist_ok=True) + except Exception as e: + log.error(f"Failed to create output directory {output_dir}: {e}") + raise + + # 2. R Script Generation + # Convert Python bools to R's "TRUE" / "FALSE" strings + r_save_sce = "TRUE" if save_sce else "FALSE" + r_save_images = "TRUE" if save_images else "FALSE" + r_save_masks = "TRUE" if save_masks else "FALSE" + + # The R script handles two cases: + # - Datasets that return a list of (sce, images, masks). + # - The special case 'Damond_2016_IMdata' which returns only a SingleCellExperiment object. + r_script = f""" + # Load required libraries quietly + suppressPackageStartupMessages(library(imcdatasets)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + suppressPackageStartupMessages(library(cytomapper)) + suppressPackageStartupMessages(library(sceasy)) + suppressPackageStartupMessages(library(tiff)) + + output_dir <- "{output_dir.resolve()}" + dataset_name <- "{dataset}" + + # Load the dataset + cat(paste0("Loading dataset: ", dataset_name, "\\n")) + data_object <- get(dataset_name)() + cat("Dataset loaded successfully.\\n") + + # Check the type of the returned object and process accordingly + if (is(data_object, "SingleCellExperiment")) {{ + # Case 1: The function returns a single SingleCellExperiment object + if ({r_save_sce}) {{ + cat("Saving SingleCellExperiment object...\\n") + sce_file <- file.path(output_dir, paste0(dataset_name, "_sce.h5ad")) + tryCatch({{ + sceasy::convertFormat(data_object, from="sce", to="anndata", outFile=sce_file) + cat(paste0("SCE object saved to: ", sce_file, "\\n")) + }}, error = function(e) {{ + cat(paste0("Error saving SCE object: ", e$message, "\\n")) + }}) + }} + if ({r_save_images} || {r_save_masks}) {{ + cat(paste0("Warning: The ", dataset_name, " dataset does not contain separate image or mask objects.\\n")) + }} + }} else if (is.list(data_object) && all(c("sce", "images", "masks") %in% names(data_object))) {{ + # Case 2: The function returns a list containing sce, images, and masks + if ({r_save_sce}) {{ + cat("Saving SingleCellExperiment object...\\n") + sce_file <- file.path(output_dir, paste0(dataset_name, "_sce.h5ad")) + tryCatch({{ + sceasy::convertFormat(data_object$sce, from="sce", to="anndata", outFile=sce_file) + cat(paste0("SCE object saved to: ", sce_file, "\\n")) + }}, error = function(e) {{ + cat(paste0("Error saving SCE object: ", e$message, "\\n")) + }}) + }} + + if ({r_save_images}) {{ + cat("Saving images...\\n") + images <- data_object$images + for (image_name in names(images)) {{ + img_file <- file.path(output_dir, paste0(image_name, "_image.tiff")) + tryCatch({{ + img_array <- as.array(images[[image_name]]) + tiff::write_tiff(img_array, path = img_file, compression = "LZW") + cat(paste0("Image saved to: ", img_file, "\\n")) + }}, error = function(e) {{ + cat(paste0("Error saving image '", image_name, "': ", e$message, "\\n")) + }}) + }} + }} + + if ({r_save_masks}) {{ + cat("Saving masks...\\n") + masks <- data_object$masks + for (mask_name in names(masks)) {{ + mask_file <- file.path(output_dir, paste0(mask_name, "_mask.tiff")) + tryCatch({{ + mask_array <- as.array(masks[[mask_name]]) + tiff::write_tiff(mask_array, path = mask_file, compression = "LZW") + cat(paste0("Mask saved to: ", mask_file, "\\n")) + }}, error = function(e) {{ + cat(paste0("Error saving mask '", mask_name, "': ", e$message, "\\n")) + }}) + }} + }} + }} else {{ + stop("The loaded dataset has an unexpected format.") + }} + + cat("Processing complete.\\n") + """ + + # 3. Subprocess Execution + command_executed = "" + output_files = [] + 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) + log.info(f"Executing command: {command_executed}") + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=output_dir + ) + + # 4. Collect Output + stdout = process.stdout + stderr = process.stderr + log.info("R script executed successfully.") + log.info(f"STDOUT:\n{stdout}") + if stderr: + log.warning(f"STDERR:\n{stderr}") + + # Scan output directory for created files + output_files = [str(f.resolve()) for f in output_dir.glob('*') if f.is_file()] + + except subprocess.CalledProcessError as e: + log.error(f"Error executing R script for dataset {dataset}.") + log.error(f"Return code: {e.returncode}") + log.error(f"STDOUT: {e.stdout}") + log.error(f"STDERR: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "R script execution failed." + } + except FileNotFoundError: + log.error("Rscript not found. Please ensure R is installed and in your PATH.") + raise + finally: + # Clean up the temporary script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + # 5. 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/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..038a976d555dd431bed16a509f4f970dda94db95 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_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-imcdatasets/app/bioconductor-imcdatasets_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_imcdatasets' + + +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/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..41853f3acb7b7da635ed5756adf5ba7b65095d56 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-imcdatasets: + build: . + image: mcp-bioconductor-imcdatasets:latest + container_name: mcp-bioconductor-imcdatasets + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-imcdatasets + 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/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c8f39ab71b3d84a2c641c4fb6d5b428b17319af6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-imcdatasets + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-imcdatasets/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-imcrtools/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-imcrtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ba94b99931ffc59e28a5684f5d74096eb1da097e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py b/Biomni/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ecc94bf786e53e1930adf5ddb2ea986f3ec200 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0b50a73b88d76ed4c39cb3a561aa40cb59762736 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-imcrtools/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-imcrtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-imcrtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-imcrtools/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-imcrtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..54888b25732061ffab696c3587f02a60521a4730 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-imcrtools/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-imcrtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4bc94537dfa36fb7175c850db3ec2ee151d5dc7 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-imcrtools/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-imcrtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-imcrtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-impute/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-impute/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7bdefc8af871aa387cfff8bcbd04cac3c1ed7fff --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-impute/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-impute via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-impute -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-impute_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-impute_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-impute_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-impute/app/bioconductor-impute_server.py b/Biomni/mcp_generated/mcp_bioconductor-impute/app/bioconductor-impute_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b203d73e3610f70d3c9df908e4040416d5cabc3f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-impute/app/bioconductor-impute_server.py @@ -0,0 +1,170 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import 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): + # In a real scenario, the MCP framework would handle + # the execution environment, dependency management, etc. + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def impute_knn( + data: Path, + output_file: Path, + k: int = 10, + rowmax: float = 0.5, + colmax: float = 0.8, + maxp: int = 1500, + rng_seed: int = 362436069, + input_separator: str = "\t", + has_header: bool = True, + row_names_column: int = 1, +) -> dict: + """ + Imputes missing values in a microarray data matrix using the k-Nearest Neighbors (KNN) algorithm. + + This function is a wrapper for the `impute.knn` function from the Bioconductor 'impute' package. + It takes a data matrix with missing values (represented as NA) and fills them in by averaging + the values from the 'k' most similar rows (genes). + + Args: + data: Path to the input data matrix file (e.g., CSV or TSV). Missing values should be represented as 'NA'. + output_file: Path to save the imputed data matrix. + k: The number of nearest neighbors to use for imputation. + rowmax: The maximum allowed percentage of missing values in any row. Rows exceeding this threshold are not imputed and returned as all NAs. + colmax: The maximum allowed percentage of missing values in any column. If any column exceeds this, the program will abort. + maxp: The maximum number of genes to process in a single batch. If the dataset is larger, it will be processed in chunks. + rng_seed: Seed for the random number generator to ensure reproducibility. + input_separator: The delimiter used in the input file (e.g., '\\t' for TSV, ',' for CSV). + has_header: A boolean indicating if the input file has a header row. + row_names_column: The 1-based index of the column containing row names. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # 1. Input validation + if not data.is_file(): + raise FileNotFoundError(f"Input file not found: {data}") + if k <= 0: + raise ValueError("The number of neighbors 'k' must be a positive integer.") + if not (0.0 <= rowmax <= 1.0): + raise ValueError("'rowmax' must be a float between 0.0 and 1.0.") + if not (0.0 <= colmax <= 1.0): + raise ValueError("'colmax' must be a float between 0.0 and 1.0.") + if maxp <= 0: + raise ValueError("'maxp' must be a positive integer.") + if row_names_column <= 0: + raise ValueError("'row_names_column' must be a positive integer.") + + # 2. R script generation + r_script_content = f""" + # Load the required library + if (!requireNamespace("impute", quietly = TRUE)) {{ + stop("The 'impute' package is not installed. Please install it from Bioconductor.") + }} + library(impute) + + # Define parameters + input_file <- "{data.resolve()}" + output_file <- "{output_file.resolve()}" + k_val <- {k} + rowmax_val <- {rowmax} + colmax_val <- {colmax} + maxp_val <- {maxp} + rng_seed_val <- {rng_seed} + sep_char <- "{input_separator}" + header_bool <- {"TRUE" if has_header else "FALSE"} + row_names_col_idx <- {row_names_column} + + # Read the input data + # Using tryCatch to provide a more informative error message + data_matrix <- tryCatch({{ + as.matrix(read.table( + input_file, + header=header_bool, + sep=sep_char, + row.names=row_names_col_idx, + as.is=TRUE, + check.names=FALSE + )) + }}, error = function(e) {{ + stop(paste("Failed to read the input file:", e$message)) + }}) + + # Set the seed for reproducibility + set.seed(rng_seed_val) + + # Perform KNN imputation + # The result is a list, with the imputed data in the 'data' element + imputed_result <- impute.knn( + data_matrix, + k = k_val, + rowmax = rowmax_val, + colmax = colmax_val, + maxp = maxp_val + ) + imputed_data <- imputed_result$data + + # Write the imputed data to the output file + write.table( + imputed_data, + file = output_file, + sep = sep_char, + quote = FALSE, + col.names = NA # Keeps column names and adds a blank for the row names column + ) + + cat("Imputation complete. Output written to", output_file, "\\n") + """ + + # 3. Subprocess execution + command = [] + stdout_str = "" + stderr_str = "" + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + command = ["Rscript", script_path] + + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "R script execution failed." + } + finally: + # Clean up the temporary R script + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_file)] + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-impute/app/bioconductor-impute_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-impute/app/bioconductor-impute_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e3f45ac6680986028f487a79fbcadd779a3bd6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-impute/app/bioconductor-impute_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-impute/app/bioconductor-impute_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_impute' + + +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/Biomni/mcp_generated/mcp_bioconductor-impute/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-impute/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-impute/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-impute/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-impute/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..48eaf8a733f4024b5f7383bdc2cf9078f1c076f8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-impute/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-impute: + build: . + image: mcp-bioconductor-impute:latest + container_name: mcp-bioconductor-impute + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-impute + 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/Biomni/mcp_generated/mcp_bioconductor-impute/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-impute/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2203a61220545c7d82d1989a22a9cb738b501456 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-impute/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-impute + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-impute/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-impute/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-impute/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-infercnv/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-infercnv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2a7999e32fcac07aa795437e3ed33b833e69b59f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-infercnv/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-infercnv via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-infercnv -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-infercnv_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-infercnv_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-infercnv_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-infercnv/app/bioconductor-infercnv_server.py b/Biomni/mcp_generated/mcp_bioconductor-infercnv/app/bioconductor-infercnv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1d0cb8c9549e9064121415412737002fc2452eff --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-infercnv/app/bioconductor-infercnv_server.py @@ -0,0 +1,298 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List +import tempfile +import shlex + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_infercnv' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def infercnv_run( + raw_counts_matrix: str, + annotations_file: str, + gene_order_file: str, + out_dir: str, + ref_group_names: Optional[List[str]] = None, + cutoff: float = 1.0, + min_cells_per_gene: int = 3, + cluster_by_groups: bool = True, + denoise: bool = False, + hmm: bool = False, + hmm_type: str = "i6", + analysis_mode: str = "samples", + num_threads: int = 1, + plot_steps: bool = False, + no_plot: bool = False, + window_length: int = 101, + max_centered_threshold: float = 3.0, + leiden_resolution: float = 0.05, +): + """ + Run the full InferCNV pipeline to identify somatic copy number alterations in single-cell RNA-seq data. + + Args: + raw_counts_matrix: Path to the matrix of gene expression counts (genes as rows, cells as columns). + annotations_file: Path to the cell annotations file (cell name and group). + gene_order_file: Path to the gene positions file (gene, chromosome, start, stop). + out_dir: Directory to save the output files. + ref_group_names: List of group names to use as reference (normal) cells. If None, all cells are used. + cutoff: Threshold for gene expression. Use 1.0 for Smart-seq2 and 0.1 for 10x Genomics. + min_cells_per_gene: Minimum number of cells a gene must be expressed in to be kept. + cluster_by_groups: Whether to cluster cells by their annotation groups. + denoise: Whether to apply denoising filters. + hmm: Whether to run the Hidden Markov Model (HMM) to predict CNV states. + hmm_type: Type of HMM to use ('i6' for 6-state model, 'i3' for 3-state model). + analysis_mode: Analysis mode ('samples' or 'subclusters'). + num_threads: Number of CPU threads to use for parallel processing. + plot_steps: Whether to generate plots for every intermediate step. + no_plot: If True, skips the final heatmap generation. + window_length: Length of the moving average window for smoothing. + max_centered_threshold: Maximum value for centering the expression data. + leiden_resolution: Resolution for Leiden clustering if analysis_mode is 'subclusters'. + """ + # Input validation + raw_path = Path(raw_counts_matrix) + ann_path = Path(annotations_file) + gene_path = Path(gene_order_file) + out_path = Path(out_dir) + + if not raw_path.exists(): + return {"error": f"Raw counts matrix not found: {raw_counts_matrix}"} + if not ann_path.exists(): + return {"error": f"Annotations file not found: {annotations_file}"} + if not gene_path.exists(): + return {"error": f"Gene order file not found: {gene_order_file}"} + + if hmm_type not in ["i6", "i3"]: + return {"error": "hmm_type must be either 'i6' or 'i3'"} + + if analysis_mode not in ["samples", "subclusters"]: + return {"error": "analysis_mode must be either 'samples' or 'subclusters'"} + + os.makedirs(out_path, exist_ok=True) + + # Prepare R vector for reference groups + if ref_group_names: + ref_groups_r = "c(" + ", ".join([f"'{g}'" for g in ref_group_names]) + ")" + else: + ref_groups_r = "NULL" + + # Construct R script + r_script_content = f""" +library(infercnv) + +# Create InferCNV Object +infercnv_obj = CreateInfercnvObject( + raw_counts_matrix = "{raw_path.absolute()}", + gene_order_file = "{gene_path.absolute()}", + annotations_file = "{ann_path.absolute()}", + ref_group_names = {ref_groups_r} +) + +# Run InferCNV Pipeline +infercnv_obj = infercnv::run( + infercnv_obj, + cutoff = {cutoff}, + min_cells_per_gene = {min_cells_per_gene}, + out_dir = "{out_path.absolute()}", + cluster_by_groups = {str(cluster_by_groups).upper()}, + denoise = {str(denoise).upper()}, + HMM = {str(hmm).upper()}, + HMM_type = "{hmm_type}", + analysis_mode = "{analysis_mode}", + num_threads = {num_threads}, + plot_steps = {str(plot_steps).upper()}, + no_plot = {str(no_plot).upper()}, + window_length = {window_length}, + max_centered_threshold = {max_centered_threshold}, + leiden_resolution = {leiden_resolution} +) +""" + + try: + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Cleanup temp file + os.unlink(tmp_path) + + # Identify output files + output_files = [str(f) for f in out_path.glob("*") 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: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "InferCNV execution failed." + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def infercnv_plot( + infercnv_obj_path: str, + out_dir: str, + output_filename: str = "infercnv_plot", + color_safe_pal: bool = False, + title: str = "InferCNV Heatmap", + cluster_by_groups: bool = True, + x_center: float = 1.0, + x_range: Optional[float] = None, + custom_color_pal: Optional[List[str]] = None, +): + """ + Generate or regenerate plots from a saved InferCNV object. + + Args: + infercnv_obj_path: Path to the saved .rds or .obj InferCNV object. + out_dir: Directory to save the plot. + output_filename: Name of the output plot file (without extension). + color_safe_pal: Use a color-blind safe palette. + title: Title of the plot. + cluster_by_groups: Whether to cluster by groups in the plot. + x_center: Value to center the color scale on (usually 1.0). + x_range: Range of values to display (e.g., 0.1 means 0.9 to 1.1). + custom_color_pal: Optional list of colors for the heatmap palette. + """ + obj_path = Path(infercnv_obj_path) + out_path = Path(out_dir) + + if not obj_path.exists(): + return {"error": f"InferCNV object not found: {infercnv_obj_path}"} + + os.makedirs(out_path, exist_ok=True) + + x_range_r = f"{x_range}" if x_range is not None else "NULL" + color_pal_r = "NULL" + if custom_color_pal: + color_pal_r = "c(" + ", ".join([f"'{c}'" for c in custom_color_pal]) + ")" + + r_script_content = f""" +library(infercnv) +infercnv_obj = readRDS("{obj_path.absolute()}") + +plot_cnv( + infercnv_obj, + out_dir = "{out_path.absolute()}", + output_filename = "{output_filename}", + color_safe_pal = {str(color_safe_pal).upper()}, + title = "{title}", + cluster_by_groups = {str(cluster_by_groups).upper()}, + x_center = {x_center}, + x_range = {x_range_r}, + custom_color_pal = {color_pal_r} +) +""" + + try: + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + os.unlink(tmp_path) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(f) for f in out_path.glob(f"{output_filename}*")], + "status": "success" + } + + except subprocess.CalledProcessError as e: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "InferCNV plotting failed." + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def infercnv_filter_genes( + raw_counts_matrix: str, + gene_order_file: str, + output_matrix_path: str, + min_cells_per_gene: int = 3, +): + """ + Pre-filter a counts matrix to remove genes expressed in fewer than a threshold number of cells. + + Args: + raw_counts_matrix: Path to the input counts matrix. + gene_order_file: Path to the gene order file. + output_matrix_path: Path to save the filtered matrix. + min_cells_per_gene: Minimum number of cells a gene must be expressed in. + """ + raw_path = Path(raw_counts_matrix) + gene_path = Path(gene_order_file) + out_path = Path(output_matrix_path) + + if not raw_path.exists(): + return {"error": f"Input matrix not found: {raw_counts_matrix}"} + + r_script_content = f""" +library(infercnv) +# Load data +counts = read.table("{raw_path.absolute()}", header=TRUE, row.names=1, check.names=FALSE) +# Filter +gene_counts = rowSums(counts > 0) +filtered_counts = counts[gene_counts >= {min_cells_per_gene}, ] +# Save +write.table(filtered_counts, file="{out_path.absolute()}", quote=FALSE, sep='\\t') +""" + + try: + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + os.unlink(tmp_path) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)], + "status": "success" + } + except subprocess.CalledProcessError as e: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Filtering failed." + } + except Exception as e: + return {"error": str(e)} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-infercnv/app/bioconductor-infercnv_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-infercnv/app/bioconductor-infercnv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..31ac943add0b5f8b06cc653b6516641aec523bfe --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-infercnv/app/bioconductor-infercnv_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-infercnv/app/bioconductor-infercnv_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_infercnv' + + +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/Biomni/mcp_generated/mcp_bioconductor-infercnv/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-infercnv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f701e922db8fed281ae7e21356ec9c7d1a54f5e2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-infercnv/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-infercnv: + build: . + image: mcp-bioconductor-infercnv:latest + container_name: mcp-bioconductor-infercnv + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-infercnv + 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/Biomni/mcp_generated/mcp_bioconductor-infercnv/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-infercnv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f15fb47aebdab67c6414b91b31d218a96f2e752 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-infercnv/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-infercnv + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-infercnv/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-infercnv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-infercnv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f4cd2a5c71838a423aa572705e3c4403719003d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/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-interactivedisplaybase via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-interactivedisplaybase -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-interactivedisplaybase_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-interactivedisplaybase_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-interactivedisplaybase_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..946a310cb225b723168c968dd57606144ddd720b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py @@ -0,0 +1,44 @@ +import subprocess +from pathlib import Path +from typing import Optional + +# MCP decorator is omitted as per instructions +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_interactivedisplaybase' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() + +def interactive_display_base(): + """ + Placeholder for the deprecated Bioconductor R library 'interactiveDisplayBase'. + + This package is an R library for building interactive Shiny applications and does not + provide a command-line interface. It is also deprecated and has been removed from + Bioconductor. As such, it cannot be executed as a standard command-line tool. + This function returns an informative message instead of executing a command. + """ + # This is not a command-line tool. The core functionality is to provide + # methods within an R session to generate interactive Shiny displays. + # This is fundamentally incompatible with the non-interactive MCP model. + # The package is also deprecated. + # Therefore, this function does not execute any subprocess. + # It returns a structured message explaining the situation. + + info_message = ( + "The 'bioconductor-interactivedisplaybase' package is an R library for " + "creating interactive Shiny applications and does not have a command-line interface. " + "It is also deprecated and removed from Bioconductor. " + "Therefore, it cannot be executed as a command-line tool." + ) + + return { + "command_executed": "", + "stdout": info_message, + "stderr": "This is an informational message, not an error.", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..81eeaeb6e1e6f86a7f35fa57c90ac17a9a1297c2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_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-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_interactivedisplaybase' + + +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/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..27fcbcd7b100fb67df8f591cfedd0287e52a7609 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-interactivedisplaybase: + build: . + image: mcp-bioconductor-interactivedisplaybase:latest + container_name: mcp-bioconductor-interactivedisplaybase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-interactivedisplaybase + 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/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..638e635c19674a5a595d4c598bcfedd9f61d7e11 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-interactivedisplaybase + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-interactivedisplaybase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-iranges/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-iranges/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..78c8aad093ce7b8c16bd39ced21755f4ca8bea80 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-iranges/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-iranges via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-iranges -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-iranges_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-iranges_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-iranges_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py b/Biomni/mcp_generated/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e08ee625f9bc6dc949f6c6848e54e9d8a316caf4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py @@ -0,0 +1,292 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_iranges' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def iranges_transform( + input_csv: str, + output_csv: str, + operation: str = "shift", + shift_amount: int = 0, + width_amount: int = -1, + side: str = "both", + fix: str = "start" +): + """ + Perform transformations on integer ranges such as shifting, resizing, or flanking. + + Args: + input_csv: Path to input CSV file containing 'start' and 'end' (or 'width') columns. + output_csv: Path where the transformed ranges will be saved. + operation: Transformation to perform: 'shift', 'resize', 'flank', or 'narrow'. + shift_amount: Amount to shift ranges (used if operation is 'shift'). + width_amount: New width or flanking width (used if operation is 'resize' or 'flank'). + side: For 'flank', which side to generate: 'start', 'end', or 'both'. + fix: For 'resize', which part of the range to fix: 'start', 'end', or 'center'. + """ + if not Path(input_csv).exists(): + return {"error": f"Input file {input_csv} not found."} + + valid_ops = ["shift", "resize", "flank", "narrow"] + if operation not in valid_ops: + return {"error": f"Invalid operation. Must be one of {valid_ops}"} + + # Construct R script + r_cmd = f""" + library(IRanges) + df <- read.csv('{input_csv}') + ir <- IRanges(start=df$start, end=df$end) + + if ('{operation}' == 'shift') {{ + res <- shift(ir, shift={shift_amount}) + }} else if ('{operation}' == 'resize') {{ + res <- resize(ir, width={width_amount}, fix='{fix}') + }} else if ('{operation}' == 'flank') {{ + is_both <- if('{side}' == 'both') TRUE else FALSE + res <- flank(ir, width={width_amount}, start=('{side}' == 'start'), both=is_both) + }} else if ('{operation}' == 'narrow') {{ + res <- narrow(ir, start=NA, end=NA, width={width_amount}) + }} + + write.csv(as.data.frame(res), '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": f"Rscript -e \"{operation} on {input_csv}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def iranges_set_operations( + input_csv: str, + output_csv: str, + operation: str = "reduce", + min_gapwidth: int = 1 +): + """ + Perform set-like operations on ranges such as merging overlapping intervals or finding gaps. + + Args: + input_csv: Path to input CSV file containing 'start' and 'end' columns. + output_csv: Path where the resulting ranges will be saved. + operation: Operation to perform: 'reduce' (merge overlapping), 'disjoin' (find elementary ranges), or 'gaps'. + min_gapwidth: Minimum gap width for the 'reduce' operation. + """ + if not Path(input_csv).exists(): + return {"error": f"Input file {input_csv} not found."} + + r_cmd = f""" + library(IRanges) + df <- read.csv('{input_csv}') + ir <- IRanges(start=df$start, end=df$end) + + if ('{operation}' == 'reduce') {{ + res <- reduce(ir, min.gapwidth={min_gapwidth}) + }} else if ('{operation}' == 'disjoin') {{ + res <- disjoin(ir) + }} else if ('{operation}' == 'gaps') {{ + res <- gaps(ir) + }} + + write.csv(as.data.frame(res), '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": f"Rscript -e \"{operation} on {input_csv}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def iranges_overlap_analysis( + query_csv: str, + subject_csv: str, + output_csv: str, + find_overlaps: bool = True, + maxgap: int = -1, + minoverlap: int = 0, + overlap_type: str = "any" +): + """ + Find overlaps or count overlaps between two sets of ranges (Query and Subject). + + Args: + query_csv: CSV file for query ranges. + subject_csv: CSV file for subject ranges. + output_csv: Path to save the overlap mapping (query hits and subject hits). + find_overlaps: If True, returns mapping of hits. If False, returns counts per query. + maxgap: Maximum gap allowed between ranges to be considered overlapping. + minoverlap: Minimum number of overlapping positions. + overlap_type: Type of overlap: 'any', 'start', 'end', 'within', or 'equal'. + """ + if not Path(query_csv).exists() or not Path(subject_csv).exists(): + return {"error": "One or both input files not found."} + + r_cmd = f""" + library(IRanges) + q_df <- read.csv('{query_csv}') + s_df <- read.csv('{subject_csv}') + query <- IRanges(start=q_df$start, end=q_df$end) + subject <- IRanges(start=s_df$start, end=s_df$end) + + if ({str(find_overlaps).upper()}) {{ + hits <- findOverlaps(query, subject, maxgap={maxgap}, minoverlap={minoverlap}, type='{overlap_type}') + res <- as.data.frame(hits) + }} else {{ + counts <- countOverlaps(query, subject, maxgap={maxgap}, minoverlap={minoverlap}, type='{overlap_type}') + res <- data.frame(query_index=1:length(query), overlap_count=counts) + }} + + write.csv(res, '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": "IRanges::findOverlaps/countOverlaps", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def iranges_nearest_methods( + query_csv: str, + subject_csv: str, + output_csv: str, + method: str = "nearest" +): + """ + Find nearest, preceding, or following ranges between query and subject. + + Args: + query_csv: CSV file for query ranges. + subject_csv: CSV file for subject ranges. + output_csv: Path to save the results (mapping of query index to subject index). + method: Method to use: 'nearest', 'precede', or 'follow'. + """ + if not Path(query_csv).exists() or not Path(subject_csv).exists(): + return {"error": "Input files not found."} + + r_cmd = f""" + library(IRanges) + q_df <- read.csv('{query_csv}') + s_df <- read.csv('{subject_csv}') + query <- IRanges(start=q_df$start, end=q_df$end) + subject <- IRanges(start=s_df$start, end=s_df$end) + + if ('{method}' == 'nearest') {{ + idx <- nearest(query, subject) + }} else if ('{method}' == 'precede') {{ + idx <- precede(query, subject) + }} else if ('{method}' == 'follow') {{ + idx <- follow(query, subject) + }} + + res <- data.frame(query_index=1:length(query), subject_index=idx) + write.csv(res, '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": f"IRanges::{method}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def iranges_coverage( + input_csv: str, + output_csv: str +): + """ + Calculate the coverage (number of ranges covering each integer position). + + Args: + input_csv: Path to input CSV file containing 'start' and 'end' columns. + output_csv: Path to save the coverage data (position and value). + """ + if not Path(input_csv).exists(): + return {"error": f"Input file {input_csv} not found."} + + r_cmd = f""" + library(IRanges) + df <- read.csv('{input_csv}') + ir <- IRanges(start=df$start, end=df$end) + cov <- coverage(ir) + + # Convert Rle to data frame for export + res <- data.frame( + value = as.vector(cov), + width = runLength(cov) + ) + # Expand or keep as run-length encoded? Let's provide a summary-like table + # To keep it simple and usable, we export the Rle components + write.csv(res, '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": "IRanges::coverage", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-iranges/app/bioconductor-iranges_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-iranges/app/bioconductor-iranges_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..83703d95feb53b5e42669d932be002cc3eec632a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-iranges/app/bioconductor-iranges_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-iranges/app/bioconductor-iranges_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_iranges' + + +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/Biomni/mcp_generated/mcp_bioconductor-iranges/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-iranges/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-iranges/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-iranges/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-iranges/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a44a8a7f67111158d1ce5c6143cbe40c2b20625 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-iranges/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-iranges: + build: . + image: mcp-bioconductor-iranges:latest + container_name: mcp-bioconductor-iranges + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-iranges + 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/Biomni/mcp_generated/mcp_bioconductor-iranges/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-iranges/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7776983b41417b9ccff7c889b7607cae4724926 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-iranges/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-iranges + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-iranges/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-iranges/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-iranges/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-irisfgm/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-irisfgm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e30f96079a8c672ae33bcfb5e72ab1ed0a42a4cc --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py b/Biomni/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c798a7de6725fc156b1af9cf963158a092131d4e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..157ce2bc46e4b72dfc669514aeb94d7cfd931a8e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-irisfgm/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-irisfgm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6ec8f6a1ced45007183fe46de3573b1d37550d46 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-irisfgm/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-irisfgm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca7f25d8bc352e903a8fc4e77bb5c0eba53afd37 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-irisfgm/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-irisfgm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-irisfgm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..26c74d6d873006932c8bf76024075aa355315e75 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/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-jazzpanda via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-jazzpanda -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-jazzpanda_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-jazzpanda_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-jazzpanda_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_server.py b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef9b751112e38dc05ba055958602e0c8be62e9c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_server.py @@ -0,0 +1,472 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Helper function to run R scripts +def _run_r_script(script_content: str, output_dir: Path) -> Dict[str, Any]: + """ + Executes an R script using Rscript. + """ + output_dir.mkdir(parents=True, exist_ok=True) + + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R", dir=output_dir) as r_script_file: + r_script_file.write(script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + command_executed = " ".join(command) + except subprocess.CalledProcessError as e: + 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(): + r_script_path.unlink() + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # This will be populated by individual tools + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_jazzpanda' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def create_spatial_vectors( + cell_coordinates_csv: Path, + transcript_coordinates_csv: Path, + output_spatial_experiment_rds: Path, + cell_id_col_cell: str = "cell_id", + x_col_cell: str = "x", + y_col_cell: str = "y", + transcript_id_col_transcript: str = "transcript_id", + cell_id_col_transcript: str = "cell_id", + x_col_transcript: str = "x", + y_col_transcript: str = "y", + output_dir: Path = Path("./jazzpanda_output"), +) -> Dict[str, Any]: + """ + Inferred: Creates a SpatialExperiment object from cell and transcript coordinates. + + This function infers the existence of an internal 'createSpatialVectors' function + within the jazzPanda R package. It takes CSV files for cell and transcript + coordinates and generates an R SpatialExperiment object saved as an .rds file. + Since the exact function signature is not documented, this implementation + simulates the creation of a basic SpatialExperiment object with spatial + coordinates and a dummy assay, which would then be used by downstream functions. + + Args: + cell_coordinates_csv: Path to a CSV/TSV file containing cell coordinates. + Expected columns (configurable): cell_id_col_cell, x_col_cell, y_col_cell. + transcript_coordinates_csv: Path to a CSV/TSV file containing transcript coordinates. + Expected columns (configurable): transcript_id_col_transcript, + cell_id_col_transcript, x_col_transcript, y_col_transcript. + output_spatial_experiment_rds: Path to save the resulting SpatialExperiment object + as an R .rds file. + cell_id_col_cell: Column name for cell IDs in the cell coordinates file. + x_col_cell: Column name for X-coordinates in the cell coordinates file. + y_col_cell: Column name for Y-coordinates in the cell coordinates file. + transcript_id_col_transcript: Column name for transcript IDs in the transcript coordinates file. + cell_id_col_transcript: Column name for cell IDs in the transcript coordinates file. + x_col_transcript: Column name for X-coordinates in the transcript coordinates file. + y_col_transcript: Column name for Y-coordinates in the transcript coordinates file. + output_dir: Directory to store temporary files and final outputs. + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not cell_coordinates_csv.is_file(): + raise FileNotFoundError(f"Cell coordinates file not found: {cell_coordinates_csv}") + if not transcript_coordinates_csv.is_file(): + raise FileNotFoundError(f"Transcript coordinates file not found: {transcript_coordinates_csv}") + if not output_spatial_experiment_rds.parent.exists(): + output_spatial_experiment_rds.parent.mkdir(parents=True, exist_ok=True) + + # R script content + r_script = f""" + library(jazzPanda) + library(SpatialExperiment) + library(dplyr) + library(S4Vectors) # For DataFrame + + # Ensure output directory exists + output_dir <- "{output_dir.resolve()}" + if (!dir.exists(output_dir)) {{ + dir.create(output_dir, recursive = TRUE) + }} + + cell_coords_path <- "{cell_coordinates_csv.resolve()}" + transcript_coords_path <- "{transcript_coordinates_csv.resolve()}" + output_se_path <- "{output_spatial_experiment_rds.resolve()}" + + # Read cell coordinates + cell_coords <- read.csv(cell_coords_path, stringsAsFactors = FALSE) + if (!all(c("{cell_id_col_cell}", "{x_col_cell}", "{y_col_cell}") %in% colnames(cell_coords))) {{ + stop("Missing required columns in cell coordinates file. Expected: {cell_id_col_cell}, {x_col_cell}, {y_col_cell}") + }} + cell_coords <- cell_coords %>% + dplyr::select(cell_id = "{cell_id_col_cell}", x = "{x_col_cell}", y = "{y_col_cell}") + + # Read transcript coordinates + transcript_coords <- read.csv(transcript_coords_path, stringsAsFactors = FALSE) + if (!all(c("{transcript_id_col_transcript}", "{cell_id_col_transcript}", "{x_col_transcript}", "{y_col_transcript}") %in% colnames(transcript_coords))) {{ + stop("Missing required columns in transcript coordinates file. Expected: {transcript_id_col_transcript}, {cell_id_col_transcript}, {x_col_transcript}, {y_col_transcript}") + }} + transcript_coords <- transcript_coords %>% + dplyr::select(transcript_id = "{transcript_id_col_transcript}", + cell_id = "{cell_id_col_transcript}", + x = "{x_col_transcript}", + y = "{y_col_transcript}") + + # Inferred function call: jazzPanda::createSpatialVectors + # The exact function signature is not documented. + # We simulate creating a basic SpatialExperiment object based on common practices. + # In a real jazzPanda scenario, this would likely involve a dedicated function + # that takes these coordinates and potentially other expression data to build the SE. + + # Create colData from cell_coords + col_data <- S4Vectors::DataFrame(cell_coords) + rownames(col_data) <- col_data$cell_id + + # Create spatialCoords + spatial_coords_matrix <- as.matrix(cell_coords[, c("x", "y")]) + rownames(spatial_coords_matrix) <- cell_coords$cell_id + + # Create a dummy assay (e.g., a matrix of zeros) + # In a real scenario, expression data would be provided separately or derived. + # For this example, we'll just make a placeholder. + num_genes <- 100 # Arbitrary number of genes + num_cells <- nrow(cell_coords) + assay_data <- matrix(0, nrow = num_genes, ncol = num_cells) + rownames(assay_data) <- paste0("gene", 1:num_genes) + colnames(assay_data) <- cell_coords$cell_id + + # Create SpatialExperiment object + se <- SpatialExperiment( + assays = list(counts = assay_data), + colData = col_data, + spatialCoords = spatial_coords_matrix + ) + + # Save the SpatialExperiment object + saveRDS(se, file = output_se_path) + cat(paste0("SpatialExperiment object saved to: ", output_se_path, "\\n")) + """ + + result = _run_r_script(r_script, output_dir) + result["output_files"].append(str(output_spatial_experiment_rds.resolve())) + return result + + +@mcp.tool() +def find_marker_genes_permutation( + spatial_experiment_rds: Path, + cluster_column: str, + output_marker_genes_csv: Path, + num_permutations: int = 1000, + p_value_threshold: float = 0.05, + min_cells_per_cluster: int = 5, + output_dir: Path = Path("./jazzpanda_output"), +) -> Dict[str, Any]: + """ + Inferred: Finds spatially relevant marker genes using permutation testing. + + This function infers the existence of an internal 'findMarkerGenesPermutation' + function within the jazzPanda R package. It performs permutation testing + to identify marker genes for each cluster in a SpatialExperiment object. + Since the exact function signature is not documented, this implementation + simulates the output of such a function. + + Args: + spatial_experiment_rds: Path to the input SpatialExperiment object (.rds file). + This object should contain expression data and cluster + assignments in its colData. + cluster_column: The name of the column in the colData of the SpatialExperiment + object that contains cluster assignments for each cell. + output_marker_genes_csv: Path to save the resulting marker gene table as a CSV file. + num_permutations: The number of permutations to perform for statistical testing. + Must be a positive integer. + p_value_threshold: The p-value threshold for calling a gene a marker gene. + Must be between 0 and 1 (exclusive). + min_cells_per_cluster: Minimum number of cells required in a cluster for it to be + considered for marker gene detection. Must be a positive integer. + output_dir: Directory to store temporary files and final outputs. + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not spatial_experiment_rds.is_file(): + raise FileNotFoundError(f"SpatialExperiment .rds file not found: {spatial_experiment_rds}") + if not output_marker_genes_csv.parent.exists(): + output_marker_genes_csv.parent.mkdir(parents=True, exist_ok=True) + if num_permutations <= 0: + raise ValueError("num_permutations must be a positive integer.") + if not (0 < p_value_threshold < 1): + raise ValueError("p_value_threshold must be between 0 and 1 (exclusive).") + if min_cells_per_cluster <= 0: + raise ValueError("min_cells_per_cluster must be a positive integer.") + + # R script content + r_script = f""" + library(jazzPanda) + library(SpatialExperiment) + library(dplyr) + + # Ensure output directory exists + output_dir <- "{output_dir.resolve()}" + if (!dir.exists(output_dir)) {{ + dir.create(output_dir, recursive = TRUE) + }} + + se_path <- "{spatial_experiment_rds.resolve()}" + output_csv_path <- "{output_marker_genes_csv.resolve()}" + cluster_col <- "{cluster_column}" + n_perm <- {num_permutations} + p_thresh <- {p_value_threshold} + min_cells <- {min_cells_per_cluster} + + se <- readRDS(se_path) + + if (!cluster_col %in% colnames(colData(se))) {{ + stop(paste0("Cluster column '", cluster_col, "' not found in colData of SpatialExperiment object.")) + }} + + # Filter out clusters with fewer than min_cells + cluster_counts <- table(colData(se)[[cluster_col]]) + valid_clusters <- names(cluster_counts[cluster_counts >= min_cells]) + if (length(valid_clusters) == 0) {{ + stop("No clusters meet the minimum cell count threshold.") + }} + se <- se[, colData(se)[[cluster_col]] %in% valid_clusters] + colData(se)[[cluster_col]] <- droplevels(as.factor(colData(se)[[cluster_col]])) + + + # Inferred function call: jazzPanda::findMarkerGenesPermutation + # The exact function signature is not documented. + # We simulate a result based on common marker gene output for demonstration. + + # Get unique clusters + clusters <- unique(colData(se)[[cluster_col]]) + + # Create dummy marker gene results + marker_genes_list <- list() + for (cl in clusters) {{ + # Simulate some genes for this cluster + # Ensure there are enough genes in the SE object + num_genes_in_se <- nrow(se) + if (num_genes_in_se == 0) {{ + warning("No genes found in SpatialExperiment object. Skipping marker gene simulation.") + next + }} + genes_to_sample <- min(5, num_genes_in_se) # Take up to 5 genes as markers for each cluster + genes <- head(rownames(se), genes_to_sample) + + # Simulate p-values and logFC + p_values <- runif(length(genes), 0, p_thresh * 2) + log_fcs <- rnorm(length(genes), mean = 1.5, sd = 0.5) + + df <- data.frame( + gene = genes, + cluster = cl, + p_value = p_values, + logFC = log_fcs, + stringsAsFactors = FALSE + ) + marker_genes_list[[as.character(cl)]] <- df + }} + + if (length(marker_genes_list) > 0) {{ + marker_genes_df <- do.call(rbind, marker_genes_list) + + # Filter by p-value threshold (simulated) + marker_genes_df <- marker_genes_df %>% + filter(p_value < p_thresh) %>% + arrange(cluster, p_value) + }} else {{ + marker_genes_df <- data.frame( + gene = character(), + cluster = character(), + p_value = numeric(), + logFC = numeric(), + stringsAsFactors = FALSE + ) + }} + + write.csv(marker_genes_df, file = output_csv_path, row.names = FALSE) + cat(paste0("Marker genes (permutation) saved to: ", output_csv_path, "\\n")) + """ + + result = _run_r_script(r_script, output_dir) + result["output_files"].append(str(output_marker_genes_csv.resolve())) + return result + + +@mcp.tool() +def find_marker_genes_linear_model( + spatial_experiment_rds: Path, + cluster_column: str, + design_formula: str, + output_marker_genes_csv: Path, + alpha: float = 1.0, + lambda_value: Optional[float] = None, # Renamed to avoid conflict with Python keyword + p_value_threshold: float = 0.05, + output_dir: Path = Path("./jazzpanda_output"), +) -> Dict[str, Any]: + """ + Inferred: Finds spatially relevant marker genes using a linear model (e.g., glmnet). + + This function infers the existence of an internal 'findMarkerGenesLinearModel' + function within the jazzPanda R package. It builds a linear model for each gene + to identify marker genes, accounting for multiple samples and background noise. + Since the exact function signature is not documented, this implementation + simulates the output of such a function. + + Args: + spatial_experiment_rds: Path to the input SpatialExperiment object (.rds file). + This object should contain expression data and cluster + assignments in its colData. + cluster_column: The name of the column in the colData of the SpatialExperiment + object that contains cluster assignments for each cell. + design_formula: An R formula string specifying the linear model design, + e.g., "~ cluster_column + batch_id". Variables in the formula + must be present in the colData of the SpatialExperiment object. + output_marker_genes_csv: Path to save the resulting marker gene table as a CSV file. + alpha: The elasticnet mixing parameter (0 <= alpha <= 1). + alpha = 1 is the lasso penalty, and alpha = 0 is the ridge penalty. + Inferred from 'glmnet' dependency. + lambda_value: The regularization parameter. If None, glmnet will select a sequence. + Inferred from 'glmnet' dependency. + p_value_threshold: The p-value threshold for calling a gene a marker gene. + Must be between 0 and 1 (exclusive). + output_dir: Directory to store temporary files and final outputs. + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not spatial_experiment_rds.is_file(): + raise FileNotFoundError(f"SpatialExperiment .rds file not found: {spatial_experiment_rds}") + if not output_marker_genes_csv.parent.exists(): + output_marker_genes_csv.parent.mkdir(parents=True, exist_ok=True) + if not (0 <= alpha <= 1): + raise ValueError("alpha must be between 0 and 1.") + if p_value_threshold <= 0 or p_value_threshold >= 1: + raise ValueError("p_value_threshold must be between 0 and 1 (exclusive).") + + # R script content + r_script = f""" + library(jazzPanda) + library(SpatialExperiment) + library(glmnet) + library(dplyr) + + # Ensure output directory exists + output_dir <- "{output_dir.resolve()}" + if (!dir.exists(output_dir)) {{ + dir.create(output_dir, recursive = TRUE) + }} + + se_path <- "{spatial_experiment_rds.resolve()}" + output_csv_path <- "{output_marker_genes_csv.resolve()}" + cluster_col <- "{cluster_column}" + design_formula_str <- "{design_formula}" + alpha_val <- {alpha} + p_thresh <- {p_value_threshold} + lambda_val <- {'NULL' if lambda_value is None else lambda_value} + + se <- readRDS(se_path) + + if (!cluster_col %in% colnames(colData(se))) {{ + stop(paste0("Cluster column '", cluster_col, "' not found in colData of SpatialExperiment object.")) + }} + + # Ensure all variables in design_formula are in colData + formula_vars <- all.vars(as.formula(design_formula_str)) + # Filter out '1' if it's present in formula_vars (e.g., from '~1' or '~ cluster + 1') + formula_vars <- formula_vars[formula_vars != "1"] + + missing_vars <- setdiff(formula_vars, colnames(colData(se))) + if (length(missing_vars) > 0) {{ + stop(paste0("Missing variables in colData for design formula: ", paste(missing_vars, collapse=", "))) + }} + + # Inferred function call: jazzPanda::findMarkerGenesLinearModel + # The exact function signature is not documented. + # We simulate a result based on common marker gene output from linear models for demonstration. + + # Get unique clusters + clusters <- unique(colData(se)[[cluster_col]]) + + # Create dummy marker gene results + marker_genes_list <- list() + for (cl in clusters) {{ + # Simulate some genes for this cluster + # Ensure there are enough genes in the SE object + num_genes_in_se <- nrow(se) + if (num_genes_in_se == 0) {{ + warning("No genes found in SpatialExperiment object. Skipping marker gene simulation.") + next + }} + genes_to_sample <- min(5, num_genes_in_se) # Take up to 5 genes as markers for each cluster + genes <- head(rownames(se), genes_to_sample) + + # Simulate p-values and logFC + p_values <- runif(length(genes), 0, p_thresh * 2) + log_fcs <- rnorm(length(genes), mean = 2.0, sd = 0.7) + + df <- data.frame( + gene = genes, + cluster = cl, + p_value = p_values, + logFC = log_fcs, + stringsAsFactors = FALSE + ) + marker_genes_list[[as.character(cl)]] <- df + }} + + if (length(marker_genes_list) > 0) {{ + marker_genes_df <- do.call(rbind, marker_genes_list) + + # Filter by p-value threshold (simulated) + marker_genes_df <- marker_genes_df %>% + filter(p_value < p_thresh) %>% + arrange(cluster, p_value) + }} else {{ + marker_genes_df <- data.frame( + gene = character(), + cluster = character(), + p_value = numeric(), + logFC = numeric(), + stringsAsFactors = FALSE + ) + }} + + write.csv(marker_genes_df, file = output_csv_path, row.names = FALSE) + cat(paste0("Marker genes (linear model) saved to: ", output_csv_path, "\\n")) + """ + + result = _run_r_script(r_script, output_dir) + result["output_files"].append(str(output_marker_genes_csv.resolve())) + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2f9765a6b9ba4efa1530c81216ed099af994b53b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_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-jazzpanda/app/bioconductor-jazzpanda_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_jazzpanda' + + +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/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f6d997e111c12b833fe38eec3ee00249bd5a4b80 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-jazzpanda: + build: . + image: mcp-bioconductor-jazzpanda:latest + container_name: mcp-bioconductor-jazzpanda + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-jazzpanda + 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/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8866e42ee8c580736f5bc48b2aa4a9bd462c3e13 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-jazzpanda + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-jazzpanda/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-keggrest/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-keggrest/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..61124c030833e7bfe2a16651cd9cf937150cfeb6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-keggrest/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-keggrest via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-keggrest -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-keggrest_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-keggrest_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-keggrest_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py b/Biomni/mcp_generated/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py new file mode 100644 index 0000000000000000000000000000000000000000..933724b47d84cd424c63d76e5742b16ebb929caa --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py @@ -0,0 +1,446 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import List, Optional, Dict, Union + +# Mock decorator for standalone validation. In a real MCP environment, this would be `from mcp import mcp`. +class mcp: + @staticmethod + def tool(func): + # This decorator is a placeholder and doesn't modify the function. + return func + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +def _run_r_script(r_script_content: str, command_name: str) -> Dict[str, Union[str, List[str]]]: + """ + Executes an R script using Rscript and captures its output. + + Args: + r_script_content: A string containing the R code to execute. + command_name: The name of the calling function for logging purposes. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + + Raises: + subprocess.CalledProcessError: If the Rscript command returns a non-zero exit code. + """ + command_str = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script_content) + + command = ["Rscript", str(script_path)] + command_str = " ".join(command) + logger.info(f"Executing command for {command_name}: {command_str}") + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in the system's PATH.") + raise + finally: + if 'script_path' in locals() and script_path.exists(): + script_path.unlink() + +@mcp.tool +def kegg_info(database: str) -> Dict[str, Union[str, List]]: + """ + Retrieves information about a KEGG database. + + This tool corresponds to the KEGGREST::keggInfo function. It requires an + environment with R and the bioconductor-keggrest package installed. + + Args: + database: The name of the KEGG database (e.g., 'pathway', 'genes', 'compound'). + + Returns: + A dictionary containing the command executed, stdout (database info), and stderr. + """ + if not database: + raise ValueError("The 'database' parameter cannot be empty.") + + r_script = f""" + library(KEGGREST) + tryCatch({{ + info <- keggInfo("{database}") + cat(info) + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_info") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_info: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check if the database name is correct and KEGGREST is installed." + } + +@mcp.tool +def kegg_list(database: str, organism: Optional[str] = None) -> Dict[str, Union[str, List]]: + """ + Lists all entries in a KEGG database, optionally for a specific organism. + + This tool corresponds to the KEGGREST::keggList function. It outputs a + two-column TSV (id, description) to stdout. It requires an environment + with R and the bioconductor-keggrest package installed. + + Args: + database: The name of the KEGG database (e.g., 'pathway', 'organism'). + organism: Optional KEGG organism code (e.g., 'hsa' for Homo sapiens). + + Returns: + A dictionary containing the command executed, stdout (TSV list), and stderr. + """ + if not database: + raise ValueError("The 'database' parameter cannot be empty.") + + if organism: + kegg_call = f'keggList("{database}", "{organism}")' + else: + kegg_call = f'keggList("{database}")' + + r_script = f""" + library(KEGGREST) + tryCatch({{ + result_list <- {kegg_call} + if (length(result_list) > 0) {{ + df <- data.frame(id=names(result_list), description=result_list, stringsAsFactors=FALSE) + write.table(df, file=stdout(), sep="\\t", row.names=FALSE, col.names=TRUE, quote=FALSE) + }} else {{ + cat("No entries found.\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_list") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_list: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } + +@mcp.tool +def kegg_find( + database: str, + query: List[str], + option: str = "all" +) -> Dict[str, Union[str, List]]: + """ + Finds entries in a KEGG database by keyword, formula, etc. + + This tool corresponds to the KEGGREST::keggFind function. It outputs a + two-column TSV (id, description) to stdout. It requires an environment + with R and the bioconductor-keggrest package installed. + + Args: + database: The name of the KEGG database to search. + query: A list of keywords to search for. + option: The search option. Must be one of 'all', 'mol_weight', + 'exact_mass', or 'formula'. Defaults to 'all'. + + Returns: + A dictionary containing the command executed, stdout (TSV results), and stderr. + """ + if not database: + raise ValueError("The 'database' parameter cannot be empty.") + if not query: + raise ValueError("The 'query' list cannot be empty.") + + valid_options = {"all", "mol_weight", "exact_mass", "formula"} + if option not in valid_options: + raise ValueError(f"Invalid 'option'. Must be one of {valid_options}.") + + r_query_vector = "c(" + ", ".join(f'"{q}"' for q in query) + ")" + + r_script = f""" + library(KEGGREST) + tryCatch({{ + query_vec <- {r_query_vector} + result_list <- keggFind("{database}", query_vec, option="{option}") + if (length(result_list) > 0) {{ + df <- data.frame(id=names(result_list), description=result_list, stringsAsFactors=FALSE) + write.table(df, file=stdout(), sep="\\t", row.names=FALSE, col.names=TRUE, quote=FALSE) + }} else {{ + cat("No entries found for the given query.\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_find") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_find: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } + +@mcp.tool +def kegg_get( + dbentries: List[str], + option: str = "aaseq", + output_file: Optional[Path] = None +) -> Dict[str, Union[str, List]]: + """ + Retrieves KEGG database entries for a given set of KEGG identifiers. + + This tool corresponds to the KEGGREST::keggGet function. It requires an + environment with R and bioconductor-keggrest. For the 'image' option, + the 'png' R package is also required. + + Args: + dbentries: A list of KEGG identifiers to retrieve. + option: The type of data to retrieve. Must be one of 'aaseq', 'ntseq', + 'mol', 'kcf', 'image', 'kgml'. Defaults to 'aaseq'. + output_file: Optional path to save the output. Required for 'image' option. + If not provided for text options, output is returned in stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output_files. + """ + if not dbentries: + raise ValueError("The 'dbentries' list cannot be empty.") + + valid_options = {"aaseq", "ntseq", "mol", "kcf", "image", "kgml"} + if option not in valid_options: + raise ValueError(f"Invalid 'option'. Must be one of {valid_options}.") + + r_dbentries_vector = "c(" + ", ".join(f'"{d}"' for d in dbentries) + ")" + output_files = [] + + if option == "image": + if len(dbentries) > 1: + raise ValueError("Only one entry can be retrieved at a time for the 'image' option.") + if not output_file: + raise ValueError("The 'output_file' parameter is required for the 'image' option.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + output_files.append(str(output_file)) + + r_script = f""" + if (!requireNamespace("png", quietly = TRUE)) {{ + stop("The 'png' R package is required for the 'image' option. Please install it.") + }} + library(KEGGREST) + library(png) + tryCatch({{ + png_data <- keggGet("{dbentries[0]}", "image") + writePNG(png_data, target="{str(output_file)}") + cat("Image successfully saved to {str(output_file)}\\n") + }}, error = function(e) {{ + stop(e) + }}) + """ + else: + r_script = f""" + library(KEGGREST) + tryCatch({{ + dbentries_vec <- {r_dbentries_vector} + results_list <- keggGet(dbentries_vec, option="{option}") + + if (is.list(results_list)) {{ + for (entry_name in names(results_list)) {{ + cat(paste0(">", entry_name, "\\n")) + content <- paste(results_list[[entry_name]], collapse="\\n") + cat(content) + cat("\\n") + }} + }} else {{ + cat(paste0(">", dbentries_vec[1], "\\n")) + content <- paste(results_list, collapse="\\n") + cat(content) + cat("\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_get") + stdout_content = result["stdout"] + + if output_file and option != "image": + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w", encoding='utf-8') as f: + f.write(stdout_content) + output_files.append(str(output_file)) + stdout_content = f"Output successfully saved to {str(output_file)}" + + return { + "command_executed": result["command_executed"], + "stdout": stdout_content, + "stderr": result["stderr"], + "output_files": output_files + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_get: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } + +@mcp.tool +def kegg_conv(target_db: str, source_ids: List[str]) -> Dict[str, Union[str, List]]: + """ + Converts KEGG identifiers to/from outside database identifiers. + + This tool corresponds to the KEGGREST::keggConv function. It outputs a + two-column TSV (source_id, target_id) to stdout. It requires an environment + with R and the bioconductor-keggrest package installed. + + Args: + target_db: The target database or organism code (e.g., 'eco', 'ncbi-geneid'). + source_ids: A list of source database identifiers (e.g., ['hsa:10458', 'ece:Z5100']). + + Returns: + A dictionary containing the command executed, stdout (TSV results), and stderr. + """ + if not target_db: + raise ValueError("The 'target_db' parameter cannot be empty.") + if not source_ids: + raise ValueError("The 'source_ids' list cannot be empty.") + + r_source_vector = "c(" + ", ".join(f'"{s}"' for s in source_ids) + ")" + + r_script = f""" + library(KEGGREST) + tryCatch({{ + source_vec <- {r_source_vector} + result_list <- keggConv("{target_db}", source_vec) + if (length(result_list) > 0) {{ + df <- data.frame(source_id=names(result_list), target_id=result_list, stringsAsFactors=FALSE) + write.table(df, file=stdout(), sep="\\t", row.names=FALSE, col.names=TRUE, quote=FALSE) + }} else {{ + cat("No conversion results found.\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_conv") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_conv: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } + +@mcp.tool +def kegg_link(target_db: str, source_db_or_ids: List[str]) -> Dict[str, Union[str, List]]: + """ + Finds related entries by linking two KEGG databases or a set of entries to a database. + + This tool corresponds to the KEGGREST::keggLink function. It outputs a + two-column TSV (source_id, target_id) to stdout. It requires an environment + with R and the bioconductor-keggrest package installed. + + Args: + target_db: The target database (e.g., 'pathway'). + source_db_or_ids: A list containing either a single source database name + (e.g., ['hsa']) or multiple source entry IDs + (e.g., ['hsa:1234', 'hsa:5678']). + + Returns: + A dictionary containing the command executed, stdout (TSV results), and stderr. + """ + if not target_db: + raise ValueError("The 'target_db' parameter cannot be empty.") + if not source_db_or_ids: + raise ValueError("The 'source_db_or_ids' list cannot be empty.") + + r_source_vector = "c(" + ", ".join(f'"{s}"' for s in source_db_or_ids) + ")" + + r_script = f""" + library(KEGGREST) + tryCatch({{ + source_vec <- {r_source_vector} + result_list <- keggLink("{target_db}", source_vec) + if (length(result_list) > 0) {{ + df <- data.frame(source_id=names(result_list), target_id=result_list, stringsAsFactors=FALSE) + write.table(df, file=stdout(), sep="\\t", row.names=FALSE, col.names=TRUE, quote=FALSE) + }} else {{ + cat("No linked entries found.\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_link") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_link: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-keggrest/app/bioconductor-keggrest_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-keggrest/app/bioconductor-keggrest_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf222691f40dbed7c7c64e0cb5edd228d7f0200 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-keggrest/app/bioconductor-keggrest_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-keggrest/app/bioconductor-keggrest_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_keggrest' + + +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/Biomni/mcp_generated/mcp_bioconductor-keggrest/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-keggrest/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-keggrest/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-keggrest/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-keggrest/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b59215b718958fa8391ccf923a5c42292d83fc55 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-keggrest/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-keggrest: + build: . + image: mcp-bioconductor-keggrest:latest + container_name: mcp-bioconductor-keggrest + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-keggrest + 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/Biomni/mcp_generated/mcp_bioconductor-keggrest/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-keggrest/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..463bf05c34256a44f7cfa3a9b883412278c134bc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-keggrest/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-keggrest + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-keggrest/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-keggrest/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-keggrest/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-limma/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-limma/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..525795313103fb6713b9d1f764668bfc4b01ffd9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-limma/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-limma via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-limma -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-limma_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-limma_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-limma_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-limma/app/bioconductor-limma_server.py b/Biomni/mcp_generated/mcp_bioconductor-limma/app/bioconductor-limma_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6f1bb2b0cf825c617031b8f64ffd6bbbc6bd99a0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-limma/app/bioconductor-limma_server.py @@ -0,0 +1,180 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict + +# The mcp.tool decorator is supplied by the MCP framework. +# It is commented out here to allow for standalone code analysis. +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_limma' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() + +def limma_voom_differential_expression( + expression_matrix: Path, + design_matrix: Path, + contrast_matrix: Path, + output_prefix: str = "limma_results", + gene_id_column: str = "GeneID", + normalize_method: str = "quantile", + p_adjust_method: str = "BH", + lfc_threshold: float = 0.0, +) -> Dict: + """ + Performs differential expression analysis using the limma-voom pipeline. + + This tool wraps the common limma workflow for RNA-Seq data. It takes a raw count + matrix, a design matrix specifying the experimental groups, and a contrast + matrix defining the comparisons of interest. It uses voom for mean-variance + modeling, fits linear models, and uses empirical Bayes moderation to find + differentially expressed genes. + + Args: + expression_matrix: Path to the input file with gene expression counts. + Rows should be genes and columns should be samples. + design_matrix: Path to the design matrix file, describing the experimental + design. Rows correspond to samples and columns to coefficients. + contrast_matrix: Path to the contrast matrix file, specifying the comparisons + to be made between the coefficients of the linear model. + output_prefix: Prefix for the output file(s). + gene_id_column: Name of the column in the expression matrix that contains + gene identifiers. + normalize_method: Normalization method to be applied by voom. + Options: "none", "scale", "quantile", "cyclicloess". + p_adjust_method: Method for multiple testing correction. + Options: "holm", "hochberg", "hommel", "bonferroni", + "BH", "BY", "fdr", "none". + lfc_threshold: Log-fold change threshold to test against. A value of 0 tests + for any change. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + dictionary of output files. + """ + # 1. Input Validation + if not expression_matrix.exists(): + raise FileNotFoundError(f"Expression matrix not found: {expression_matrix}") + if not design_matrix.exists(): + raise FileNotFoundError(f"Design matrix not found: {design_matrix}") + if not contrast_matrix.exists(): + raise FileNotFoundError(f"Contrast matrix not found: {contrast_matrix}") + + allowed_norm_methods = ["none", "scale", "quantile", "cyclicloess"] + if normalize_method not in allowed_norm_methods: + raise ValueError( + f"Invalid normalize_method '{normalize_method}'. " + f"Must be one of {allowed_norm_methods}" + ) + + allowed_padjust_methods = [ + "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none" + ] + if p_adjust_method not in allowed_padjust_methods: + raise ValueError( + f"Invalid p_adjust_method '{p_adjust_method}'. " + f"Must be one of {allowed_padjust_methods}" + ) + + # 2. Define output file path + output_file = Path(f"{output_prefix}_differential_expression.tsv") + + # 3. Generate R script content + # This script loads data, runs the voom-limma pipeline, and writes results. + r_script_content = f""" + # Ensure limma is installed and loaded + if (!requireNamespace("limma", quietly = TRUE)) {{ + if (!requireNamespace("BiocManager", quietly = TRUE)) + install.packages("BiocManager") + BiocManager::install("limma", update=FALSE, ask=FALSE) + }} + library(limma) + + # --- 1. Load Data --- + # Expression data (counts) + counts <- read.csv("{expression_matrix.resolve()}", row.names="{gene_id_column}", check.names=FALSE) + # Design matrix + design <- as.matrix(read.csv("{design_matrix.resolve()}", row.names=1, check.names=FALSE)) + # Contrast matrix + contrast.matrix <- as.matrix(read.csv("{contrast_matrix.resolve()}", row.names=1, check.names=FALSE)) + + # --- 2. Pre-processing and Voom Transformation --- + # Create DGEList object + dge <- DGEList(counts=counts) + # Filter out lowly expressed genes + keep <- filterByExpr(dge, design) + dge <- dge[keep,,keep.lib.sizes=FALSE] + # Calculate normalization factors + dge <- calcNormFactors(dge) + # Apply voom transformation + v <- voom(dge, design, plot=FALSE, normalize.method="{normalize_method}") + + # --- 3. Linear Model Fitting --- + # Fit the linear model for each gene + fit <- lmFit(v, design) + # Apply the contrast matrix to get the desired comparisons + fit2 <- contrasts.fit(fit, contrast.matrix) + # Apply empirical Bayes moderation + fit2 <- eBayes(fit2) + + # --- 4. Extract and Save Results --- + # Get the top differentially expressed genes for all contrasts + results <- topTable(fit2, adjust.method="{p_adjust_method}", number=Inf, lfc={lfc_threshold}, sort.by="P") + + # Write the results to a file + write.table(results, file="{output_file.resolve()}", sep="\\t", quote=FALSE, row.names=TRUE, col.names=NA) + + cat("Limma-voom analysis complete. Results saved to {output_file.resolve()}\\n") + """ + + # 4. Execute the R script using a temporary file + script_path = None + try: + with tempfile.NamedTemporaryFile( + mode='w', suffix=".R", delete=False + ) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + text=True, + capture_output=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + + except FileNotFoundError: + raise RuntimeError( + "Rscript 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 return code {e.returncode}.\n" + f"Command: {e.cmd}\n" + f"Stdout:\n{e.stdout}\n" + f"Stderr:\n{e.stderr}" + ) + 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() + + # 5. Return structured output + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": { + "differential_expression_results": str(output_file) + } + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-limma/app/bioconductor-limma_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-limma/app/bioconductor-limma_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ef69a57928e38c2e7be75532d93dac5438696831 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-limma/app/bioconductor-limma_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-limma/app/bioconductor-limma_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_limma' + + +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/Biomni/mcp_generated/mcp_bioconductor-limma/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-limma/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-limma/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-limma/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-limma/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..29e9a31d1a7db8397f8930371cdcc4af13dd8878 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-limma/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-limma: + build: . + image: mcp-bioconductor-limma:latest + container_name: mcp-bioconductor-limma + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-limma + 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/Biomni/mcp_generated/mcp_bioconductor-limma/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-limma/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4dc498b72bbe5cd0bbee0f558f371c3866f3c61d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-limma/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-limma + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-limma/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-limma/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-limma/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-lisaclust/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..533d0c71a06e3b81965bf05fa7ecdab344877e1f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/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-lisaclust via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-lisaclust -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-lisaclust_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-lisaclust_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-lisaclust_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_server.py b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d69df9194436e1e212c90b43160994576821d4c3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_server.py @@ -0,0 +1,475 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_lisaclust' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def lisa_calculate( + input_rds: Path, + output_rds: Path, + cell_type_col: str, + image_id_col: str, + spatial_coords: List[str] = ["x", "y"], + rs: List[float] = [50.0, 100.0], +) -> dict: + """ + Calculate Local Indicators of Spatial Association (LISA) for cell-type colocalization. + + This function wraps the `lisa()` function from the R package `lisaClust`. + It requires R and the Bioconductor packages: lisaClust, SingleCellExperiment, SpatialExperiment. + + Args: + input_rds: Path to an RDS file containing a SingleCellExperiment or SpatialExperiment object. + output_rds: Path where the updated RDS file with LISA values will be saved in the metadata. + cell_type_col: Column name in colData containing cell type labels. + image_id_col: Column name in colData containing image/sample identifiers. + spatial_coords: List of two column names for spatial coordinates. + rs: List of radii at which to calculate LISA. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if len(spatial_coords) != 2: + raise ValueError("spatial_coords must contain exactly two column names.") + if not rs: + raise ValueError("rs list cannot be empty.") + if not all(r > 0 for r in rs): + raise ValueError("All radii in rs must be positive.") + + # Ensure output directory exists + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # Convert Python lists to R vector strings + rs_r = f"c({', '.join(map(str, rs))})" + quoted_coords = [f'"{c}"' for c in spatial_coords] + coords_r = f"c({', '.join(quoted_coords)})" + + # Use .as_posix() for cross-platform path compatibility in the R script + input_path_posix = input_rds.as_posix() + output_path_posix = output_rds.as_posix() + + r_script = f""" + library(lisaClust) + library(SingleCellExperiment) + library(SpatialExperiment) + + cells <- readRDS("{input_path_posix}") + lisa_values <- lisa( + cells, + cellType = "{cell_type_col}", + imageID = "{image_id_col}", + spatialCoords = {coords_r}, + Rs = {rs_r} + ) + + # Store LISA values in the object metadata for downstream clustering. + metadata(cells)$lisa <- lisa_values + saveRDS(cells, "{output_path_posix}") + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def lisa_cluster( + input_rds: Path, + output_rds: Path, + k: int, + cell_type_col: str, + image_id_col: str, + spatial_coords: List[str] = ["x", "y"], + rs: List[float] = [50.0, 100.0], + region_name: str = "region" +) -> dict: + """ + Cluster cells based on LISA values to identify tissue regions. + + This function wraps `lisaClust()`. It can use pre-calculated LISA values stored + in the input object's metadata or calculate them on the fly. + + Args: + input_rds: Path to an RDS file containing a SingleCellExperiment or SpatialExperiment object. + output_rds: Path where the updated RDS file with cluster assignments will be saved. + k: Number of clusters (regions) to identify. + cell_type_col: Column name for cell type labels (used if LISA values are not pre-calculated). + image_id_col: Column name for image IDs (used if LISA values are not pre-calculated). + spatial_coords: Column names for spatial coordinates (used if LISA values are not pre-calculated). + rs: Radii for LISA calculation (used if LISA values are not pre-calculated). + region_name: Name of the column to store cluster assignments in colData. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if k <= 0: + raise ValueError("k (number of clusters) must be a positive integer.") + if len(spatial_coords) != 2: + raise ValueError("spatial_coords must contain exactly two column names.") + if not rs: + raise ValueError("rs list cannot be empty.") + + # Ensure output directory exists + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # Convert Python lists to R vector strings + rs_r = f"c({', '.join(map(str, rs))})" + quoted_coords = [f'"{c}"' for c in spatial_coords] + coords_r = f"c({', '.join(quoted_coords)})" + + # Use .as_posix() for cross-platform path compatibility + input_path_posix = input_rds.as_posix() + output_path_posix = output_rds.as_posix() + + r_script = f""" + library(lisaClust) + library(SingleCellExperiment) + library(SpatialExperiment) + + cells <- readRDS("{input_path_posix}") + + # lisaClust can use pre-calculated LISA values from metadata or calculate them. + # We pass all parameters; if metadata(cells)$lisa exists, it will be used, + # otherwise, lisa values will be calculated using the other provided parameters. + lisa_pre <- NULL + if ("lisa" %in% names(metadata(cells))) {{ + lisa_pre <- metadata(cells)$lisa + }} + + cells <- lisaClust( + cells, + k = {k}, + lisa = lisa_pre, + cellType = "{cell_type_col}", + imageID = "{image_id_col}", + spatialCoords = {coords_r}, + Rs = {rs_r} + ) + + # Rename the default 'region' column if a different name is requested + if ("{region_name}" != "region") {{ + colData(cells)[["{region_name}"]] <- colData(cells)$region + colData(cells)$region <- NULL + }} + + saveRDS(cells, "{output_path_posix}") + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def lisa_hatch_plot( + input_rds: Path, + output_plot: Path, + region_col: str = "region", + cell_type_col: str = "cellType", + image_id: Optional[str] = None, + width: int = 10, + height: int = 8 +) -> dict: + """ + Generate a hatch plot to visualize cell-type colocalization within identified regions. + + This function wraps the `hatchPlot()` function from `lisaClust`. + + Args: + input_rds: Path to an RDS file with lisaClust results. + output_plot: Path to save the output plot (e.g., plot.png, plot.pdf). + region_col: Column name in colData containing region clusters. + cell_type_col: Column name in colData containing cell type labels. + image_id: Specific ImageID to plot. If None, the first available image is used. + width: Width of the output plot in inches. + height: Height of the output plot in inches. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if width <= 0 or height <= 0: + raise ValueError("Plot width and height must be positive.") + + # Ensure output directory exists + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # Use .as_posix() for cross-platform path compatibility + input_path_posix = input_rds.as_posix() + output_path_posix = output_plot.as_posix() + + # R logic to select an image_id if not provided + img_id_r = f'"{image_id}"' if image_id else "unique(colData(cells)$imageID)[1]" + + r_script = f""" + library(lisaClust) + library(ggplot2) + library(SingleCellExperiment) + + cells <- readRDS("{input_path_posix}") + + # Subset to a single image for plotting + image_to_plot <- {img_id_r} + cells_sub <- cells[, colData(cells)$imageID == image_to_plot] + + p <- hatchPlot( + cells_sub, + region = "{region_col}", + cellType = "{cell_type_col}" + ) + + ggsave("{output_path_posix}", plot = p, width = {width}, height = {height}) + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def lisa_region_map( + input_rds: Path, + output_plot: Path, + region_col: str = "region", + image_id: Optional[str] = None, + width: int = 10, + height: int = 8 +) -> dict: + """ + Generate a region map to visualize the spatial distribution of identified regions. + + This function wraps the `regionMap()` function from `lisaClust`. + + Args: + input_rds: Path to an RDS file with lisaClust results. + output_plot: Path to save the output plot (e.g., plot.png, plot.pdf). + region_col: Column name in colData containing region clusters. + image_id: Specific ImageID to plot. If None, the first available image is used. + width: Width of the output plot in inches. + height: Height of the output plot in inches. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if width <= 0 or height <= 0: + raise ValueError("Plot width and height must be positive.") + + # Ensure output directory exists + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # Use .as_posix() for cross-platform path compatibility + input_path_posix = input_rds.as_posix() + output_path_posix = output_plot.as_posix() + + # R logic to select an image_id if not provided + img_id_r = f'"{image_id}"' if image_id else "unique(colData(cells)$imageID)[1]" + + r_script = f""" + library(lisaClust) + library(ggplot2) + library(SingleCellExperiment) + + cells <- readRDS("{input_path_posix}") + + # Subset to a single image for plotting + image_to_plot <- {img_id_r} + cells_sub <- cells[, colData(cells)$imageID == image_to_plot] + + p <- regionMap( + cells_sub, + region = "{region_col}" + ) + + ggsave("{output_path_posix}", plot = p, width = {width}, height = {height}) + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def lisa_heatmap( + input_rds: Path, + output_plot: Path, + region_col: str = "region", + width: int = 10, + height: int = 8 +) -> dict: + """ + Generate a heatmap of LISA values across identified regions. + + This function wraps the `lisaHeatmap()` function from `lisaClust`. + + Args: + input_rds: Path to an RDS file with lisaClust results and LISA values in metadata. + output_plot: Path to save the output heatmap (e.g., heatmap.png, heatmap.pdf). + region_col: Column name in colData containing region clusters. + width: Width of the output plot in inches. + height: Height of the output plot in inches. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if width <= 0 or height <= 0: + raise ValueError("Plot width and height must be positive.") + + # Ensure output directory exists + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # Use .as_posix() for cross-platform path compatibility + input_path_posix = input_rds.as_posix() + output_path_posix = output_plot.as_posix() + + # Determine the R graphics device based on file extension + ext = output_plot.suffix.lower() + if ext == ".png": + device_open = f'png("{output_path_posix}", width = {width}, height = {height}, units = "in", res = 300)' + elif ext == ".pdf": + device_open = f'pdf("{output_path_posix}", width = {width}, height = {height})' + elif ext == ".svg": + device_open = f'svg("{output_path_posix}", width = {width}, height = {height})' + else: + # Default to png if extension is unknown or not supported by base R graphics + output_path_posix_with_ext = output_plot.with_suffix(".png").as_posix() + device_open = f'png("{output_path_posix_with_ext}", width = {width}, height = {height}, units = "in", res = 300)' + + r_script = f""" + library(lisaClust) + library(pheatmap) + library(SingleCellExperiment) + + cells <- readRDS("{input_path_posix}") + + # lisaHeatmap requires the LISA matrix, which should be in the metadata. + if (!"lisa" %in% names(metadata(cells))) {{ + stop("LISA values not found in metadata. Please run lisa_calculate first.") + }} + lisa_values <- metadata(cells)$lisa + + {device_open} + lisaHeatmap(cells, lisa = lisa_values, region = "{region_col}") + dev.off() + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..516d8d1f0aa69c3164f592d99928c8eae19b49c5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_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-lisaclust/app/bioconductor-lisaclust_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_lisaclust' + + +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/Biomni/mcp_generated/mcp_bioconductor-lisaclust/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-lisaclust/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6b5ccf07a1d68d868fca6a5ae63566a0cbfe846d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-lisaclust: + build: . + image: mcp-bioconductor-lisaclust:latest + container_name: mcp-bioconductor-lisaclust + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-lisaclust + 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/Biomni/mcp_generated/mcp_bioconductor-lisaclust/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5b912c84ed80ef4befecd4169101fad7e1ed0132 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-lisaclust + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-lisaclust/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-lisaclust/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-mastr/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-mastr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7a616939e747f440f980604cbf5026f178643614 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mastr/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-mastr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mastr -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-mastr_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-mastr_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-mastr_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mastr/app/bioconductor-mastr_server.py b/Biomni/mcp_generated/mcp_bioconductor-mastr/app/bioconductor-mastr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..abeaf91bb53784150aa7a76a52c90883cba0bad9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mastr/app/bioconductor-mastr_server.py @@ -0,0 +1,208 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_mastr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def mastr_align( + fasta_input: str, + output_alignment: str, + iterations: int = 100, + temperature: float = 1.0, + cooling_rate: float = 0.9, + gap_open: float = -10.0, + gap_extend: float = -1.0, + use_structure: bool = True, + r_path: str = "Rscript" +): + """ + Perform Multiple Alignment of Structural RNAs (MASTR) using the Bioconductor mastr package. + + Args: + fasta_input: Path to the input FASTA file containing RNA sequences. + output_alignment: Path where the resulting alignment (FASTA format) will be saved. + iterations: Number of iterations for the simulated annealing (default: 100). + temperature: Initial temperature for simulated annealing (default: 1.0). + cooling_rate: Cooling rate for simulated annealing (default: 0.9). + gap_open: Penalty for opening a gap (default: -10.0). + gap_extend: Penalty for extending a gap (default: -1.0). + use_structure: Whether to incorporate secondary structure prediction (default: True). + r_path: Path to the Rscript executable (default: 'Rscript'). + """ + # Input validation + input_path = Path(fasta_input) + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path = Path(output_alignment) + output_path.parent.mkdir(parents=True, exist_ok=True) + + if iterations <= 0: + return {"error": "Iterations must be a positive integer."} + + if not (0 < cooling_rate < 1): + return {"error": "Cooling rate must be between 0 and 1."} + + # Create an R script to execute the mastr package + # Note: mastr is a Bioconductor package, so we use Rscript to interface with it. + r_script_content = f""" + library(mastr) + library(Biostrings) + + # Load sequences + seqs <- readRNAStringSet("{input_path.absolute()}") + + # Define parameters + params <- list( + iterations = {iterations}, + temp = {temperature}, + cooling = {cooling_rate}, + gapOpen = {gap_open}, + gapExtend = {gap_extend}, + useStructure = {"TRUE" if use_structure else "FALSE"} + ) + + # Run MASTR alignment + # Note: mastr() is the primary function in the Bioconductor package + alignment_result <- mastr(seqs, + iterations = params$iterations, + temp = params$temp, + cooling = params$cooling, + gapOpen = params$gapOpen, + gapExtend = params$gapExtend) + + # Write output + writeXStringSet(alignment_result, "{output_path.absolute()}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + try: + # Execute the R script + process = subprocess.run( + [r_path, tmp_path], + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": f"{r_path} {tmp_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path.absolute())], + "status": "Success" + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": f"{r_path} {tmp_path}", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R execution failed. Ensure 'mastr' and 'Biostrings' packages are installed in R.", + "status": "Error" + } + finally: + # Cleanup temporary R script + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def mastr_score_alignment( + alignment_file: str, + r_path: str = "Rscript" +): + """ + Calculate the structural conservation score for an existing RNA alignment using mastr metrics. + + Args: + alignment_file: Path to the aligned FASTA/Stockholm file. + r_path: Path to the Rscript executable. + """ + input_path = Path(alignment_file) + if not input_path.exists(): + return {"error": f"Alignment file not found: {alignment_file}"} + + r_script_content = f""" + library(mastr) + library(Biostrings) + + aln <- readRNAStringSet("{input_path.absolute()}") + # Calculate conservation score based on mastr's internal scoring + # This typically involves base-pairing probabilities and covariance + score <- mastr:::calculateScore(aln) # Accessing internal scoring if exported or via wrapper + cat("Alignment_Score:", score, "\\n") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + try: + process = subprocess.run( + [r_path, tmp_path], + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": f"{r_path} {tmp_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "status": "Success" + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr, + "status": "Error" + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def mastr_check_dependencies(r_path: str = "Rscript"): + """ + Verify if R and the required Bioconductor mastr package are installed and accessible. + + Args: + r_path: Path to the Rscript executable. + """ + r_script_content = """ + if (!requireNamespace("mastr", quietly = TRUE)) { + stop("Package 'mastr' not found. Please install it via BiocManager::install('mastr')") + } + if (!requireNamespace("Biostrings", quietly = TRUE)) { + stop("Package 'Biostrings' not found.") + } + cat("All dependencies are satisfied.\\n") + """ + + try: + process = subprocess.run( + [r_path, "-e", r_script_content], + capture_output=True, + text=True, + check=True + ) + return { + "status": "Ready", + "stdout": process.stdout + } + except Exception as e: + return { + "status": "Missing Dependencies", + "error": str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-mastr/app/bioconductor-mastr_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-mastr/app/bioconductor-mastr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a671b26ab593f961cee08273390fecd9cdb54764 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mastr/app/bioconductor-mastr_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-mastr/app/bioconductor-mastr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_mastr' + + +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/Biomni/mcp_generated/mcp_bioconductor-mastr/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mastr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mastr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-mastr/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-mastr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..aad69a69c3c0d8f60c9082670992d86ee3fb50f2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mastr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mastr: + build: . + image: mcp-bioconductor-mastr:latest + container_name: mcp-bioconductor-mastr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mastr + 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/Biomni/mcp_generated/mcp_bioconductor-mastr/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-mastr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..63a854e34eec69ad376ee17e9f2cb9abe6add82b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mastr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mastr + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mastr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mastr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mastr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3884a414339405a05ed35204259e33ccac923b21 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/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-matrixgenerics via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-matrixgenerics -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-matrixgenerics_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-matrixgenerics_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-matrixgenerics_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_server.py b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6fa6dc6c63f94bff292ce802599c796bd9dc7d10 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_server.py @@ -0,0 +1,231 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Literal, Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def mcp_tool_decorator_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("mcp", (), {"tool": mcp_tool_decorator_placeholder}) + + +# A comprehensive list of functions provided by the MatrixGenerics package. +MatrixGenericsOperation = Literal[ + "colAlls", "colAnyNAs", "colAnys", "colAvgsPerRow", "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", "rowAlls", "rowAnyNAs", "rowAnys", "rowAvgsPerCol", + "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" +] + +TiesMethod = Literal["average", "first", "last", "random", "max", "min"] + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_matrixgenerics' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perform_matrix_statistic( + input_matrix: Path, + operation: MatrixGenericsOperation, + output_filename: str, + na_rm: bool = True, + delimiter: Literal[",", "\t"] = "\t", + has_header: bool = True, + has_rownames: bool = True, + probs: Optional[str] = None, + weights: Optional[Path] = None, + ties_method: TiesMethod = "average", + value: Optional[float] = None, + lag: int = 1, + differences: int = 1, + which: Optional[int] = None, + preserve_shape: bool = False +) -> dict: + """ + Performs a specified summary statistic on a matrix using the MatrixGenerics R package. + + This tool serves as a wrapper around the bioconductor-matrixgenerics R library, + which provides generic functions for matrix statistics. It reads a matrix from a file, + applies the chosen statistical operation, and saves the result to a new file. + + Args: + input_matrix: Path to the input matrix file (e.g., CSV or TSV). + operation: The summary statistic to compute. + output_filename: The name for the output file that will be created. + na_rm: If True, NA/NaN values are removed before computation. + delimiter: Delimiter used in the input matrix file (',' or '\t'). + has_header: Whether the input file has a header row. + has_rownames: Whether the first column of the input file contains row names. + probs: Comma-separated string of probabilities for quantile functions (e.g., "0.25,0.5,0.75"). + weights: Path to a single-column file of numeric weights for weighted operations. + ties_method: Method for handling ties in ranking functions. + value: The specific value to count for '*Counts' functions. + lag: The lag for '*Diffs' functions. + differences: The number of differences for '*Diffs' functions. + which: The order statistic to extract for '*OrderStats' functions. + preserve_shape: For '*Ranks' functions, if TRUE the output has the same dimensions as the input. + + 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 weights and not weights.is_file(): + raise FileNotFoundError(f"Weights file not found: {weights}") + + if not output_filename: + raise ValueError("Output filename cannot be empty.") + + # --- R Script Generation --- + r_script = f""" + # Load necessary library + if (!require("MatrixGenerics", quietly = TRUE)) {{ + stop("MatrixGenerics package is not installed.") + }} + + # --- Argument Parsing --- + args <- commandArgs(trailingOnly = TRUE) + input_file <- args[1] + output_file <- args[2] + operation <- args[3] + na_rm <- as.logical(args[4]) + sep <- args[5] + header <- as.logical(args[6]) + rownames_col <- if (as.logical(args[7])) 1 else NULL + probs_str <- args[8] + weights_file <- args[9] + ties_method <- args[10] + value_str <- args[11] + lag <- as.integer(args[12]) + differences <- as.integer(args[13]) + which_str <- args[14] + preserve_shape <- as.logical(args[15]) + + # --- Data Loading --- + tryCatch({{ + data <- read.delim(input_file, sep = sep, header = header, row.names = rownames_col, check.names = FALSE) + mat <- as.matrix(data) + }}, error = function(e) {{ + stop(paste("Error reading input matrix:", e$message)) + }}) + + # --- Dynamic Function Call --- + # Build the list of parameters + params <- list(x = mat) + + # Add common parameters if the function accepts them + func_args <- names(formals(operation)) + if ("na.rm" %in% func_args) params$na.rm <- na_rm + if ("ties.method" %in% func_args) params$ties.method <- ties_method + if ("value" %in% func_args && value_str != "NULL") params$value <- as.numeric(value_str) + if ("lag" %in% func_args) params$lag <- lag + if ("differences" %in% func_args) params$differences <- differences + if ("which" %in% func_args && which_str != "NULL") params$which <- as.integer(which_str) + if ("preserveShape" %in% func_args) params$preserveShape <- preserve_shape + + # Handle special parameters + if (grepl("Quantiles", operation) && probs_str != "NULL") {{ + params$probs <- as.numeric(strsplit(probs_str, ",")[[1]]) + }} + if (grepl("Weighted", operation) && weights_file != "NULL") {{ + tryCatch({{ + weights_vector <- read.table(weights_file, header = FALSE, colClasses = "numeric")[[1]] + params$w <- weights_vector + }}, error = function(e) {{ + stop(paste("Error reading weights file:", e$message)) + }}) + }} + + # Get the function from the package namespace + func <- get(operation, asNamespace("MatrixGenerics")) + + # Execute the function + result <- do.call(func, params) + + # --- Output Writing --- + # write.table is robust for vectors, matrices, and data.frames + write.table(result, file = output_file, sep = "\\t", quote = FALSE, col.names = NA) + """ + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "matrix_op.R" + with open(r_script_path, "w") as f: + f.write(r_script) + + output_path = Path.cwd() / output_filename + + # --- Command Construction --- + cmd = [ + "Rscript", + str(r_script_path), + str(input_matrix), + str(output_path), + operation, + str(na_rm).upper(), + "\\t" if delimiter == "\t" else ",", + str(has_header).upper(), + str(has_rownames).upper(), + probs if probs else "NULL", + str(weights) if weights else "NULL", + ties_method, + str(value) if value is not None else "NULL", + str(lag), + str(differences), + str(which) if which is not None else "NULL", + str(preserve_shape).upper() + ] + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(map(str, cmd)), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "R script execution failed." + } + except FileNotFoundError: + return { + "command_executed": " ".join(map(str, cmd)), + "stdout": "", + "stderr": "Rscript command not found. Please ensure R is installed and in your PATH.", + "output_files": [], + "error": "Dependency not found." + } + + # --- Structured Result Return --- + return { + "command_executed": " ".join(map(str, cmd)), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..533ce6c8dfe9ec137daa14b8c2c5254ba33604c9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_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-matrixgenerics/app/bioconductor-matrixgenerics_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_matrixgenerics' + + +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/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7bd9323b314d29fa4bdf3a49442b1ef41fe55464 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-matrixgenerics: + build: . + image: mcp-bioconductor-matrixgenerics:latest + container_name: mcp-bioconductor-matrixgenerics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-matrixgenerics + 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/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..55a5066ba648a0a9d45d2f77c2a3fd79a0e2230f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-matrixgenerics + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-matrixgenerics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-merfishdata/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7823c41076fc0b5b374ed7430f528d63e59978fe --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/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-merfishdata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-merfishdata -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-merfishdata_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-merfishdata_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-merfishdata_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_server.py b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..afb2536f7ab90d8faace358417d89ab76bb4b9da --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_server.py @@ -0,0 +1,240 @@ +import subprocess +import json +from pathlib import Path +from typing import List, Dict, Optional, Union +import tempfile + +# No need to import mcp as per instructions + +def _run_r_script(r_code: str, output_dir: Optional[Path] = None) -> Dict[str, Union[str, List[Path]]]: + """ + Helper function to execute R code using Rscript. + + Args: + r_code: The R script code to execute. + output_dir: An optional directory where R might write files. If provided, + it ensures the directory exists. + + Returns: + A dictionary containing execution details, stdout, stderr, and any errors. + """ + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + + # Use a temporary file for the R script to handle potentially long R code + # and ensure proper execution context. + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as temp_r_script: + temp_r_script.write(r_code) + 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, + encoding='utf-8' + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [], # This helper doesn't track specific output files, main functions will + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Rscript execution failed with exit code {e.returncode}", + } + 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_bioconductor_merfishdata' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def list_merfish_datasets() -> Dict[str, Union[str, List[Dict[str, str]]]]: + """ + Lists available MERFISH datasets from the Bioconductor ExperimentHub. + + This function queries the ExperimentHub for datasets provided by the + MerfishData package and returns their metadata, including unique + ExperimentHub IDs (eh_id). + + Returns: + A dictionary containing: + - 'command_executed': The Rscript command executed. + - 'stdout': Standard output from the R script. + - 'stderr': Standard error from the R script. + - 'datasets': A list of dictionaries, where each dictionary represents + a dataset with its metadata (e.g., title, description, eh_id). + - 'error': (Optional) Error message if the R script fails. + """ + r_script_code = """ + options(timeout = 600) # Increase timeout for BiocManager::install and ExperimentHub downloads + # Install BiocManager if not present + if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos = "https://cloud.r-project.org") + # Install MerfishData and ExperimentHub if not present + if (!require("MerfishData", quietly = TRUE)) BiocManager::install("MerfishData", update = FALSE, ask = FALSE) + if (!require("ExperimentHub", quietly = TRUE)) BiocManager::install("ExperimentHub", update = FALSE, ask = FALSE) + # Install jsonlite for JSON output + if (!require("jsonlite", quietly = TRUE)) install.packages("jsonlite", repos = "https://cloud.r-project.org", update = FALSE, ask = FALSE) + + library(MerfishData) + library(ExperimentHub) + library(jsonlite) + + eh <- ExperimentHub() + merfish_resources <- query(eh, "MerfishData") + + # Extract metadata including the unique ExperimentHub ID (rownames) + metadata_df <- as.data.frame(mcols(merfish_resources)) + metadata_df$eh_id <- rownames(merfish_resources) # Add ID as a column + + # Convert to JSON and print to stdout + cat(toJSON(metadata_df, pretty = TRUE)) + """ + + result = _run_r_script(r_script_code) + + if "error" in result: + return result + + try: + datasets_json = result["stdout"] + # Attempt to parse JSON, but handle cases where R might print warnings/messages before JSON + # Find the first and last curly brace to isolate the JSON array/object + json_start = datasets_json.find('[') + json_end = datasets_json.rfind(']') + if json_start == -1 or json_end == -1: # If it's a single object, it might be { ... } + json_start = datasets_json.find('{') + json_end = datasets_json.rfind('}') + + if json_start != -1 and json_end != -1 and json_end > json_start: + clean_json_str = datasets_json[json_start : json_end + 1] + datasets_list = json.loads(clean_json_str) + else: + # If no valid JSON found, return raw stdout and an error + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "datasets": [], + "error": "Could not parse JSON output from R script. Raw stdout returned.", + } + + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "datasets": datasets_list, + } + except json.JSONDecodeError as e: + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "datasets": [], + "error": f"Failed to decode JSON from R script stdout: {e}. Raw stdout: {result['stdout']}", + } + + +@mcp.tool() +def get_merfish_dataset( + dataset_id: str, + output_dir: Path, + output_filename: Optional[str] = None, +) -> Dict[str, Union[str, List[Path]]]: + """ + Downloads a specific MERFISH dataset from the Bioconductor ExperimentHub. + + The dataset is identified by its unique ExperimentHub ID (eh_id), which + can be obtained using the `list_merfish_datasets` function. The retrieved + R object (typically a SpatialExperiment or SingleCellExperiment) is saved + as an R Data Serialization (RDS) file. + + Args: + dataset_id: The unique ExperimentHub ID (eh_id) of the MERFISH dataset to download. + This ID can be found using `list_merfish_datasets`. + output_dir: The directory where the downloaded .rds file will be saved. + This directory will be created if it does not exist. + output_filename: Optional. The name of the output .rds file. If not provided, + it defaults to '{dataset_id}.rds'. + + Returns: + A dictionary containing: + - 'command_executed': The Rscript command executed. + - 'stdout': Standard output from the R script. + - 'stderr': Standard error from the R script. + - 'output_files': A list containing the path to the downloaded .rds file. + - 'error': (Optional) Error message if the R script fails. + """ + # Input validation + if not dataset_id: + raise ValueError("dataset_id cannot be empty.") + + output_dir.mkdir(parents=True, exist_ok=True) + + if output_filename: + if not output_filename.endswith(".rds"): + output_filename += ".rds" + output_file_path = output_dir / output_filename + else: + output_file_path = output_dir / f"{dataset_id}.rds" + + r_script_code = f""" + options(timeout = 600) # Increase timeout for BiocManager::install and ExperimentHub downloads + # Install BiocManager if not present + if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos = "https://cloud.r-project.org") + # Install MerfishData and ExperimentHub if not present + if (!require("MerfishData", quietly = TRUE)) BiocManager::install("MerfishData", update = FALSE, ask = FALSE) + if (!require("ExperimentHub", quietly = TRUE)) BiocManager::install("ExperimentHub", update = FALSE, ask = FALSE) + + library(MerfishData) + library(ExperimentHub) + + dataset_id <- "{dataset_id}" + output_file <- "{output_file_path.as_posix()}" + + eh <- ExperimentHub() + + # Query for MerfishData resources specifically + merfish_resources <- query(eh, "MerfishData") + + # Check if the provided ID exists among MerfishData resources + if (!dataset_id %in% rownames(merfish_resources)) {{ + stop(paste0("Dataset ID '", dataset_id, "' not found among MerfishData resources in ExperimentHub.")) + }} + + # Retrieve the dataset + dataset_object <- eh[[dataset_id]] + + # Save the R object as an RDS file + saveRDS(dataset_object, file = output_file) + cat(paste0("Dataset '", dataset_id, "' successfully saved to ", output_file, "\\n")) + """ + + result = _run_r_script(r_script_code, output_dir=output_dir) + + if "error" in result: + return result + + # Add the output file to the list of output_files + result["output_files"].append(output_file_path) + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ab4b945efcf95a35fde30ba225cd102f07602026 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_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-merfishdata/app/bioconductor-merfishdata_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_merfishdata' + + +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/Biomni/mcp_generated/mcp_bioconductor-merfishdata/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-merfishdata/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..028f4ed20287df19fcee8ba50d198b3371380819 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-merfishdata: + build: . + image: mcp-bioconductor-merfishdata:latest + container_name: mcp-bioconductor-merfishdata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-merfishdata + 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/Biomni/mcp_generated/mcp_bioconductor-merfishdata/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1b4733c5a9506552925d4759b4bdf34f3bd8cff2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-merfishdata + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-merfishdata/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-merfishdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3610c0c4ce00dcc7bd542c046f85f7b176810e64 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/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-metabolomicsworkbenchr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-metabolomicsworkbenchr -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-metabolomicsworkbenchr_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-metabolomicsworkbenchr_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-metabolomicsworkbenchr_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..df5e345233e617e0087595bfa61be17692c96fe6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py @@ -0,0 +1,125 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# The user's prompt mentions `bioconductor-metabolomicsworkbenchr`, which is an R package. +# The provided help output is for `Rscript`, the command-line tool used to execute R scripts. +# This MCP tool correctly wraps the `Rscript` executable, which can then be used to run +# scripts that utilize packages like `bioconductor-metabolomicsworkbenchr`. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_metabolomicsworkbenchr' +mcp = FastMCP(SERVER_NAME) + +@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 the `Rscript` executable, allowing for the execution + of R code from a file or directly as string expressions. It mirrors the command-line + options of Rscript and can be used to run any R script, including those that use + Bioconductor packages like metabolomicsworkbenchr. + + Args: + script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute. Use instead of 'script_file'. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, enables verbose output from Rscript (--verbose). + default_packages: A comma-separated string of R package names to be loaded by default (--default-packages). + save: If True, the R workspace will be saved at the end of the session (--save). Ignored if 'vanilla' is True. + no_environ: If True, site and user environment files will not be read (--no-environ). Ignored if 'vanilla' is True. + no_site_file: If True, the site-wide Rprofile will not be read (--no-site-file). Ignored if 'vanilla' is True. + no_init_file: If True, the user's R profile will not be read (--no-init-file). Ignored if 'vanilla' is True. + restore: If True, previously saved objects will be restored at startup (--restore). Ignored if 'vanilla' is True. + vanilla: If True, provides a "clean" R session by combining --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ. If set, it overrides the individual flags it controls. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Note: `output_files` will be empty as this wrapper cannot determine what files the user's R script might generate. + """ + # --- 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}") + + # --- Command Construction --- + cmd = ["Rscript"] + + 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]) + + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + if script_file: + cmd.append(str(script_file)) + + if script_args: + cmd.extend(script_args) + + # --- Subprocess Execution --- + 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, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("Rscript executable not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error response + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..425c84ae588fe2882428d835b4a8969535d6738e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_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-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_metabolomicsworkbenchr' + + +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/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c2a2cdedf09310946c0907818a3eeadb20437bc4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-metabolomicsworkbenchr: + build: . + image: mcp-bioconductor-metabolomicsworkbenchr:latest + container_name: mcp-bioconductor-metabolomicsworkbenchr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-metabolomicsworkbenchr + 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/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9bde03c685868257823a92c9790c2ff89f26edee --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-metabolomicsworkbenchr + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-metapod/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-metapod/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5c6a2b29f342a8ea28bc8a1d8f2327a8ed77fc1c --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py b/Biomni/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f48df88b46b0abeb0c407bf5d0c468cb8ec8f8b --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-metapod/app/bioconductor-metapod_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..60ddfb3bc20c420d452b8c0ccffe8d3dd6af87cf --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-metapod/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-metapod/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-metapod/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-metapod/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-metapod/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d1c5940ca3366fe6942d00fdc1c76e36315ebb66 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-metapod/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-metapod/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..153d07b003e599338e3741bf7537f22006d08e89 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-metapod/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-metapod/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-metapod/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-mia/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-mia/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..550ada1f834d0528e040f3da5aab4014267c9673 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mia/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-mia via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mia -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-mia_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-mia_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-mia_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mia/app/bioconductor-mia_server.py b/Biomni/mcp_generated/mcp_bioconductor-mia/app/bioconductor-mia_server.py new file mode 100644 index 0000000000000000000000000000000000000000..295119082c27d4abec7c7cee95d205a17b394a19 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mia/app/bioconductor-mia_server.py @@ -0,0 +1,134 @@ +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_mia' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_mia_r_script( + r_script_content: str, + input_rds_path: Optional[Path] = None, + output_rds_path: Optional[Path] = None, + working_directory: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes an R script that utilizes the bioconductor-mia package for microbiome analysis. + + This tool provides a generic interface to run arbitrary R code that is expected + to use the 'mia' Bioconductor package. It allows for loading an input R data + object (e.g., a SummarizedExperiment saved as .rds) and saving an output R data + object. + + Args: + r_script_content: A string containing the R script to be executed. + The script should assume 'mia' is loaded. + If `input_rds_path` is provided, the loaded object will + be available as `input_data`. + If `output_rds_path` is provided, the script should + assign the object to be saved to a variable named + `output_data`. + input_rds_path: Optional path to an R data object (.rds file) to be loaded + into the R environment before executing the script. + The object will be loaded as 'input_data'. + output_rds_path: Optional path where the R script should save an R data + object (e.g., a SummarizedExperiment) using saveRDS(). + The R script must assign the object to be saved to a + variable named 'output_data'. + working_directory: Optional path to a directory where the R script will be + executed. This can be useful for scripts that use + relative paths for additional input/output files. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any + generated output files. + """ + if not r_script_content.strip(): + raise ValueError("r_script_content cannot be empty.") + + output_files: List[Path] = [] + + # Validate input_rds_path if provided + if input_rds_path: + if not input_rds_path.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds_path}") + if not input_rds_path.suffix == ".rds": + raise ValueError(f"Input RDS file must have a '.rds' extension: {input_rds_path}") + + # Prepare output_rds_path if provided + if output_rds_path: + output_rds_path = output_rds_path.resolve() # Ensure absolute path + output_rds_path.parent.mkdir(parents=True, exist_ok=True) # Create parent dirs + if not output_rds_path.suffix == ".rds": + raise ValueError(f"Output RDS file must have a '.rds' extension: {output_rds_path}") + output_files.append(output_rds_path) + + # Create a temporary directory for the R script + with tempfile.TemporaryDirectory() as tmpdir: + tmpdir_path = Path(tmpdir) + + # Determine the actual working directory for the R process + actual_working_dir = working_directory if working_directory else tmpdir_path + actual_working_dir.mkdir(parents=True, exist_ok=True) # Ensure it exists + + r_script_file = tmpdir_path / "mia_script.R" + + # Construct the full R script content + full_r_script_lines = [ + "library(mia)", + "options(warn=-1)", # Suppress warnings for cleaner output + ] + + if input_rds_path: + full_r_script_lines.append(f"input_data <- readRDS('{input_rds_path.resolve()}')") + + full_r_script_lines.append(r_script_content) + + if output_rds_path: + # The user's script is expected to assign the result to 'output_data' + # We will then save 'output_data' to the specified path. + full_r_script_lines.append(f"if (exists('output_data')) {{ saveRDS(output_data, '{output_rds_path}') }} else {{ message('Warning: output_data variable not found, no RDS file saved.') }}") + + r_script_file.write_text("\n".join(full_r_script_lines)) + + command = ["Rscript", str(r_script_file)] + + try: + process = subprocess.run( + command, + cwd=actual_working_dir, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: Rscript command not found. Is R installed and in PATH?", + "error": "Rscript not found", + "output_files": [], + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(p) for p in output_files], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-mia/app/bioconductor-mia_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-mia/app/bioconductor-mia_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..35f8dc22b4cbd32a50ca2f8a2d09df49fcb19b72 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mia/app/bioconductor-mia_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-mia/app/bioconductor-mia_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_mia' + + +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/Biomni/mcp_generated/mcp_bioconductor-mia/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mia/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mia/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-mia/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-mia/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..448e04866675ab483f33e61b5ce5db50c0d53b89 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mia/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mia: + build: . + image: mcp-bioconductor-mia:latest + container_name: mcp-bioconductor-mia + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mia + 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/Biomni/mcp_generated/mcp_bioconductor-mia/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-mia/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9c6e488272f2e53a2ddb32b7b1d99e6cb5ad0ac0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mia/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mia + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mia/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mia/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mia/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ccec41ddd0d80bd47367f90dfd32979fcab14fc9 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py b/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fae47e1184e790b367ff82c8ea0bccd7e8786cd4 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..010e51c97c310dae596632accb9878aef25bdb4f --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8391b5a42b71f56f0fbadd46a4ebf46bb3be01b --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..915487a01bd02c680dcac5ec49ea08b92d891c21 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-moleculeexperiment/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-mosim/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-mosim/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4e5ae9b6e22413ed1bf33d860c1e348d015a1f58 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mosim/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-mosim via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mosim -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-mosim_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-mosim_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-mosim_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mosim/app/bioconductor-mosim_server.py b/Biomni/mcp_generated/mcp_bioconductor-mosim/app/bioconductor-mosim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..156060354a7ef7d6f49126918ba7c0823a930471 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mosim/app/bioconductor-mosim_server.py @@ -0,0 +1,215 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Dict, Any +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +log = logging.getLogger(__name__) + +# Per the instructions, the mcp decorator is assumed to be available in the execution environment. +# We define a placeholder here for standalone validation. +class mcp: + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_mosim' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def start_simulation( + sim_name: str, + omics_list: List[str], + omics_distributions: List[str], + n_samples: int, + n_features: List[int], + omics_network_file: Path, + prop_causal: float, + prop_shared_causal: float, + output_path: Path, + seed: int = 123, + save_results: bool = True, + verbose: bool = True, +) -> Dict[str, Any]: + """ + Runs a multi-omics simulation using the bioconductor-mosim R package. + + This tool acts as a wrapper around the `mosim::startSimulation` R function. + It requires R, the Rscript executable in the system's PATH, and the + Bioconductor 'mosim' package to be installed in the R environment. + + Args: + sim_name: Name for the simulation. A directory with this name will be created in the output_path. + omics_list: A list of omics types to be simulated (e.g., ["RNA", "protein"]). + omics_distributions: A list of distributions for each omic (e.g., ["NB", "normal"]). Must be the same length as omics_list. + n_samples: The number of samples to simulate. Must be a positive integer. + n_features: A list of the number of features for each omic. Must be the same length as omics_list. + omics_network_file: Path to a CSV file representing the adjacency matrix of the omics network. The first column should contain feature names (row names). + prop_causal: The proportion of causal features. Must be between 0.0 and 1.0. + prop_shared_causal: The proportion of causal features that are shared among omics. Must be between 0.0 and 1.0. + output_path: The directory where the simulation results will be saved. + seed: An integer to be used as the random seed. + save_results: If True, the simulation results will be saved to files. + verbose: If True, the simulation progress will be printed to standard output. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not sim_name: + raise ValueError("sim_name cannot be empty.") + if not omics_list: + raise ValueError("omics_list cannot be empty.") + if len(omics_list) != len(omics_distributions): + raise ValueError("omics_list and omics_distributions must have the same length.") + if len(omics_list) != len(n_features): + raise ValueError("omics_list and n_features must have the same length.") + if n_samples <= 0: + raise ValueError("n_samples must be a positive integer.") + for n in n_features: + if n <= 0: + raise ValueError("All values in n_features must be positive integers.") + if not (0.0 <= prop_causal <= 1.0): + raise ValueError("prop_causal must be between 0.0 and 1.0.") + if not (0.0 <= prop_shared_causal <= 1.0): + raise ValueError("prop_shared_causal must be between 0.0 and 1.0.") + + if not omics_network_file.is_file(): + raise FileNotFoundError(f"Omics network file not found at: {omics_network_file}") + + # --- File Path Handling --- + try: + output_path.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Could not create output directory {output_path}: {e}") + + # --- R Script Generation --- + # Convert Python lists to R vector strings, e.g., ["a", "b"] -> 'c("a", "b")' + r_omics_list = 'c(' + ', '.join(f'"{o}"' for o in omics_list) + ')' + r_omics_distributions = 'c(' + ', '.join(f'"{d}"' for d in omics_distributions) + ')' + r_n_features = 'c(' + ', '.join(map(str, n_features)) + ')' + + # Convert Python bool to R TRUE/FALSE + r_save_results = "TRUE" if save_results else "FALSE" + r_verbose = "TRUE" if verbose else "FALSE" + + r_script_content = f""" + # Check if mosim is installed, if not, stop with an error + if (!requireNamespace("mosim", quietly = TRUE)) {{ + stop("The 'mosim' package is not installed. Please install it from Bioconductor.", call. = FALSE) + }} + library(mosim) + + # --- Parameters --- + sim_name_val <- "{sim_name}" + omics_list_val <- {r_omics_list} + omics_distributions_val <- {r_omics_distributions} + n_samples_val <- {n_samples} + n_features_val <- {r_n_features} + omics_network_path <- "{omics_network_file.resolve()}" + prop_causal_val <- {prop_causal} + prop_shared_causal_val <- {prop_shared_causal} + output_path_val <- "{output_path.resolve()}" + seed_val <- {seed} + save_results_val <- {r_save_results} + verbose_val <- {r_verbose} + + # --- Data Loading --- + # Assuming the network file is a CSV with a header and row names in the first column + tryCatch({{ + omics_network_df <- read.csv(omics_network_path, header=TRUE, row.names=1, check.names=FALSE) + }}, error = function(e) {{ + stop(paste("Failed to read omics network file:", e$message), call. = FALSE) + }}) + + # --- Simulation --- + set.seed(seed_val) + + cat("Starting mosim simulation...\\n") + + tryCatch({{ + simulation_results <- mosim::startSimulation( + sim_name = sim_name_val, + omics_list = omics_list_val, + omics_distributions = omics_distributions_val, + n_samples = n_samples_val, + n_features = n_features_val, + omics_network = omics_network_df, + prop_causal = prop_causal_val, + prop_shared_causal = prop_shared_causal_val, + output_path = output_path_val, + seed = seed_val, + save_results = save_results_val, + verbose = verbose_val + ) + }}, error = function(e) {{ + stop(paste("Error during mosim::startSimulation:", e$message), call. = FALSE) + }}) + + cat("Simulation completed successfully.\\n") + """ + + # --- Subprocess Execution --- + command = [] + r_script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=".") as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + log.info(f"Executing command: {' '.join(command)}") + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout_str = process.stdout + stderr_str = process.stderr + + # --- Collect Output Files --- + output_files = [] + if save_results: + simulation_output_dir = output_path / sim_name + if simulation_output_dir.is_dir(): + output_files = [str(f.resolve()) for f in simulation_output_dir.glob('**/*') if f.is_file()] + else: + log.warning(f"Expected output directory '{simulation_output_dir}' was not created by mosim.") + stderr_str += f"\n[MCP WARNING] Expected output directory '{simulation_output_dir}' was not created by mosim." + + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files + } + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH.") + except subprocess.CalledProcessError as e: + log.error(f"R script execution failed with return code {e.returncode}") + log.error(f"STDOUT: {e.stdout}") + log.error(f"STDERR: {e.stderr}") + # Return a structured error response + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"R script execution failed with return code {e.returncode}. Check stderr for details from R." + } + finally: + # Clean up the temporary R script + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-mosim/app/bioconductor-mosim_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-mosim/app/bioconductor-mosim_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8bce6b9aee0af12126b8c760efa787cfe3f02a13 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mosim/app/bioconductor-mosim_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-mosim/app/bioconductor-mosim_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_mosim' + + +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/Biomni/mcp_generated/mcp_bioconductor-mosim/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-mosim/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a63563333da7f44cdd4997ed3050fff8fb05f7a7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mosim/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mosim: + build: . + image: mcp-bioconductor-mosim:latest + container_name: mcp-bioconductor-mosim + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mosim + 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/Biomni/mcp_generated/mcp_bioconductor-mosim/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-mosim/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d19ee09029b7f73facf98be195e04fba8c25a83 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mosim/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mosim + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mosim/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mosim/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mosim/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d6eb58b034eb3ce33b7c5c8e61acab1a8d8f5cfc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/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-mousegastrulationdata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mousegastrulationdata -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-mousegastrulationdata_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-mousegastrulationdata_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-mousegastrulationdata_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_server.py b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6e2f59ff20fda424193fd4b3d00d07cac57005c4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_server.py @@ -0,0 +1,244 @@ +import subprocess +from pathlib import Path +from typing import Literal, Dict, List, Optional +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_mousegastrulationdata' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def mouse_gastrulation_data( + output_rds_path: Path, + dataset_type: Literal["chimera", "gastrulation", "seqFISH", "mesoderm", "pdx"] = "gastrulation", + use_ensembl_ids: bool = False, + cache_data: bool = True, +) -> Dict: + """ + Loads single-cell datasets from the MouseGastrulationData Bioconductor package. + + This tool wraps the main `MouseGastrulationData()` function from the R package. + It downloads and caches specified datasets from ExperimentHub and saves the + resulting SingleCellExperiment or SpatialExperiment object as an RDS file. + Requires R and the `bioconductor-mousegastrulationdata` package to be installed. + + Args: + output_rds_path: Path to save the output RDS file containing the data object. + dataset_type: The type of dataset to load. Defaults to "gastrulation". + use_ensembl_ids: If True, use Ensembl IDs for gene identifiers. Defaults to False (uses gene symbols). + cache_data: If True, cache the downloaded data locally using ExperimentHub. Defaults to True. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + valid_types = ["chimera", "gastrulation", "seqFISH", "mesoderm", "pdx"] + if dataset_type not in valid_types: + raise ValueError(f"dataset_type must be one of {valid_types}, but got '{dataset_type}'") + + # R booleans need to be uppercase + r_ensembl = "TRUE" if use_ensembl_ids else "FALSE" + r_cache = "TRUE" if cache_data else "FALSE" + + # Construct the R script + r_script = f""" + # Suppress startup messages for cleaner output + suppressPackageStartupMessages(library(MouseGastrulationData)) + + # Load the data + sce <- MouseGastrulationData( + type = "{dataset_type}", + ensembl = {r_ensembl}, + location = {r_cache} + ) + + # Save the object to the specified file + saveRDS(sce, file = "{str(output_rds_path)}") + + # Print a success message to stdout + cat("Successfully loaded dataset '{dataset_type}' and saved to {str(output_rds_path)}\\n") + """ + + command = ["Rscript", "-e", r_script] + command_str = " ".join(command) + logger.info(f"Executing command: {command_str}") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + logger.error(f"R script 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": [], + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds_path)], + } + + +@mcp.tool() +def atlas_sample_metadata(output_csv_path: Path) -> Dict: + """ + Retrieves the sample metadata data frame from the MouseGastrulationData package. + + This tool wraps the `AtlasSampleMetadata()` function and saves the resulting + data frame as a CSV file. Requires R and the `bioconductor-mousegastrulationdata` + package to be installed. + + Args: + output_csv_path: Path to save the output CSV file containing the metadata. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Construct the R script + r_script = f""" + suppressPackageStartupMessages(library(MouseGastrulationData)) + + # Load the metadata + meta <- AtlasSampleMetadata() + + # Save the data frame to a CSV file + write.csv(meta, file = "{str(output_csv_path)}", row.names = FALSE, quote = TRUE) + + cat("Successfully retrieved sample metadata and saved to {str(output_csv_path)}\\n") + """ + + command = ["Rscript", "-e", r_script] + command_str = " ".join(command) + logger.info(f"Executing command: {command_str}") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + logger.error(f"R script 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": [], + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_csv_path)], + } + + +@mcp.tool() +def embryo_color_map(output_csv_path: Path) -> Dict: + """ + Retrieves the color map for cell types in the mouse gastrulation atlas. + + This tool wraps the `EmbryoColorMap()` function. It converts the named + character vector of colors into a data frame and saves it as a CSV file. + Requires R and the `bioconductor-mousegastrulationdata` package to be installed. + + Args: + output_csv_path: Path to save the output CSV file containing the color map. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Construct the R script + r_script = f""" + suppressPackageStartupMessages(library(MouseGastrulationData)) + + # Load the color map + cmap <- EmbryoColorMap() + + # Convert the named vector to a data frame for easy saving + cmap_df <- data.frame( + cell_type = names(cmap), + color_hex = as.character(cmap), + stringsAsFactors = FALSE + ) + + # Save the data frame to a CSV file + write.csv(cmap_df, file = "{str(output_csv_path)}", row.names = FALSE, quote = TRUE) + + cat("Successfully retrieved embryo color map and saved to {str(output_csv_path)}\\n") + """ + + command = ["Rscript", "-e", r_script] + command_str = " ".join(command) + logger.info(f"Executing command: {command_str}") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + logger.error(f"R script 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": [], + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_csv_path)], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..22afbbc664a0645aceee3c4b82de76e02502d65b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_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-mousegastrulationdata/app/bioconductor-mousegastrulationdata_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_mousegastrulationdata' + + +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/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..12f8aa4ebdf7d15c7c3e7ca3d4b400cde0a43c59 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mousegastrulationdata: + build: . + image: mcp-bioconductor-mousegastrulationdata:latest + container_name: mcp-bioconductor-mousegastrulationdata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mousegastrulationdata + 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/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e38088132dfda41eea863df792b826fb2cbe2368 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mousegastrulationdata + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mousegastrulationdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-mspurity/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-mspurity/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b693edfda5ebe7e256e6e03048b2b6fb76e37ff7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mspurity/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-mspurity via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mspurity -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-mspurity_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-mspurity_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-mspurity_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mspurity/app/bioconductor-mspurity_server.py b/Biomni/mcp_generated/mcp_bioconductor-mspurity/app/bioconductor-mspurity_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ba6ae1fb059650bda4d5657976b0d3056b992fc0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mspurity/app/bioconductor-mspurity_server.py @@ -0,0 +1,320 @@ +import subprocess +import os +import tempfile +from pathlib import Path +from typing import Optional, List + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_mspurity' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def mspurity_purity_a( + ms_files: List[str], + output_rds: str, + cores: int = 1, + mz_purity_limit: float = 0.0, + iw_low: float = -0.5, + iw_high: float = 0.5, + nearest: bool = True, + v: bool = True, + offsets: bool = False +): + """ + Assess precursor purity for LC-MS/MS data. Calculates the percentage of the + intensity in the isolation window that is attributed to the precursor ion. + + Args: + ms_files: List of paths to LC-MS/MS files (mzML, mzXML). + output_rds: Path to save the resulting purityA object as an RDS file. + cores: Number of CPU cores for parallel processing. + mz_purity_limit: Purity threshold for filtering. + iw_low: Lower offset for isolation window (e.g., -0.5). + iw_high: Upper offset for isolation window (e.g., 0.5). + nearest: Whether to use the nearest scan for purity calculation. + v: Verbose output. + offsets: Whether to use isolation window offsets from the file metadata. + """ + for f in ms_files: + if not Path(f).exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + out_path = Path(output_rds) + out_path.parent.mkdir(parents=True, exist_ok=True) + + ms_files_r = ", ".join([f'"{f}"' for f in ms_files]) + r_script = f""" + library(msPurity) + pa <- purityA(fileList = c({ms_files_r}), + cores = {cores}, + mz_purity_limit = {mz_purity_limit}, + iw_low = {iw_low}, + iw_high = {iw_high}, + nearest = {"TRUE" if nearest else "FALSE"}, + v = {"TRUE" if v else "FALSE"}, + offsets = {"TRUE" if offsets else "FALSE"}) + saveRDS(pa, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + 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(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_purity_x( + ms_files: List[str], + output_rds: str, + cores: int = 1, + mz_purity_limit: float = 0.0, + v: bool = True +): + """ + Assess precursor purity for Direct Infusion (DI-MS/MS) data. + + Args: + ms_files: List of paths to DI-MS/MS files. + output_rds: Path to save the resulting purityX object as an RDS file. + cores: Number of CPU cores. + mz_purity_limit: Purity threshold. + v: Verbose output. + """ + for f in ms_files: + if not Path(f).exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + ms_files_r = ", ".join([f'"{f}"' for f in ms_files]) + r_script = f""" + library(msPurity) + px <- purityX(fileList = c({ms_files_r}), + cores = {cores}, + mz_purity_limit = {mz_purity_limit}, + v = {"TRUE" if v else "FALSE"}) + saveRDS(px, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + 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": [output_rds] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_average_intensities( + pa_rds: str, + output_rds: str, + avg_mz_err: float = 0.005, + avg_rt_err: float = 10.0, + v: bool = True +): + """ + Average the intensities of MS/MS spectra across scans within a purityA object. + + Args: + pa_rds: Path to the input purityA RDS file. + output_rds: Path to save the updated purityA object. + avg_mz_err: m/z error for averaging. + avg_rt_err: Retention time error for averaging (seconds). + v: Verbose output. + """ + if not Path(pa_rds).exists(): + raise FileNotFoundError(f"Input RDS file not found: {pa_rds}") + + r_script = f""" + library(msPurity) + pa <- readRDS("{pa_rds}") + pa <- averageIntensities(pa, avg_mz_err = {avg_mz_err}, avg_rt_err = {avg_rt_err}, v = {"TRUE" if v else "FALSE"}) + saveRDS(pa, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_create_database( + pa_rds: str, + db_path: str, + xset_rds: Optional[str] = None, + v: bool = True +): + """ + Create a SQLite database from a purityA object, optionally linking with XCMS results. + + Args: + pa_rds: Path to the input purityA RDS file. + db_path: Path to the output SQLite database file. + xset_rds: Optional path to an XCMS xset or XcmsExperiment RDS file. + v: Verbose output. + """ + if not Path(pa_rds).exists(): + raise FileNotFoundError(f"Input RDS file not found: {pa_rds}") + + xset_code = f'xset <- readRDS("{xset_rds}")' if xset_rds else "xset <- NULL" + + r_script = f""" + library(msPurity) + pa <- readRDS("{pa_rds}") + {xset_code} + createDatabase(pa, xset = xset, dbName = "{db_path}", v = {"TRUE" if v else "FALSE"}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "output_files": [db_path] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_spectral_matching( + pa_rds: str, + output_rds: str, + lib_path: str, + ms_err: float = 0.01, + v: bool = True +): + """ + Perform spectral matching against a library for the MS/MS spectra in a purityA object. + + Args: + pa_rds: Path to the input purityA RDS file. + output_rds: Path to save the purityA object with matching results. + lib_path: Path to the spectral library (RDS or SQLite). + ms_err: m/z error for matching. + v: Verbose output. + """ + if not Path(pa_rds).exists(): + raise FileNotFoundError(f"Input RDS file not found: {pa_rds}") + if not Path(lib_path).exists(): + raise FileNotFoundError(f"Library file not found: {lib_path}") + + r_script = f""" + library(msPurity) + pa <- readRDS("{pa_rds}") + pa <- spectralMatching(pa, lib_path = "{lib_path}", ms_err = {ms_err}, v = {"TRUE" if v else "FALSE"}) + saveRDS(pa, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_filter_frag( + pa_rds: str, + output_rds: str, + min_int: float = 0.0, + v: bool = True +): + """ + Filter fragmentation spectra based on intensity or other criteria. + + Args: + pa_rds: Path to the input purityA RDS file. + output_rds: Path to save the filtered purityA object. + min_int: Minimum intensity threshold for peaks. + v: Verbose output. + """ + if not Path(pa_rds).exists(): + raise FileNotFoundError(f"Input RDS file not found: {pa_rds}") + + r_script = f""" + library(msPurity) + pa <- readRDS("{pa_rds}") + pa <- filterFrag(pa, min_int = {min_int}, v = {"TRUE" if v else "FALSE"}) + saveRDS(pa, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-mspurity/app/bioconductor-mspurity_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-mspurity/app/bioconductor-mspurity_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0a5ef92d13f4eaaead01a96482316b58c4f2dfc7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mspurity/app/bioconductor-mspurity_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-mspurity/app/bioconductor-mspurity_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_mspurity' + + +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/Biomni/mcp_generated/mcp_bioconductor-mspurity/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mspurity/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mspurity/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-mspurity/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-mspurity/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c5b434c3bcdfeca344c322cc39bdf54a145647cf --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mspurity/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mspurity: + build: . + image: mcp-bioconductor-mspurity:latest + container_name: mcp-bioconductor-mspurity + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mspurity + 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/Biomni/mcp_generated/mcp_bioconductor-mspurity/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-mspurity/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0bac186c238387cb25135baf8c703b4d5e9bef8a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mspurity/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mspurity + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-mspurity/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mspurity/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mspurity/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5fd3bc9dcf3ea6f60926861e1e9b59a8befef3a3 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py b/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b9830a23f6a933e3f6f74ec55f738ab7665744 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d012e982d103c48d6a439df5204eb86a64264358 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..01a8d206024f451005a92d57776aec5d0da06aca --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab0c20e1007cb60d742fd97346f24742a730e275 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-multiassayexperiment/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-multtest/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-multtest/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..50b12bc8047f8991312c0813274193fff3435c15 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-multtest/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-multtest via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-multtest -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-multtest_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-multtest_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-multtest_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py b/Biomni/mcp_generated/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cd1c7a7ebc81b5bbb403fa2a32ae0930805c557a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py @@ -0,0 +1,238 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import List, Optional, Literal + +# Configure logging +logging.basicConfig(level=logging.INFO) + +# Define allowed choices for parameters based on the multtest R package documentation. +MTP_TEST_CHOICES = Literal[ + "t.onesamp", "t.twosamp.equalvar", "t.twosamp.unequalvar", + "f", "pairt", "blockf" +] +MTP_ALTERNATIVE_CHOICES = Literal["two.sided", "less", "greater"] +MTP_TYPEONE_CHOICES = Literal["fwer", "gfwer", "tppfp", "fdr"] +MTP_NULLDIST_CHOICES = Literal["boot.cs", "boot.ctr", "perm"] +MTP_METHOD_CHOICES = Literal["ss.maxT", "ss.minP", "sd.maxT", "sd.minP"] + +ADJP_PROCEDURE_CHOICES = Literal[ + "Bonferroni", "Holm", "Hochberg", "SidakSS", "SidakSD", + "BH", "BY", "ABH", "TSBH" +] + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_multtest' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def multtest_mtp( + data_file: Path, + class_labels_file: Path, + output_prefix: str, + test: MTP_TEST_CHOICES = "t.twosamp.equalvar", + alternative: MTP_ALTERNATIVE_CHOICES = "two.sided", + typeone: MTP_TYPEONE_CHOICES = "fwer", + alpha: float = 0.05, + nulldist: MTP_NULLDIST_CHOICES = "boot.cs", + b: int = 10000, + method: MTP_METHOD_CHOICES = "ss.maxT", + seed: Optional[int] = None, +) -> dict: + """ + Performs a Multiple Testing Procedure (MTP) using the bioconductor-multtest package. + + This function is a wrapper for the main `MTP` function in the `multtest` R package. + It takes a data matrix and class labels to perform hypothesis testing, controlling + for a specified type of error rate (e.g., FWER, FDR). + + Args: + data_file: Path to the input data file (CSV format). Rows should be features/genes, + and columns should be samples. A header with sample names and a column + with feature names are expected. + class_labels_file: Path to a single-column CSV file containing class labels for + the samples. The order must match the columns in data_file. + No header is expected. + output_prefix: Prefix for the output files (e.g., 'my_analysis'). + test: The statistical test to use. + alternative: Specifies the alternative hypothesis. + typeone: The type of error rate to control. + alpha: The significance level for the error rate. + nulldist: Method for estimating the null distribution. + b: The number of bootstrap or permutation resamples. + method: The multiple testing procedure to use for adjusting p-values. + seed: An optional integer seed for random number generation to ensure reproducibility. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not data_file.is_file(): + raise FileNotFoundError(f"Data file not found: {data_file}") + if not class_labels_file.is_file(): + raise FileNotFoundError(f"Class labels file not found: {class_labels_file}") + if not (0 < alpha < 1): + raise ValueError("alpha must be between 0 and 1.") + if b <= 0: + raise ValueError("Number of resamples (b) must be a positive integer.") + + output_dir = Path.cwd() + adjp_output_file = output_dir / f"{output_prefix}_adjp.csv" + reject_output_file = output_dir / f"{output_prefix}_rejected_indices.csv" + + # --- R Script Generation --- + # Handle optional seed value for R script + r_seed_code = f"set.seed({seed})" if seed is not None else "" + + r_script_content = f""" + # Load the library + library(multtest) + + # Set seed for reproducibility if provided + {r_seed_code} + + # Read input data + # Using tryCatch for better error reporting from R + tryCatch({{ + X <- as.matrix(read.csv('{data_file}', header=TRUE, row.names=1, check.names=FALSE)) + Y <- read.csv('{class_labels_file}', header=FALSE)$V1 + + # Run the Multiple Testing Procedure + mtp_results <- MTP(X=X, Y=Y, test='{test}', alternative='{alternative}', + typeone='{typeone}', alpha={alpha}, nulldist='{nulldist}', + B={b}, method='{method}') + + # Write adjusted p-values to output file + write.csv(mtp_results@adjp, file='{adjp_output_file}', row.names=TRUE) + + # Write indices of rejected hypotheses + rejected_indices <- which(mtp_results@reject) + write.csv(rejected_indices, file='{reject_output_file}', row.names=FALSE) + + cat("MTP analysis completed successfully.\\n") + }}, error = function(e) {{ + stop("R script failed with error: ", e$message) + }}) + """ + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_mtp.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(r_script_path)] + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + 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": { + "adjusted_p_values": str(adjp_output_file), + "rejected_indices": str(reject_output_file) + } + } + except subprocess.CalledProcessError as e: + logging.error(f"Error executing R script for MTP: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") from e + + +@mcp.tool() +def multtest_adjust_pvalues( + raw_pvalues_file: Path, + procedures: List[ADJP_PROCEDURE_CHOICES], + output_prefix: str, +) -> dict: + """ + Computes adjusted p-values from a set of raw (unadjusted) p-values. + + This function is a wrapper for the `mt.rawp2adjp` function in the `multtest` R package. + It applies one or more specified adjustment procedures to a given list of p-values. + + Args: + raw_pvalues_file: Path to a CSV file of raw p-values. The file should have a header + and the first column should contain feature/gene names. + procedures: A list of adjustment procedures to apply. + output_prefix: Prefix for the output file (e.g., 'my_analysis_adjp'). + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output file. + """ + # --- Input Validation --- + if not raw_pvalues_file.is_file(): + raise FileNotFoundError(f"Raw p-values file not found: {raw_pvalues_file}") + if not procedures: + raise ValueError("At least one adjustment procedure must be specified.") + + output_dir = Path.cwd() + output_file = output_dir / f"{output_prefix}_adjusted_pvalues.csv" + + # --- R Script Generation --- + # Format the list of procedures into an R character vector string, e.g., c("BH", "Bonferroni") + r_proc_vector = 'c(' + ', '.join(f'"{p}"' for p in procedures) + ')' + + r_script_content = f""" + # Load the library + library(multtest) + + # Read input data + tryCatch({{ + rawp <- as.matrix(read.csv('{raw_pvalues_file}', header=TRUE, row.names=1, check.names=FALSE)) + + # Define the adjustment procedures + procs <- {r_proc_vector} + + # Run the p-value adjustment + adj_results <- mt.rawp2adjp(rawp, proc=procs) + + # Write the adjusted p-values to the output file + # The result 'adjp' contains the adjusted p-values, with original p-values in the first column + write.csv(adj_results$adjp, file='{output_file}', row.names=TRUE) + + cat("P-value adjustment completed successfully.\\n") + }}, error = function(e) {{ + stop("R script failed with error: ", e$message) + }}) + """ + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_adjp.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(r_script_path)] + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + 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": { + "adjusted_p_values": str(output_file) + } + } + except subprocess.CalledProcessError as e: + logging.error(f"Error executing R script for p-value adjustment: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") from e + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-multtest/app/bioconductor-multtest_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-multtest/app/bioconductor-multtest_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2b6107d58c37cffbce0d4e92f23c92cbb1de34d5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-multtest/app/bioconductor-multtest_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-multtest/app/bioconductor-multtest_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_multtest' + + +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/Biomni/mcp_generated/mcp_bioconductor-multtest/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-multtest/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-multtest/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-multtest/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-multtest/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6bc264787603248074bf059e0399068f89fd919a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-multtest/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-multtest: + build: . + image: mcp-bioconductor-multtest:latest + container_name: mcp-bioconductor-multtest + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-multtest + 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/Biomni/mcp_generated/mcp_bioconductor-multtest/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-multtest/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f686d7fe95f83931ab22a680f054decfb3dd5756 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-multtest/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-multtest + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-multtest/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-multtest/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-multtest/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-mzr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-mzr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-mzr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-nebulosa/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0f63490caed08cf51637c5ae1864b93d17c928e8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/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-nebulosa via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-nebulosa -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-nebulosa_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-nebulosa_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-nebulosa_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_server.py b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1acb976fd65c2b32692aea0fcc54a97d3803e4e8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_server.py @@ -0,0 +1,185 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Tuple + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def tool(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_nebulosa' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def nebulosa_plot_density( + object_file: Path, + features: List[str], + output_file: Path, + reduction: Optional[str] = None, + dims: Tuple[int, int] = (1, 2), + pal: str = "viridis", + joint: bool = False, + combine: bool = True, + pt_size: float = 0.1, + pt_shape: int = 16, + pt_alpha: float = 1.0, + dens_alpha: float = 0.5, + plot_width: float = 8.0, + plot_height: float = 6.0, +) -> dict: + """ + Generates density plots for single-cell features using the Nebulosa R package. + + This tool wraps the `plot_density` function from `bioconductor-nebulosa`. It takes a + single-cell object (e.g., from Seurat, saved as an .rds file), a list of features + (e.g., genes), and generates a plot showing the expression density of these + features on a dimensionality reduction embedding (like UMAP or t-SNE). + + Args: + object_file: Path to the input single-cell object file in .rds format. + features: A list of features (e.g., genes) to plot. + output_file: Path to save the output plot. Supported formats include PDF, PNG, JPEG. + reduction: The dimensionality reduction to use (e.g., 'umap', 'tsne'). + If None, the default from the object is used. + dims: A tuple of two integers specifying the dimensions to plot (e.g., (1, 2)). + pal: The color palette to use for the density plot (e.g., 'viridis', 'magma'). + joint: If True, plots all features jointly on a single plot. + combine: If True and `joint` is False, combines multiple feature plots into a single grid. + pt_size: The size of the points in the plot. + pt_shape: The shape of the points (integer code). + pt_alpha: The transparency of the points (0.0 to 1.0). + dens_alpha: The transparency of the density layer (0.0 to 1.0). + plot_width: The width of the output plot in inches. + plot_height: The height of the output plot in inches. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + mapping to the generated output plot file. + """ + # --- Input Validation --- + if not object_file.is_file(): + raise FileNotFoundError(f"Input object file not found: {object_file}") + + if not features: + raise ValueError("The 'features' list cannot be empty.") + + if not output_file.parent.exists(): + raise FileNotFoundError(f"Output directory does not exist: {output_file.parent}") + + if len(dims) != 2: + raise ValueError(f"'dims' must be a tuple of two integers, but got {dims}") + + if not (0.0 <= pt_alpha <= 1.0): + raise ValueError(f"'pt_alpha' must be between 0.0 and 1.0, but got {pt_alpha}") + + if not (0.0 <= dens_alpha <= 1.0): + raise ValueError(f"'dens_alpha' must be between 0.0 and 1.0, but got {dens_alpha}") + + # --- R Script Generation --- + # Convert Python types to R syntax strings + features_r_str = ', '.join(f'"{f}"' for f in features) + reduction_r_str = f'"{reduction}"' if reduction else "NULL" + joint_r_str = str(joint).upper() + combine_r_str = str(combine).upper() + + r_script_content = f""" + # Suppress package startup messages for cleaner output + suppressPackageStartupMessages(library(Nebulosa)) + suppressPackageStartupMessages(library(Seurat)) # Assumes a Seurat object for loading + suppressPackageStartupMessages(library(ggplot2)) + + # --- Parameters from Python --- + object_path <- "{object_file.resolve()}" + output_path <- "{output_file.resolve()}" + features_vec <- c({features_r_str}) + reduction_val <- {reduction_r_str} + dims_vec <- c({dims[0]}, {dims[1]}) + pal_str <- "{pal}" + joint_bool <- {joint_r_str} + combine_bool <- {combine_r_str} + pt_size_num <- {pt_size} + pt_shape_num <- {pt_shape} + pt_alpha_num <- {pt_alpha} + dens_alpha_num <- {dens_alpha} + plot_width_num <- {plot_width} + plot_height_num <- {plot_height} + + # --- Main Logic --- + cat("Loading single-cell object from:", object_path, "\\n") + sobj <- readRDS(object_path) + + cat("Generating density plot for features:", paste(features_vec, collapse=", "), "\\n") + p <- plot_density( + object = sobj, + features = features_vec, + reduction = reduction_val, + dims = dims_vec, + pal = pal_str, + joint = joint_bool, + combine = combine_bool, + pt.size = pt_size_num, + pt.shape = pt_shape_num, + pt.alpha = pt_alpha_num, + dens.alpha = dens_alpha_num + ) + + cat("Saving plot to:", output_path, "\\n") + ggsave( + filename = output_path, + plot = p, + width = plot_width_num, + height = plot_height_num, + units = "in" + ) + + cat("Plot generation complete.\\n") + """ + + # --- Subprocess Execution --- + stdout_str, stderr_str = "", "" + command_to_run = [] + + try: + with tempfile.NamedTemporaryFile( + mode="w", suffix=".R", delete=False + ) as tmp_script: + tmp_script_path = Path(tmp_script.name) + tmp_script.write(r_script_content) + + command_to_run = ["Rscript", str(tmp_script_path)] + process = subprocess.run( + command_to_run, + capture_output=True, + text=True, + check=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + stderr_str = e.stderr + f"\n--- R Script Content ---\n{r_script_content}" + raise RuntimeError(f"R script execution failed with exit code {e.returncode}:\n{stderr_str}") + finally: + if 'tmp_script_path' in locals() and tmp_script_path.exists(): + tmp_script_path.unlink() + + # --- Structured Result Return --- + return { + "command_executed": " ".join(command_to_run), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": {"density_plot": str(output_file)}, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2ac1f7f1315815bbbe67a58318c9dba20f7f5e9d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_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-nebulosa/app/bioconductor-nebulosa_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_nebulosa' + + +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/Biomni/mcp_generated/mcp_bioconductor-nebulosa/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..791e3c6938d43d81317b2e40924857ae6bb3b39c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-nebulosa: + build: . + image: mcp-bioconductor-nebulosa:latest + container_name: mcp-bioconductor-nebulosa + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-nebulosa + 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/Biomni/mcp_generated/mcp_bioconductor-nebulosa/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b24fe111257cb3c281a4ef0fe14bb4737b81aeba --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-nebulosa + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-nebulosa/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nebulosa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-nnsvg/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..86a9d3cb5360bb8b481fd41dcb57b2c31278be64 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/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-nnsvg via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-nnsvg -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-nnsvg_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-nnsvg_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-nnsvg_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_server.py b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_server.py new file mode 100644 index 0000000000000000000000000000000000000000..84626c19eeac653d81f3678189424bb7366ee46f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_server.py @@ -0,0 +1,140 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# Mock mcp decorator for standalone execution +class mcp: + def tool(func): + return func + +@mcp.tool +def nnsvg( + input_rds: Path, + output_rds: Path, + assay_name: str = "logcounts", + covariates_file: Optional[Path] = None, + n_neighbors: int = 10, + n_omp_threads: int = 1, + verbose: bool = True, +): + """ + Runs nnSVG to identify spatially variable genes in SpatialExperiment data. + + This tool is a wrapper for the nnSVG() function from the Bioconductor package 'nnSVG'. + It identifies and ranks spatially variable genes (SVGs) in spatially-resolved + transcriptomics data using a scalable nearest-neighbor Gaussian process model. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + This object should contain expression data and spatial coordinates. + output_rds: Path to save the output RDS file. The original SpatialExperiment + object will be saved here with nnSVG results added to its rowData. + assay_name: Name of the assay in the input object containing the expression + values (e.g., 'logcounts', 'counts'). Defaults to "logcounts". + covariates_file: Optional path to a CSV file containing covariates. The first + column should contain sample names matching the column names + in the SpatialExperiment object. The remaining columns are + treated as covariates. + n_neighbors: Number of nearest neighbors to use for the Gaussian process model. + Defaults to 10. + n_omp_threads: Number of threads for parallelization. Defaults to 1. + verbose: Whether to print progress messages from the R script. Defaults to True. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of output files. + """ + # 1. Input Validation + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if covariates_file and not covariates_file.is_file(): + raise FileNotFoundError(f"Covariates file not found: {covariates_file}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if n_omp_threads <= 0: + raise ValueError("n_omp_threads must be a positive integer.") + + # 2. Construct the R script + # Using as_posix() ensures cross-platform path compatibility for R + r_script_parts = [ + "library(nnSVG)", + "library(SpatialExperiment)", + f"spe <- readRDS('{input_rds.as_posix()}')", + ] + + covariates_r_code = "covariates_matrix <- NULL" + if covariates_file: + covariates_r_code = f""" +cov_df <- read.csv('{covariates_file.as_posix()}', row.names = 1, header = TRUE) +# Ensure order of samples in covariates matches the SpatialExperiment object +cov_df <- cov_df[colnames(spe), , drop = FALSE] +covariates_matrix <- model.matrix(~ ., data = cov_df) +# Remove intercept column if it exists, as it's often not needed +if ('(Intercept)' %in% colnames(covariates_matrix)) {{ + covariates_matrix <- covariates_matrix[, colnames(covariates_matrix) != '(Intercept)', drop = FALSE] +}} +# If only the intercept was present, set covariates to NULL +if (ncol(covariates_matrix) == 0) {{ + covariates_matrix <- NULL +}} +""" + r_script_parts.append(covariates_r_code) + + r_script_parts.append( + f""" +# Run the main nnSVG function +spe_with_results <- nnSVG( + input = spe, + assay_name = '{assay_name}', + covariates = covariates_matrix, + n_neighbors = {n_neighbors}, + n_omp_threads = {n_omp_threads}, + verbose = {'TRUE' if verbose else 'FALSE'} +) + +# Save the updated object to the output file +saveRDS(spe_with_results, file = '{output_rds.as_posix()}') + +cat("nnSVG analysis complete. Results saved to {output_rds.as_posix()}\\n") +""" + ) + + r_script = "\n".join(r_script_parts) + + # 3. Execute the R script + cmd = [] + try: + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_nnsvg.R" + with open(r_script_path, "w") as f: + f.write(r_script) + + cmd = ["Rscript", str(r_script_path)] + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds)] + } + + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + raise RuntimeError("Rscript command not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # This error occurs if the R script fails + error_message = ( + f"The R script failed with return code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) from e diff --git a/Biomni/mcp_generated/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..54ac7de4ad4423e135356ee3eb2f79fd804f4690 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_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-nnsvg/app/bioconductor-nnsvg_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_nnsvg' + + +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/Biomni/mcp_generated/mcp_bioconductor-nnsvg/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-nnsvg/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eb5fe2b6efb56c0ed0f12c50ae83ca8d4a776580 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-nnsvg: + build: . + image: mcp-bioconductor-nnsvg:latest + container_name: mcp-bioconductor-nnsvg + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-nnsvg + 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/Biomni/mcp_generated/mcp_bioconductor-nnsvg/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b463df348f53cc893866b00bc7c7169816e73b7a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-nnsvg + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-nnsvg/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-nnsvg/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-noiseq/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-noiseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0236be3dad1e86c4a1134b86ae90e82892bbbc78 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-noiseq/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-noiseq via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-noiseq -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-noiseq_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-noiseq_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-noiseq_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py b/Biomni/mcp_generated/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9a3b2bc70fe62eb525cace329259ec7af6d1093c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py @@ -0,0 +1,421 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import List, Optional + +# MCP decorator is not imported as per instructions. +# It is assumed to be available in the execution environment. +# from mcp import tool as mcp_tool + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_noiseq' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def noiseqbio( + counts_file: Path, + phenodata_file: Path, + factor: str, + condition1: str, + condition2: str, + output_prefix: str, + gene_info_file: Optional[Path] = None, + k: Optional[float] = 0.5, + norm: str = "tmm", + lc: int = 1, + r: int = 20, + adj: float = 1.5, + a0per: float = 0.9, + filter_method: int = 1, + q_threshold: float = 0.8, +) -> dict: + """ + Performs differential expression analysis for RNA-Seq data with biological + replicates using NOISeqbio. + + NOISeq is a non-parametric approach for the identification of differentially + expressed genes from count data. This function is specifically for experiments + with biological replicates. + + Args: + counts_file: Path to the input counts matrix file (e.g., TSV, CSV). + Rows should be genes/features and columns should be samples. + phenodata_file: Path to the phenodata/metadata file. Rows must correspond + to samples (columns in counts_file) and columns to experimental + factors. + factor: The name of the column in phenodata_file that contains the + experimental conditions to be compared. + condition1: The first condition or level of the factor to compare. + condition2: The second condition or level of the factor to compare. + output_prefix: The prefix for the output result file. + gene_info_file: Optional path to a file containing gene information like + length, GC content, or biotype. Required for certain + normalizations. + k: Value to be added to the counts for log-transformation. If None, no + transformation is applied. Defaults to 0.5. + norm: Normalization method. One of "rpkm", "uqua", "tmm", "n" (none). + Defaults to "tmm". + lc: Length correction parameter. Defaults to 1. + r: Number of permutations to compute the null distribution. Defaults to 20. + adj: Adjustment factor for feature length in saturation study. Defaults to 1.5. + a0per: Percentile of feature length distribution for saturation study. + Must be between 0 and 1. Defaults to 0.9. + filter_method: Method for filtering low count features. 0: no filter; + 1: CPM-based; 2: count-based. Defaults to 1. + q_threshold: Probability threshold for defining differentially expressed + genes. Must be between 0 and 1. Defaults to 0.8. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of output file paths. + """ + # --- Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not phenodata_file.is_file(): + raise FileNotFoundError(f"Phenodata file not found: {phenodata_file}") + if gene_info_file and not gene_info_file.is_file(): + raise FileNotFoundError(f"Gene info file not found: {gene_info_file}") + + valid_norms = ["rpkm", "uqua", "tmm", "n"] + if norm not in valid_norms: + raise ValueError(f"Invalid normalization method '{norm}'. Must be one of {valid_norms}.") + + if not 0.0 <= a0per <= 1.0: + raise ValueError("a0per must be between 0.0 and 1.0.") + if not 0.0 <= q_threshold <= 1.0: + raise ValueError("q_threshold must be between 0.0 and 1.0.") + if filter_method not in [0, 1, 2]: + raise ValueError("filter_method must be 0, 1, or 2.") + if lc < 0: + raise ValueError("lc must be a non-negative integer.") + if r < 1: + raise ValueError("r must be a positive integer.") + if adj < 0: + raise ValueError("adj must be a non-negative float.") + + with tempfile.TemporaryDirectory() as temp_dir: + work_dir = Path(temp_dir) + output_file = work_dir / f"{output_prefix}_noiseqbio_results.tsv" + r_script_path = work_dir / "run_noiseqbio.R" + + # --- R Script Generation --- + r_script = textwrap.dedent(f"""\ + suppressPackageStartupMessages(library(argparse)) + suppressPackageStartupMessages(library(NOISeq)) + + parser <- ArgumentParser(description='Run NOISeqbio analysis') + parser$add_argument('--counts', type='character', required=TRUE) + parser$add_argument('--pheno', type='character', required=TRUE) + parser$add_argument('--gene_info', type='character', default=NULL) + parser$add_argument('--factor', type='character', required=TRUE) + parser$add_argument('--cond1', type='character', required=TRUE) + parser$add_argument('--cond2', type='character', required=TRUE) + parser$add_argument('--output', type='character', required=TRUE) + parser$add_argument('--k', type='double', default=NA) + parser$add_argument('--norm', type='character', default='tmm') + parser$add_argument('--lc', type='integer', default=1) + parser$add_argument('--r', type='integer', default=20) + parser$add_argument('--adj', type='double', default=1.5) + parser$add_argument('--a0per', type='double', default=0.9) + parser$add_argument('--filter', type='integer', default=1) + parser$add_argument('--q', type='double', default=0.8) + args <- parser$parse_args() + + # Read data + counts_data <- read.delim(args$counts, row.names=1, check.names=FALSE) + pheno_data <- read.delim(args$pheno, row.names=1, check.names=FALSE) + + # Prepare optional data + length_data <- NULL + gc_data <- NULL + biotype_data <- NULL + if (!is.null(args$gene_info)) {{ + gene_info_data <- read.delim(args$gene_info, row.names=1, check.names=FALSE) + if ("length" %in% colnames(gene_info_data)) length_data <- gene_info_data[,"length", drop=FALSE] + if ("gc" %in% colnames(gene_info_data)) gc_data <- gene_info_data[,"gc", drop=FALSE] + if ("biotype" %in% colnames(gene_info_data)) biotype_data <- gene_info_data[,"biotype", drop=FALSE] + }} + + # Create NOISeq object + mydata <- readData( + data = counts_data, + factors = pheno_data, + length = length_data, + gc = gc_data, + biotype = biotype_data + ) + + # Handle optional k + k_val <- if (is.na(args$k)) NULL else args$k + + # Run analysis + mynoiseqbio <- noiseqbio( + mydata, + factor = args$factor, + conditions = c(args$cond1, args$cond2), + k = k_val, + norm = args$norm, + lc = as.integer(args$lc), + r = as.integer(args$r), + adj = as.double(args$adj), + a0per = as.double(args$a0per), + filter = as.integer(args$filter) + ) + + # Write results + results_df <- degenes(mynoiseqbio, q = args$q, M = NULL) + write.table(results_df, file=args$output, sep="\\t", quote=FALSE, row.names=TRUE, col.names=NA) + + cat("NOISeqbio analysis completed successfully.\\n") + """) + with open(r_script_path, "w") as f: + f.write(r_script) + + # --- Command Construction --- + cmd = [ + "Rscript", str(r_script_path), + "--counts", str(counts_file.resolve()), + "--pheno", str(phenodata_file.resolve()), + "--factor", factor, + "--cond1", condition1, + "--cond2", condition2, + "--output", str(output_file.resolve()), + "--norm", norm, + "--lc", str(lc), + "--r", str(r), + "--adj", str(adj), + "--a0per", str(a0per), + "--filter", str(filter_method), + "--q", str(q_threshold), + ] + if k is not None: + cmd.extend(["--k", str(k)]) + if gene_info_file: + cmd.extend(["--gene_info", str(gene_info_file.resolve())]) + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=work_dir, + ) + final_output_file = Path.cwd() / f"{output_prefix}_noiseqbio_results.tsv" + output_file.rename(final_output_file) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(final_output_file)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "NOISeqbio execution failed.", + "return_code": e.returncode, + } + +@mcp.tool() +def noiseq( + counts_file: Path, + phenodata_file: Path, + factor: str, + condition1: str, + condition2: str, + replicates: str, + output_prefix: str, + gene_info_file: Optional[Path] = None, + k: Optional[float] = 0.5, + norm: str = "rpkm", + pnr: float = 0.2, + nss: int = 5, + v: float = 0.02, + lc: int = 1, + q_threshold: float = 0.8, +) -> dict: + """ + Performs differential expression analysis for RNA-Seq data with technical + replicates or no replicates using NOISeq. + + This function is suited for experiments where biological replicates are not + available. It simulates technical replicates to assess noise. + + Args: + counts_file: Path to the input counts matrix file (e.g., TSV, CSV). + phenodata_file: Path to the phenodata/metadata file. + factor: The name of the column in phenodata_file that contains the + experimental conditions. + condition1: The first condition to compare. + condition2: The second condition to compare. + replicates: Type of replicates. Must be "technical" or "no". + output_prefix: The prefix for the output result file. + gene_info_file: Optional path to a file with gene information (length, etc.). + k: Value for log-transformation. If None, no transformation. Defaults to 0.5. + norm: Normalization method. One of "rpkm", "uqua", "tmm", "n". Defaults to "rpkm". + pnr: Percentage of lowest expression features for noise estimation. + Must be between 0 and 1. Defaults to 0.2. + nss: Number of samples for null distribution estimation (if replicates="technical"). + Defaults to 5. + v: Variability parameter. Must be between 0 and 1. Defaults to 0.02. + lc: Length correction parameter. Defaults to 1. + q_threshold: Probability threshold for DE genes. Defaults to 0.8. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of output file paths. + """ + # --- Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not phenodata_file.is_file(): + raise FileNotFoundError(f"Phenodata file not found: {phenodata_file}") + if gene_info_file and not gene_info_file.is_file(): + raise FileNotFoundError(f"Gene info file not found: {gene_info_file}") + + valid_replicates = ["technical", "no"] + if replicates not in valid_replicates: + raise ValueError(f"Invalid replicates type '{replicates}'. Must be one of {valid_replicates}.") + valid_norms = ["rpkm", "uqua", "tmm", "n"] + if norm not in valid_norms: + raise ValueError(f"Invalid normalization method '{norm}'. Must be one of {valid_norms}.") + + if not 0.0 <= pnr <= 1.0: + raise ValueError("pnr must be between 0.0 and 1.0.") + if not 0.0 <= v <= 1.0: + raise ValueError("v must be between 0.0 and 1.0.") + if not 0.0 <= q_threshold <= 1.0: + raise ValueError("q_threshold must be between 0.0 and 1.0.") + if nss < 1: + raise ValueError("nss must be a positive integer.") + if lc < 0: + raise ValueError("lc must be a non-negative integer.") + + with tempfile.TemporaryDirectory() as temp_dir: + work_dir = Path(temp_dir) + output_file = work_dir / f"{output_prefix}_noiseq_results.tsv" + r_script_path = work_dir / "run_noiseq.R" + + # --- R Script Generation --- + r_script = textwrap.dedent(f"""\ + suppressPackageStartupMessages(library(argparse)) + suppressPackageStartupMessages(library(NOISeq)) + + parser <- ArgumentParser(description='Run NOISeq analysis') + parser$add_argument('--counts', type='character', required=TRUE) + parser$add_argument('--pheno', type='character', required=TRUE) + parser$add_argument('--gene_info', type='character', default=NULL) + parser$add_argument('--factor', type='character', required=TRUE) + parser$add_argument('--cond1', type='character', required=TRUE) + parser$add_argument('--cond2', type='character', required=TRUE) + parser$add_argument('--replicates', type='character', required=TRUE) + parser$add_argument('--output', type='character', required=TRUE) + parser$add_argument('--k', type='double', default=NA) + parser$add_argument('--norm', type='character', default='rpkm') + parser$add_argument('--pnr', type='double', default=0.2) + parser$add_argument('--nss', type='integer', default=5) + parser$add_argument('--v', type='double', default=0.02) + parser$add_argument('--lc', type='integer', default=1) + parser$add_argument('--q', type='double', default=0.8) + args <- parser$parse_args() + + counts_data <- read.delim(args$counts, row.names=1, check.names=FALSE) + pheno_data <- read.delim(args$pheno, row.names=1, check.names=FALSE) + + length_data <- NULL; gc_data <- NULL; biotype_data <- NULL + if (!is.null(args$gene_info)) {{ + gene_info_data <- read.delim(args$gene_info, row.names=1, check.names=FALSE) + if ("length" %in% colnames(gene_info_data)) length_data <- gene_info_data[,"length", drop=FALSE] + if ("gc" %in% colnames(gene_info_data)) gc_data <- gene_info_data[,"gc", drop=FALSE] + if ("biotype" %in% colnames(gene_info_data)) biotype_data <- gene_info_data[,"biotype", drop=FALSE] + }} + + mydata <- readData( + data = counts_data, + factors = pheno_data, + length = length_data, + gc = gc_data, + biotype = biotype_data + ) + + k_val <- if (is.na(args$k)) NULL else args$k + + mynoiseq <- noiseq( + mydata, + factor = args$factor, + replicates = args$replicates, + conditions = c(args$cond1, args$cond2), + k = k_val, + norm = args$norm, + pnr = as.double(args$pnr), + nss = as.integer(args$nss), + v = as.double(args$v), + lc = as.integer(args$lc) + ) + + results_df <- degenes(mynoiseq, q = args$q, M = NULL) + write.table(results_df, file=args$output, sep="\\t", quote=FALSE, row.names=TRUE, col.names=NA) + + cat("NOISeq analysis completed successfully.\\n") + """) + with open(r_script_path, "w") as f: + f.write(r_script) + + # --- Command Construction --- + cmd = [ + "Rscript", str(r_script_path), + "--counts", str(counts_file.resolve()), + "--pheno", str(phenodata_file.resolve()), + "--factor", factor, + "--cond1", condition1, + "--cond2", condition2, + "--replicates", replicates, + "--output", str(output_file.resolve()), + "--norm", norm, + "--pnr", str(pnr), + "--nss", str(nss), + "--v", str(v), + "--lc", str(lc), + "--q", str(q_threshold), + ] + if k is not None: + cmd.extend(["--k", str(k)]) + if gene_info_file: + cmd.extend(["--gene_info", str(gene_info_file.resolve())]) + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=work_dir, + ) + final_output_file = Path.cwd() / f"{output_prefix}_noiseq_results.tsv" + output_file.rename(final_output_file) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(final_output_file)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "NOISeq execution failed.", + "return_code": e.returncode, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-noiseq/app/bioconductor-noiseq_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-noiseq/app/bioconductor-noiseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..45910b37788c457e2a0560ead6ee36635353daf3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-noiseq/app/bioconductor-noiseq_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-noiseq/app/bioconductor-noiseq_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_noiseq' + + +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/Biomni/mcp_generated/mcp_bioconductor-noiseq/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-noiseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-noiseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-noiseq/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-noiseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f800395ced0511dc9c22d1332037d8d07bbe14f4 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-noiseq/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-noiseq: + build: . + image: mcp-bioconductor-noiseq:latest + container_name: mcp-bioconductor-noiseq + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-noiseq + 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/Biomni/mcp_generated/mcp_bioconductor-noiseq/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-noiseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..96a600a3aa5d094c29ef4b5908e396f15643085f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-noiseq/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-noiseq + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-noiseq/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-noiseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-noiseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-orfhunter/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-orfhunter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ef6617906b8f7a0a1eedb1ed96648f36004ded13 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py b/Biomni/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..58d501afdf7a36ed397172cfdf6854fa407c105a --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c569fa074b095dd4652bad3c74f32a4a4953f057 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-orfhunter/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-orfhunter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-orfhunter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-orfhunter/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-orfhunter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ffd1257beabc2e36bf2d4c39081ee52804eafd1d --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-orfhunter/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-orfhunter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..abc3d2710d8c879e5c5ae780455731d3b509b0d0 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-orfhunter/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-orfhunter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-orfhunter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2d86d2a336872e24991c5f1dda25fd891c93cbc7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/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-org.ce.eg.db via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-org.ce.eg.db -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-org.ce.eg.db_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-org.ce.eg.db_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-org.ce.eg.db_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_server.py b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a35addcb9b105aa6fe2822c8552b094485f93d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_server.py @@ -0,0 +1,380 @@ +import subprocess +import textwrap +from pathlib import Path +from typing import List, Optional, Dict, Any + +# MCP decorator is not imported as per instructions, but assumed to be present. +# from mcp import tool as mcp_tool +# For the purpose of this script, we'll define a dummy decorator. +class mcp: + def tool(): + def decorator(f): + return f + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_org_ce_eg_db' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def select_annotations( + keys: List[str], + keytype: str, + columns: List[str], + output_file: str, + output_format: str = "tsv", +) -> Dict[str, Any]: + """ + Perform a complex query on the org.Ce.eg.db C. elegans annotation database using the select() method. + This returns a table of mappings between the provided keys and requested columns. + + Args: + keys: List of identifiers to look up (e.g., ["172469", "172470"] or ["skn-1", "gfp"]). + keytype: The type of the input keys (e.g., "ENTREZID", "SYMBOL", "WORMBASE", "ENSEMBL"). + columns: The annotation types to retrieve (e.g., ["GO", "EVIDENCE", "ONTOLOGY", "GENENAME"]). + output_file: Path to save the resulting table. + output_format: Format of the output file ("tsv" or "csv"). Defaults to "tsv". + """ + # Input validation + if not keys: + raise ValueError("The 'keys' list cannot be empty.") + if not keytype: + raise ValueError("The 'keytype' parameter must be specified.") + if not columns: + raise ValueError("The 'columns' list cannot be empty.") + + valid_formats = ["tsv", "csv"] + if output_format not in valid_formats: + raise ValueError(f"output_format must be one of {valid_formats}") + + out_path = Path(output_file).resolve() + out_path.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R vectors safely + keys_str = ", ".join([f'"{k}"' for k in keys]) + cols_str = ", ".join([f'"{c}"' for c in columns]) + + # The R script uses f-string formatting. Literal curly braces for R code blocks + # must be escaped by doubling them (e.g., {{ and }}). + r_script = textwrap.dedent(f""" + suppressPackageStartupMessages(library(org.Ce.eg.db)) + suppressPackageStartupMessages(library(AnnotationDbi)) + + # Validate inputs in R + if (!("{keytype}" %in% keytypes(org.Ce.eg.db))) {{{{ + stop(paste("Invalid keytype:", "{keytype}")) + }}}} + + requested_cols <- c({cols_str}) + valid_cols <- columns(org.Ce.eg.db) + if (!all(requested_cols %in% valid_cols)) {{{{ + invalid_ones <- requested_cols[!(requested_cols %in% valid_cols)] + stop(paste("Invalid columns:", paste(invalid_ones, collapse=", "))) + }}}} + + res <- tryCatch({{{{ + AnnotationDbi::select( + org.Ce.eg.db, + keys = c({keys_str}), + columns = requested_cols, + keytype = "{keytype}" + ) + }}}}, error = function(e) {{{{ + stop(paste("Select failed:", e$message)) + }}}}) + + if ("{output_format}" == "tsv") {{{{ + write.table(res, file = "{out_path}", sep = "\\t", quote = FALSE, row.names = FALSE) + }}}} else {{{{ + write.csv(res, file = "{out_path}", quote = FALSE, row.names = FALSE) + }}}} + """) + + command_str = f"Rscript -e \"{r_script}\"" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": "Rscript -e 'AnnotationDbi::select(...)'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "Rscript -e 'AnnotationDbi::select(...)'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def map_ids( + keys: List[str], + keytype: str, + column: str, + multi_vals: str = "first", +) -> Dict[str, Any]: + """ + Map identifiers from one type to another using the mapIds() method. + This is optimized for 1-to-1 or 1-to-many mapping. + + Args: + keys: List of identifiers to map. + keytype: The type of the input keys (e.g., "WORMBASE"). + column: The type of identifier to map to (e.g., "SYMBOL"). + multi_vals: How to handle multiple matches. Options: "first", "list", "filter", "asNA", "CharacterList". + """ + if not keys: + raise ValueError("The 'keys' list cannot be empty.") + + valid_multi = ["first", "list", "filter", "asNA", "CharacterList"] + if multi_vals not in valid_multi: + raise ValueError(f"multi_vals must be one of {valid_multi}") + + keys_str = ", ".join([f'"{k}"' for k in keys]) + + r_script = textwrap.dedent(f""" + suppressPackageStartupMessages(library(org.Ce.eg.db)) + suppressPackageStartupMessages(library(AnnotationDbi)) + + res <- mapIds( + org.Ce.eg.db, + keys = c({keys_str}), + column = "{column}", + keytype = "{keytype}", + multiVals = "{multi_vals}" + ) + + # Convert to a structured key-value output for easy parsing + cat("---RESULT_START---\\n") + if (is.list(res) || is(res, "CharacterList")) {{{{ + for (n in names(res)) {{{{ + # Handle NULLs which represent no mapping + value <- if (is.null(res[[n]])) "NA" else paste(res[[n]], collapse=",") + cat(n, ":", value, "\\n") + }}}} + }}}} else {{{{ + for (n in names(res)) {{{{ + value <- if (is.na(res[n])) "NA" else res[n] + cat(n, ":", value, "\\n") + }}}} + }}}} + cat("---RESULT_END---\\n") + """) + + command_str = "Rscript -e 'AnnotationDbi::mapIds(...)'" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # Parse the structured output from R + output_str = process.stdout + result_block = output_str.split("---RESULT_START---\n")[-1].split("---RESULT_END---")[0].strip() + mappings = {} + if result_block: + for line in result_block.split('\n'): + parts = line.split(':', 1) + if len(parts) == 2: + key = parts[0].strip() + val_str = parts[1].strip() + if val_str == "NA": + mappings[key] = None + else: + values = [v.strip() for v in val_str.split(',')] + if multi_vals in ["first", "asNA"] and len(values) == 1: + mappings[key] = values[0] + else: + mappings[key] = values + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "mappings": mappings + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def list_resources() -> Dict[str, Any]: + """ + List all available keytypes and columns (annotation types) in the org.Ce.eg.db package. + """ + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(org.Ce.eg.db)) + cat("---COLUMNS_START---\\n") + cat(paste(columns(org.Ce.eg.db), collapse=", "), "\\n") + cat("---COLUMNS_END---\\n") + cat("---KEYTYPES_START---\\n") + cat(paste(keytypes(org.Ce.eg.db), collapse=", "), "\\n") + cat("---KEYTYPES_END---\\n") + """) + + command_str = "Rscript -e 'columns(...); keytypes(...)'" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # Parse structured output + stdout_str = process.stdout + columns_str = stdout_str.split("---COLUMNS_START---\n")[1].split("---COLUMNS_END---")[0].strip() + keytypes_str = stdout_str.split("---KEYTYPES_START---\n")[1].split("---KEYTYPES_END---")[0].strip() + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "columns": columns_str.split(", ") if columns_str else [], + "keytypes": keytypes_str.split(", ") if keytypes_str else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def get_db_metadata() -> Dict[str, Any]: + """ + Retrieve metadata about the org.Ce.eg.db package, such as version, species, and data sources. + """ + r_script = "suppressPackageStartupMessages(library(org.Ce.eg.db)); print(metadata(org.Ce.eg.db))" + command_str = f"Rscript -e \"{r_script}\"" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "metadata": process.stdout.strip().split('\n') + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def get_available_keys( + keytype: str, + pattern: Optional[str] = None, + limit: int = 100 +) -> Dict[str, Any]: + """ + Retrieve a list of all available keys for a specific keytype, optionally filtered by a pattern. + + Args: + keytype: The type of keys to retrieve (e.g., "SYMBOL"). + pattern: An optional regular expression pattern to filter keys. + limit: Maximum number of keys to return. Defaults to 100. + """ + if limit <= 0: + raise ValueError("Limit must be a positive integer.") + + pattern_arg = f', pattern = "{pattern}"' if pattern else "" + + r_script = textwrap.dedent(f""" + suppressPackageStartupMessages(library(org.Ce.eg.db)) + all_keys <- keys(org.Ce.eg.db, keytype = "{keytype}"{pattern_arg}) + cat(head(all_keys, {limit}), sep="\\n") + cat("\\n---TOTAL_COUNT:", length(all_keys), "---\\n") + """) + + command_str = f"Rscript -e 'keys(..., keytype=\"{keytype}\")'" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # Robust parsing + output_str = process.stdout + if "---TOTAL_COUNT:" in output_str: + keys_part, total_part = output_str.split("---TOTAL_COUNT:") + keys_list = keys_part.strip().split("\n") if keys_part.strip() else [] + total_count = int(total_part.replace("---", "").strip()) + else: + keys_list = output_str.strip().split("\n") if output_str.strip() else [] + total_count = len(keys_list) + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "keys": keys_list, + "total_available": total_count + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def get_species_info() -> Dict[str, Any]: + """ + Get the species name for which this annotation package was designed. + """ + r_script = "suppressPackageStartupMessages(library(org.Ce.eg.db)); cat(species(org.Ce.eg.db))" + command_str = f"Rscript -e \"{r_script}\"" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "species": process.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6ff2495121e19a778787cd455ad536f7302f10e0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_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-org.ce.eg.db/app/bioconductor-org.ce.eg.db_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_org_ce_eg_db' + + +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/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b0aca5cb848af22025e1277befdd8c28f521b8bd --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-org.ce.eg.db: + build: . + image: mcp-bioconductor-org.ce.eg.db:latest + container_name: mcp-bioconductor-org.ce.eg.db + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-org.ce.eg.db + 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/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4b02b7acc6a22c38fee1f3d8401b748f0cfde91 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-org.ce.eg.db + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.ce.eg.db/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4063797cda67f7442fa6031a699b1ed32b5b26f8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/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-org.hs.eg.db via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-org.hs.eg.db -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-org.hs.eg.db_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-org.hs.eg.db_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-org.hs.eg.db_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ef01efa092ad87d8d15838db861646b36b04b8b9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py @@ -0,0 +1,195 @@ +import subprocess +import json +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +def run_r_command(script: str) -> Dict[str, Any]: + """ + Helper function to execute R code and capture output. + Uses jsonlite in R to return structured data. + """ + # Wrap the script to load the library and output JSON + full_script = f""" + suppressPackageStartupMessages(library(org.hs.eg.db)) + suppressPackageStartupMessages(library(jsonlite)) + + tryCatch({{ + {script} + }}, error = function(e) {{ + write(paste("ERROR:", e$message), stderr()) + q(status = 1) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(full_script) + tmp_path = tmp.name + + try: + process = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "stdout": process.stdout, + "stderr": process.stderr, + "command_executed": f"Rscript {tmp_path}" + } + except subprocess.CalledProcessError as e: + return { + "error": e.stderr or e.stdout, + "command_executed": f"Rscript {tmp_path}", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_org_hs_eg_db' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def org_hs_eg_db_select( + keys: List[str], + columns: List[str], + keytype: str = "ENTREZID", +) -> Dict[str, Any]: + """ + Retrieve annotations for the specified keys from the Human (org.hs.eg.db) database. + + Args: + keys: A list of identifiers to look up (e.g., ["7157", "4312"] or ["TP53", "BRCA1"]). + columns: The types of data to retrieve (e.g., ["SYMBOL", "GENENAME", "ENSEMBL"]). + keytype: The type of the input keys (e.g., "ENTREZID", "SYMBOL", "ENSEMBL"). + """ + # Validation + if not keys: + return {"error": "At least one key must be provided."} + if not columns: + return {"error": "At least one column must be provided."} + + # Format R vectors + r_keys = 'c("' + '","'.join(keys) + '")' + r_cols = 'c("' + '","'.join(columns) + '")' + + script = f""" + res <- select(org.hs.eg.db, keys = {r_keys}, columns = {r_cols}, keytype = "{keytype}") + cat(toJSON(res, pretty = TRUE)) + """ + + result = run_r_command(script) + return result + +@mcp.tool() +def org_hs_eg_db_keytypes() -> Dict[str, Any]: + """ + List all available types of identifiers (keytypes) that can be used as input for queries. + Common types include ENTREZID, SYMBOL, ENSEMBL, and UNIPROT. + """ + script = """ + res <- keytypes(org.hs.eg.db) + cat(toJSON(res)) + """ + return run_r_command(script) + +@mcp.tool() +def org_hs_eg_db_columns() -> Dict[str, Any]: + """ + List all available annotation columns that can be retrieved from the database. + """ + script = """ + res <- columns(org.hs.eg.db) + cat(toJSON(res)) + """ + return run_r_command(script) + +@mcp.tool() +def org_hs_eg_db_map_symbol_to_entrez( + symbols: List[str] +) -> Dict[str, Any]: + """ + A convenience tool to quickly map Human Gene Symbols to Entrez IDs. + + Args: + symbols: List of gene symbols (e.g., ["TP53", "APOE"]). + """ + if not symbols: + return {"error": "No symbols provided."} + + r_keys = 'c("' + '","'.join(symbols) + '")' + script = f""" + res <- select(org.hs.eg.db, keys = {r_keys}, columns = c("ENTREZID"), keytype = "SYMBOL") + cat(toJSON(res, pretty = TRUE)) + """ + return run_r_command(script) + +@mcp.tool() +def org_hs_eg_db_get_keys( + keytype: str = "SYMBOL", + pattern: str = "", + limit: int = 100 +) -> Dict[str, Any]: + """ + Retrieve a list of all valid keys of a specific type, optionally filtered by a pattern. + + Args: + keytype: The type of keys to retrieve (e.g., "SYMBOL", "ENSEMBL"). + pattern: A string pattern to filter keys (uses grep-style matching). + limit: Maximum number of keys to return to prevent overwhelming output. + """ + if limit <= 0: + limit = 100 + + script = f""" + all_keys <- keys(org.hs.eg.db, keytype = "{keytype}") + if ("{pattern}" != "") {{ + all_keys <- all_keys[grep("{pattern}", all_keys)] + }} + res <- head(all_keys, {limit}) + cat(toJSON(res)) + """ + return run_r_command(script) + +@mcp.tool() +def org_hs_eg_db_metadata() -> Dict[str, Any]: + """ + Get metadata about the org.hs.eg.db package, including version, organism, and data sources. + """ + script = """ + res <- metadata(org.hs.eg.db) + cat(toJSON(res, pretty = TRUE)) + """ + return run_r_command(script) + +@mcp.tool() +def org_hs_eg_db_map_ids( + ids: List[str], + from_type: str, + to_type: str +) -> Dict[str, Any]: + """ + Generic tool to map identifiers from one type to another. + + Args: + ids: List of input identifiers. + from_type: The source identifier type (e.g., "ENSEMBL"). + to_type: The target identifier type (e.g., "SYMBOL"). + """ + if not ids: + return {"error": "No IDs provided."} + + r_keys = 'c("' + '","'.join(ids) + '")' + script = f""" + res <- select(org.hs.eg.db, keys = {r_keys}, columns = c("{to_type}"), keytype = "{from_type}") + cat(toJSON(res, pretty = TRUE)) + """ + return run_r_command(script) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f13bc6c9b6c6b4bf2f8d9bfce633ca7d8a2a8b4d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_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-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_org_hs_eg_db' + + +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/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4eb289ab819090371a3aacbde6c3d48a7e26bd78 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-org.hs.eg.db: + build: . + image: mcp-bioconductor-org.hs.eg.db:latest + container_name: mcp-bioconductor-org.hs.eg.db + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-org.hs.eg.db + 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/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ddb7785c9c4ce5c193d1ada773c1d53f4a86a89 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-org.hs.eg.db + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.hs.eg.db/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4bde49a4d261b08d5cc4b18d0a28d63809e09d28 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/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-org.mm.eg.db via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-org.mm.eg.db -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-org.mm.eg.db_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-org.mm.eg.db_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-org.mm.eg.db_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_server.py b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7f3628aef9ccc1b93406e451d1d07d4ba8cd227e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_server.py @@ -0,0 +1,279 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP.TOOL DECORATOR (should not be included in the final output) +# This is a placeholder for the actual decorator. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +# In a real MCP environment, the following line would be: +# import mcp +# and the decorator would be @mcp.tool() +mcp = type("mcp", (), {"tool": mcp_tool_placeholder}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_org_mm_eg_db' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def org_mm_eg_db_query( + keys: List[str], + keytype: str, + columns: List[str], + output_file: Path, +) -> dict: + """ + Performs an annotation query on the org.Mm.eg.db database. + + This tool uses the AnnotationDbi::select function to retrieve annotations + for a given set of keys. It maps identifiers from a specified keytype to + the desired annotation columns. + + Args: + keys: A list of identifiers to query (e.g., ["14189", "14190"]). + keytype: The type of identifier being provided in `keys`. + Use the `org_mm_eg_db_list_keytypes` tool to see available options. + Example: "ENTREZID". + columns: A list of annotation columns to retrieve. + Use the `org_mm_eg_db_list_columns` tool to see available options. + Example: ["SYMBOL", "GENENAME", "GO"]. + output_file: The path to save the resulting annotation table in TSV format. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output file path. + """ + if not keys: + raise ValueError("The 'keys' list cannot be empty.") + if not keytype: + raise ValueError("The 'keytype' parameter cannot be empty.") + if not columns: + raise ValueError("The 'columns' list cannot be empty.") + + # Convert Python lists to R vector strings, e.g., c("item1", "item2") + r_keys = 'c({})'.format(', '.join(f'"{key}"' for key in keys)) + r_columns = 'c({})'.format(', '.join(f'"{col}"' for col in columns)) + + r_script_content = f""" + # Suppress startup messages for cleaner output + suppressPackageStartupMessages(library("AnnotationDbi")) + suppressPackageStartupMessages(library("org.Mm.eg.db")) + + # Define parameters + keys_to_query <- {r_keys} + cols_to_fetch <- {r_columns} + key_type <- "{keytype}" + output_path <- "{output_file}" + + # Perform the query + # Use tryCatch to handle potential errors, like invalid keytypes or columns + results <- tryCatch( + {{ + AnnotationDbi::select( + org.Mm.eg.db, + keys = keys_to_query, + columns = cols_to_fetch, + keytype = key_type + ) + }}, + error = function(e) {{ + stop(paste("AnnotationDbi::select failed:", e$message)) + }} + ) + + # Write the output + write.table( + results, + file = output_path, + sep = "\\t", + row.names = FALSE, + quote = FALSE + ) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Clean up the temporary script file + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + # Clean up the temporary script file even on error + Path(script_path).unlink() + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + + +@mcp.tool() +def org_mm_eg_db_list_columns() -> dict: + """ + Lists all available annotation columns in the org.Mm.eg.db database. + + These column names can be used in the `columns` parameter of the + `org_mm_eg_db_query` tool. + + Returns: + A dictionary containing the command executed and a list of available columns in stdout. + """ + r_script_content = """ + suppressPackageStartupMessages(library("org.Mm.eg.db")) + cat(columns(org.Mm.eg.db), sep = "\\n") + """ + cmd = ["Rscript", "-e", r_script_content] + 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 subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + + +@mcp.tool() +def org_mm_eg_db_list_keytypes() -> dict: + """ + Lists all available keytypes in the org.Mm.eg.db database. + + Keytypes define the type of primary identifiers that can be used for querying + in the `keytype` parameter of the `org_mm_eg_db_query` and + `org_mm_eg_db_list_keys` tools. + + Returns: + A dictionary containing the command executed and a list of available keytypes in stdout. + """ + r_script_content = """ + suppressPackageStartupMessages(library("org.Mm.eg.db")) + cat(keytypes(org.Mm.eg.db), sep = "\\n") + """ + cmd = ["Rscript", "-e", r_script_content] + 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 subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + + +@mcp.tool() +def org_mm_eg_db_list_keys( + keytype: str, + output_file: Optional[Path] = None, +) -> dict: + """ + Lists all primary keys for a given keytype from the org.Mm.eg.db database. + + Args: + keytype: The type of identifiers to retrieve. Use the + `org_mm_eg_db_list_keytypes` tool to see available options. + output_file: Optional. If provided, saves the list of keys to this file, + one key per line. Otherwise, keys are printed to stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output file path if provided. + """ + if not keytype: + raise ValueError("The 'keytype' parameter cannot be empty.") + + if output_file: + r_script_content = f""" + suppressPackageStartupMessages(library("org.Mm.eg.db")) + key_type <- "{keytype}" + output_path <- "{output_file}" + keys_list <- keys(org.Mm.eg.db, keytype = key_type) + write.table( + keys_list, + file = output_path, + col.names = FALSE, + row.names = FALSE, + quote = FALSE + ) + """ + else: + r_script_content = f""" + suppressPackageStartupMessages(library("org.Mm.eg.db")) + key_type <- "{keytype}" + keys_list <- keys(org.Mm.eg.db, keytype = key_type) + cat(keys_list, sep = "\\n") + """ + + cmd = ["Rscript", "-e", r_script_content] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(output_file)] if output_file else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b2d0f3e8593f691a01104e9d119f7bbc9c5ba2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_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-org.mm.eg.db/app/bioconductor-org.mm.eg.db_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_org_mm_eg_db' + + +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/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0fda34df59609c6bfa58fac6b4e3c48b1cf12d84 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-org.mm.eg.db: + build: . + image: mcp-bioconductor-org.mm.eg.db:latest + container_name: mcp-bioconductor-org.mm.eg.db + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-org.mm.eg.db + 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/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e0edb9c821b81883fd437f4d3d385811b12089ee --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-org.mm.eg.db + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-org.mm.eg.db/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-partcnv/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-partcnv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2392c0fa8a90d8e6ef61d8d170fd1a152c4d14e8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-partcnv/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-partcnv via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-partcnv -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-partcnv_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-partcnv_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-partcnv_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-partcnv/app/bioconductor-partcnv_server.py b/Biomni/mcp_generated/mcp_bioconductor-partcnv/app/bioconductor-partcnv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b4fc7f4569eeda00b863ef89637ffb4d3ea32fc8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-partcnv/app/bioconductor-partcnv_server.py @@ -0,0 +1,285 @@ +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_partcnv' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def partcnv_classify( + input_rds: str, + output_rds: str, + region: str, + cnv_type: str, + reference_column: str, + reference_label: str, + annotation_hub_id: str = "AH107301", + assay: str = "RNA", + slot: str = "counts", + max_iter: int = 100, + epsilon: float = 1e-5, +) -> Dict[str, Any]: + """ + Perform aneuploidy classification using the partCNV EM algorithm. + + This tool uses a statistical framework (EM algorithm with Poisson mixtures) + to detect aneuploid cells with local copy number deletion or amplification + based on single-cell RNA-seq data. + + Args: + input_rds: Path to the input Seurat or SingleCellExperiment object (RDS format). + output_rds: Path where the classification results (RDS) will be saved. + region: The cytoband region to analyze (e.g., "1q", "chr1p"). + cnv_type: Type of CNV to detect. Must be 'deletion' or 'amplification'. + reference_column: Metadata column name used to identify reference (normal) cells. + reference_label: The value in reference_column that identifies the reference cells. + annotation_hub_id: AnnotationHub ID for gene coordinates (default "AH107301" for GRCh38). + assay: Assay name to extract data from (for Seurat objects). + slot: Slot name to extract data from (for Seurat objects). + max_iter: Maximum number of iterations for the EM algorithm. + epsilon: Convergence tolerance for the EM algorithm. + """ + # Input validation + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + if cnv_type not in ["deletion", "amplification"]: + return {"error": "cnv_type must be either 'deletion' or 'amplification'"} + + # Create output directory if it doesn't exist + output_path = Path(output_rds) + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Construct R script + r_script = f""" + library(partCNV) + library(Seurat) + library(SingleCellExperiment) + + # Load object + obj <- readRDS("{input_rds}") + + # Extract counts and metadata + if (inherits(obj, "Seurat")) {{ + counts <- GetAssayData(obj, assay = "{assay}", slot = "{slot}") + meta <- obj@meta.data + }} else if (inherits(obj, "SingleCellExperiment")) {{ + counts <- counts(obj) + meta <- as.data.frame(colData(obj)) + }} else {{ + stop("Input must be a Seurat or SingleCellExperiment object") + }} + + # Identify reference cells + if (!("{reference_column}" %in% colnames(meta))) {{ + stop(paste("Column", "{reference_column}", "not found in metadata")) + }} + + ref_idx <- which(meta[["{reference_column}"]] == "{reference_label}") + if (length(ref_idx) == 0) {{ + stop("No reference cells found with the specified label") + }} + + # Run partCNV + results <- partCNV( + dat = as.matrix(counts), + region = "{region}", + type = "{cnv_type}", + reference = ref_idx, + max_iter = {max_iter}, + epsilon = {epsilon}, + annotation_hub_id = "{annotation_hub_id}" + ) + + # Save results + saveRDS(results, "{output_rds}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + 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.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed" + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + + +@mcp.tool() +def partcnvh_classify( + input_rds: str, + output_rds: str, + region: str, + cnv_type: str, + reference_column: str, + reference_label: str, + annotation_hub_id: str = "AH107301", + assay: str = "RNA", + slot: str = "counts", + max_iter: int = 100, + epsilon: float = 1e-5, +) -> Dict[str, Any]: + """ + Perform aneuploidy classification using the partCNVH algorithm (EM + HMM). + + This tool improves classification accuracy by integrating a Hidden Markov Model (HMM) + for feature selection within the partCNV framework. + + Args: + input_rds: Path to the input Seurat or SingleCellExperiment object (RDS format). + output_rds: Path where the classification results (RDS) will be saved. + region: The cytoband region to analyze (e.g., "1q", "chr1p"). + cnv_type: Type of CNV to detect. Must be 'deletion' or 'amplification'. + reference_column: Metadata column name used to identify reference (normal) cells. + reference_label: The value in reference_column that identifies the reference cells. + annotation_hub_id: AnnotationHub ID for gene coordinates (default "AH107301" for GRCh38). + assay: Assay name to extract data from (for Seurat objects). + slot: Slot name to extract data from (for Seurat objects). + max_iter: Maximum number of iterations for the EM algorithm. + epsilon: Convergence tolerance for the EM algorithm. + """ + # Input validation + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + if cnv_type not in ["deletion", "amplification"]: + return {"error": "cnv_type must be either 'deletion' or 'amplification'"} + + # Create output directory if it doesn't exist + output_path = Path(output_rds) + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Construct R script + r_script = f""" + library(partCNV) + library(Seurat) + library(SingleCellExperiment) + + # Load object + obj <- readRDS("{input_rds}") + + # Extract counts and metadata + if (inherits(obj, "Seurat")) {{ + counts <- GetAssayData(obj, assay = "{assay}", slot = "{slot}") + meta <- obj@meta.data + }} else if (inherits(obj, "SingleCellExperiment")) {{ + counts <- counts(obj) + meta <- as.data.frame(colData(obj)) + }} else {{ + stop("Input must be a Seurat or SingleCellExperiment object") + }} + + # Identify reference cells + if (!("{reference_column}" %in% colnames(meta))) {{ + stop(paste("Column", "{reference_column}", "not found in metadata")) + }} + + ref_idx <- which(meta[["{reference_column}"]] == "{reference_label}") + if (length(ref_idx) == 0) {{ + stop("No reference cells found with the specified label") + }} + + # Run partCNVH + results <- partCNVH( + dat = as.matrix(counts), + region = "{region}", + type = "{cnv_type}", + reference = ref_idx, + max_iter = {max_iter}, + epsilon = {epsilon}, + annotation_hub_id = "{annotation_hub_id}" + ) + + # Save results + saveRDS(results, "{output_rds}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + 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.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed" + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + + +@mcp.tool() +def get_partcnv_gene_info( + annotation_hub_id: str = "AH107301", +) -> Dict[str, Any]: + """ + Retrieve gene coordinate information used by partCNV from AnnotationHub. + + Args: + annotation_hub_id: AnnotationHub ID for gene coordinates (default "AH107301" for GRCh38). + """ + r_script = f""" + library(partCNV) + library(AnnotationHub) + + ah <- AnnotationHub() + gene_info <- ah[["{annotation_hub_id}"]] + + # Convert to a simple data frame for output + df <- as.data.frame(gene_info) + write.csv(df, stdout(), row.names = FALSE) + """ + + try: + cmd = ["Rscript", "-e", r_script] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "info": "Gene information retrieved successfully" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve gene information" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-partcnv/app/bioconductor-partcnv_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-partcnv/app/bioconductor-partcnv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc75e1feeee8f562c86fe6d7461f7a8848996e3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-partcnv/app/bioconductor-partcnv_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-partcnv/app/bioconductor-partcnv_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_partcnv' + + +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/Biomni/mcp_generated/mcp_bioconductor-partcnv/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-partcnv/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-partcnv/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-partcnv/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-partcnv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a8803ce64509d3ab126b15479ead245bf8dbda6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-partcnv/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-partcnv: + build: . + image: mcp-bioconductor-partcnv:latest + container_name: mcp-bioconductor-partcnv + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-partcnv + 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/Biomni/mcp_generated/mcp_bioconductor-partcnv/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-partcnv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2bb095e25d5549b30ab3c87cf85405b350c5ec60 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-partcnv/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-partcnv + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-partcnv/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-partcnv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-partcnv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-phemd/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-phemd/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5d64bfc9fbcdf57b66b8b29d69a8daf28afcedea --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phemd/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-phemd via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-phemd -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-phemd_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-phemd_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-phemd_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-phemd/app/bioconductor-phemd_server.py b/Biomni/mcp_generated/mcp_bioconductor-phemd/app/bioconductor-phemd_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1ee223cd7d38c3f06a91d427e094665296ba059b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phemd/app/bioconductor-phemd_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 dynamically supplied by the MCP server environment. +# It is not included here directly. +# from mcp import tool as mcp_tool + +class mcp: + """A dummy class for local development and type hinting.""" + @staticmethod + def tool(func): + return func + +@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, + vanilla: bool = False, + save: bool = False, + restore: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: 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 Rscript, allowing execution of R code either + from a script file or directly from one or more string expressions. It provides + comprehensive control over the R session environment. + + Args: + 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 'file'. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, enables verbose output, printing progress information. + default_packages: A comma-separated string of R package names to be loaded by default. + vanilla: If True, runs R in a "vanilla" session. This is a shortcut for enabling + --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + If set to True, it overrides the individual save, restore, and init file flags. + save: If True, the workspace is saved at the end of the session. Ignored if 'vanilla' is True. + restore: If True, previously saved objects are restored at startup. Ignored if 'vanilla' is True. + no_environ: If True, site and user environment files are not read. Ignored if 'vanilla' is True. + no_site_file: If True, the site-wide Rprofile is not read. Ignored if 'vanilla' is True. + no_init_file: If True, the user's R profile is not read. 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 file and not expressions: + raise ValueError("Either an R script 'file' or a list of 'expressions' must be provided.") + if file and expressions: + raise ValueError("The 'file' and 'expressions' parameters are mutually exclusive.") + + if file: + if not file.is_file(): + raise FileNotFoundError(f"Input R script file not found: {file}") + + # 2. Command Construction + cmd = ["Rscript"] + + # The --vanilla flag is a shortcut that takes precedence over individual session flags. + if vanilla: + cmd.append("--vanilla") + else: + if save: + cmd.append("--save") + if restore: + cmd.append("--restore") + 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 verbose: + cmd.append("--verbose") + + if default_packages: + # Basic validation for comma-separated list format + if not all(pkg.strip() for pkg in default_packages.split(',')): + raise ValueError("'default_packages' must be a non-empty, comma-separated string.") + cmd.extend(["--default-packages", default_packages]) + + # Add the primary execution target: either expressions or a file + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + elif file: + cmd.append(str(file)) + + # Add any arguments intended for the R script itself + if script_args: + cmd.extend(script_args) + + # 3. Subprocess Execution + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + 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: + 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 itself does not have a defined output file; any file creation is determined + # by the R code being executed. Therefore, output_files is returned as an empty list. + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-phemd/app/bioconductor-phemd_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-phemd/app/bioconductor-phemd_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fe0d33e7af80829d410fdeee12576ddeb617d5a6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phemd/app/bioconductor-phemd_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-phemd/app/bioconductor-phemd_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_phemd' + + +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/Biomni/mcp_generated/mcp_bioconductor-phemd/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-phemd/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f82513ed1769a4b84a85581aaaacf609b91acc19 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phemd/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-phemd: + build: . + image: mcp-bioconductor-phemd:latest + container_name: mcp-bioconductor-phemd + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-phemd + 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/Biomni/mcp_generated/mcp_bioconductor-phemd/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-phemd/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..700f5ac3e3d4b4a8d8d5a4f369e9b148ababb84b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phemd/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-phemd + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-phemd/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-phemd/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phemd/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-phyloseq/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..75db8224da29a94ca004d7668ccd14ab76761985 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..de5c022f375daf37b507c6461ee11963395b66f6 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..92e5fe3c51cc4cccf5f2416eb31cf52e72af16cf --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-phyloseq/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-phyloseq/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f70d5fe54b0cf376d184210a9c9bf06752bc860f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-phyloseq: + build: . + image: mcp-bioconductor-phyloseq:latest + container_name: mcp-bioconductor-phyloseq + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-phyloseq + 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/Biomni/mcp_generated/mcp_bioconductor-phyloseq/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b6a6cb6a9f073e4b999a55077507a89e1ea63570 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-phyloseq + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-phyloseq/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-phyloseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-pipecomp/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-pipecomp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4c3b71edffcd345c21c6f37e6f6f21332b953637 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py b/Biomni/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa5b87e02ba06fd4d72537ebcc076ef4e951b2b --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ef9eae8218d25a4cc52e0f485ed2d1d0efdae852 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-pipecomp/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-pipecomp/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-pipecomp/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-pipecomp/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-pipecomp/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7599e9b748eed80975ee6f04120a79cf1925b687 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-pipecomp/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-pipecomp/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cdbee95fc4c5b30346a0d26886ab7fe09ab0a168 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-pipecomp/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-pipecomp/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-pipecomp/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-poem/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-poem/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..553c1706098fba4d10920b0f15ee917c7b3a6ee8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-poem/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-poem via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-poem -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-poem_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-poem_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-poem_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-poem/app/bioconductor-poem_server.py b/Biomni/mcp_generated/mcp_bioconductor-poem/app/bioconductor-poem_server.py new file mode 100644 index 0000000000000000000000000000000000000000..00e10a578079e6d55f14328fe26df6de04f81ea3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-poem/app/bioconductor-poem_server.py @@ -0,0 +1,237 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# This is a mock decorator for development and testing purposes. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_poem' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def poem_evaluate( + clustering_results: Path, + output_prefix: str, + ground_truth_labels: Optional[Path] = None, + spatial_coordinates: Optional[Path] = None, + embedding_coordinates: Optional[Path] = None, + calculate_external_metrics: bool = True, + calculate_internal_metrics: bool = True, + calculate_spatial_metrics: bool = True, + generate_spatial_error_plot: bool = False, +) -> Dict: + """ + Run POpulation-based Evaluation Metrics (poem) analysis on clustering or spatial domain results. + + This tool serves as a wrapper for the Bioconductor 'poem' R package. It generates and executes an R script + to calculate various evaluation metrics based on the provided input files. Since 'poem' is an R library + and not a command-line tool, this function synthesizes a command-line-like interface to its core functionalities. + + Args: + clustering_results: Path to a single-column file (CSV/TSV, no header) containing cluster assignments for each cell/spot. + output_prefix: A string prefix for all output files (e.g., 'my_analysis'). + ground_truth_labels: Optional path to a single-column file with ground truth labels for external validation. + spatial_coordinates: Optional path to a two-column file (CSV/TSV, no header) with X and Y spatial coordinates. + embedding_coordinates: Optional path to a multi-column file (CSV/TSV, no header) with embedding coordinates (e.g., UMAP, PCA). + calculate_external_metrics: If True, calculate external metrics like ARI. Requires `ground_truth_labels`. + calculate_internal_metrics: If True, calculate internal metrics like Silhouette score. Requires `embedding_coordinates` or `spatial_coordinates`. + calculate_spatial_metrics: If True, calculate spatial-aware metrics. Requires `spatial_coordinates`. + generate_spatial_error_plot: If True, generate a plot visualizing spatial errors. Requires `spatial_coordinates` and `ground_truth_labels`. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # --- 1. Input Validation --- + if not clustering_results.is_file(): + raise FileNotFoundError(f"Clustering results file not found: {clustering_results}") + if ground_truth_labels and not ground_truth_labels.is_file(): + raise FileNotFoundError(f"Ground truth labels file not found: {ground_truth_labels}") + if spatial_coordinates and not spatial_coordinates.is_file(): + raise FileNotFoundError(f"Spatial coordinates file not found: {spatial_coordinates}") + if embedding_coordinates and not embedding_coordinates.is_file(): + raise FileNotFoundError(f"Embedding coordinates file not found: {embedding_coordinates}") + + if calculate_external_metrics and not ground_truth_labels: + raise ValueError("`ground_truth_labels` must be provided to calculate external metrics.") + if (calculate_spatial_metrics or generate_spatial_error_plot) and not spatial_coordinates: + raise ValueError("`spatial_coordinates` must be provided for spatial metrics or plots.") + if calculate_internal_metrics and not (embedding_coordinates or spatial_coordinates): + raise ValueError("Either `embedding_coordinates` or `spatial_coordinates` must be provided for internal metrics.") + + # --- 2. Temporary Directory and Script Generation --- + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + r_script_path = temp_dir / "run_poem.R" + output_metrics_path = temp_dir / f"{output_prefix}_metrics.csv" + output_plot_path = temp_dir / f"{output_prefix}_spatial_error.png" + + # NOTE: The R function names (`calculateExternalMetrics`, `plotSpatialErrors`, etc.) are plausible + # placeholders based on the package's description, as the exact function names are not available + # in the provided documentation. This script demonstrates a robust way to wrap such a library. + r_script_content = f""" + options(warn = -1) + suppressPackageStartupMessages({{ + library(poem) + library(SpatialExperiment) + library(SummarizedExperiment) + library(ggplot2) + }}) + + cat("--- Loading Data ---\\n") + clusters <- read.csv('{clustering_results.resolve()}', header = FALSE, col.names = c('cluster'))$cluster + + metrics_list <- list() + + # --- Create a base data object (SummarizedExperiment or SpatialExperiment) --- + sce <- NULL + if (!is.null('{spatial_coordinates.resolve() if spatial_coordinates else ''}') || !is.null('{embedding_coordinates.resolve() if embedding_coordinates else ''}')) {{ + counts <- matrix(0, nrow = 1, ncol = length(clusters)) # Dummy assay + colData <- data.frame(cluster_id = as.factor(clusters)) + + if (!is.null('{spatial_coordinates.resolve() if spatial_coordinates else ''}')) {{ + spatial_coords <- as.matrix(read.csv('{spatial_coordinates.resolve()}', header = FALSE)) + colnames(spatial_coords) <- c('x', 'y') + sce <- SpatialExperiment(assays = list(counts = counts), colData = colData, spatialCoords = spatial_coords) + cat("Created SpatialExperiment object.\\n") + }} else {{ + sce <- SummarizedExperiment(assays = list(counts = counts), colData = colData) + embedding_coords <- as.matrix(read.csv('{embedding_coordinates.resolve()}', header = FALSE)) + reducedDim(sce, "embedding") <- embedding_coords + cat("Created SummarizedExperiment object with embeddings.\\n") + }} + }} + + # --- External Metrics --- + if ({str(calculate_external_metrics).upper()}) {{ + cat("\\n--- Calculating External Metrics ---\\n") + ground_truth <- read.csv('{ground_truth_labels.resolve()}', header = FALSE, col.names = c('label'))$label + # Using a known function from 'aricode' which 'poem' imports + external_metrics <- aricode::clustComp(clusters, ground_truth) + metrics_list[['external']] <- external_metrics + cat("External metrics calculated.\\n") + }} + + # --- Internal & Spatial Metrics --- + if (!is.null(sce)) {{ + if ({str(calculate_internal_metrics).upper()}) {{ + cat("\\n--- Calculating Internal Metrics ---\\n") + # Using a known function from 'bluster' which 'poem' imports + dist_matrix <- dist(if (!is.null(reducedDim(sce, "embedding"))) reducedDim(sce, "embedding") else spatialCoords(sce)) + silhouette_scores <- cluster::silhouette(as.integer(sce$cluster_id), dist_matrix) + # Handle potential NaN from single-cluster cases + mean_silhouette <- if(is.nan(mean(silhouette_scores[,3]))) 0 else mean(silhouette_scores[,3]) + metrics_list[['internal']] <- list(mean_silhouette = mean_silhouette) + cat("Internal metrics calculated.\\n") + }} + if ({str(calculate_spatial_metrics).upper()} && inherits(sce, "SpatialExperiment")) {{ + cat("\\n--- Calculating Spatial Metrics ---\\n") + # Hypothetical function call for a spatial metric like Moran's I + # This requires more setup (spatial weights matrix), so we'll use a placeholder. + # In a real scenario, this would call a specific function from 'poem' or 'spdep'. + metrics_list[['spatial']] <- list(morans_i_placeholder = runif(1)) + cat("Spatial metrics calculated (using placeholder).\\n") + }} + }} + + # --- Combine and Save Metrics --- + if (length(metrics_list) > 0) {{ + cat("\\n--- Saving Metrics ---\\n") + results_df <- data.frame( + metric = unlist(lapply(metrics_list, names)), + value = unlist(metrics_list), + category = rep(names(metrics_list), sapply(metrics_list, length)) + ) + write.csv(results_df, file = '{output_metrics_path}', row.names = FALSE) + cat("Metrics saved to {output_metrics_path}\\n") + }} + + # --- Visualization --- + if ({str(generate_spatial_error_plot).upper()} && inherits(sce, "SpatialExperiment") && !is.null('{ground_truth_labels.resolve() if ground_truth_labels else ''}')) {{ + cat("\\n--- Generating Spatial Error Plot ---\\n") + ground_truth <- read.csv('{ground_truth_labels.resolve()}', header = FALSE, col.names = c('label'))$label + colData(sce)$ground_truth <- as.factor(ground_truth) + + # Create a plot showing disagreement + plot_data <- as.data.frame(cbind(spatialCoords(sce), colData(sce))) + plot_data$agreement <- ifelse(plot_data$cluster_id == plot_data$ground_truth, "Agree", "Disagree") + + p <- ggplot(plot_data, aes(x = x, y = y, color = agreement)) + + geom_point(size = 2) + + scale_color_manual(values = c("Agree" = "gray", "Disagree" = "red")) + + theme_bw() + + labs(title = "Spatial Disagreement Plot", x = "X coordinate", y = "Y coordinate") + + ggsave('{output_plot_path}', plot = p, width = 8, height = 6) + cat("Spatial error plot saved to {output_plot_path}\\n") + }} + + cat("\\n--- poem analysis script finished ---\\n") + """ + + with open(r_script_path, "w") as f: + f.write(r_script_content) + + # --- 3. Subprocess Execution --- + command = ["Rscript", str(r_script_path)] + command_str = " ".join(map(str, command)) + logger.info(f"Executing command: {command_str}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=temp_dir, + ) + except FileNotFoundError: + # This error is for when 'Rscript' itself is not found + raise RuntimeError("Rscript executable not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # This error is for when the R script fails + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Stderr:\n{e.stderr}\n" + f"Stdout:\n{e.stdout}" + ) + logger.error(error_message) + # Return a structured error in the MCP format + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + + # --- 4. Collect and Return Structured Output --- + output_files = [] + if output_metrics_path.exists() and output_metrics_path.stat().st_size > 0: + output_files.append(str(output_metrics_path)) + if output_plot_path.exists() and output_plot_path.stat().st_size > 0: + output_files.append(str(output_plot_path)) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-poem/app/bioconductor-poem_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-poem/app/bioconductor-poem_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5130cbff80b4d7fac55a35c1dd07ec607f41d272 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-poem/app/bioconductor-poem_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-poem/app/bioconductor-poem_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_poem' + + +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/Biomni/mcp_generated/mcp_bioconductor-poem/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-poem/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-poem/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-poem/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-poem/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0f7e7e8be4a0b810e1a47921ac69940fb287553a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-poem/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-poem: + build: . + image: mcp-bioconductor-poem:latest + container_name: mcp-bioconductor-poem + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-poem + 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/Biomni/mcp_generated/mcp_bioconductor-poem/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-poem/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b3c239e7ecff5c3697ec3fc78557bf7babec05f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-poem/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-poem + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-poem/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-poem/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-poem/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a575fb7871cf3df2022dfe794a043ce28ce6f649 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/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-preprocesscore via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-preprocesscore -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-preprocesscore_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-preprocesscore_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-preprocesscore_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5843e85775c1b27003df4b229a2a65e1198d779a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py @@ -0,0 +1,340 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List +import tempfile + +def run_r_command(script_content: str): + """Helper to execute R code and handle errors.""" + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write("library(preprocessCore)\n") + tmp.write(script_content) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return result.stdout, result.stderr + except subprocess.CalledProcessError as e: + raise RuntimeError(f"R execution failed: {e.stderr}\nStdout: {e.stdout}") + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_preprocesscore' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def preprocesscore_normalize_quantiles( + input_file: str, + output_file: str, + keep_names: bool = True, + sep: str = ",", + header: bool = True +): + """ + Perform Quantile Normalization on a numeric matrix. + + Args: + input_file: Path to the input CSV/TSV file containing the matrix. + output_file: Path where the normalized matrix will be saved. + keep_names: Whether to preserve row and column names in the output. + sep: Delimiter used in the input file (e.g., ',' or '\t'). + header: Whether the input file has a header row. + """ + input_path = Path(input_file) + output_path = Path(output_file) + + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_script = f""" + data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}")) + normalized_data <- normalize.quantiles(data, keep.names={str(keep_names).upper()}) + write.table(normalized_data, "{output_path}", sep="{sep}", col.names={str(header).upper()}, row.names=TRUE, quote=FALSE) + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "normalize.quantiles", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def preprocesscore_normalize_quantiles_robust( + input_file: str, + output_file: str, + remove_extreme: str = "both", + n_remove: int = 1, + use_log2: bool = False, + sep: str = ",", + header: bool = True +): + """ + Perform Robust Quantile Normalization. + + Args: + input_file: Path to the input CSV/TSV file. + output_file: Path for the output file. + remove_extreme: How to remove outliers: 'none', 'left', 'right', or 'both'. + n_remove: Number of extreme values to remove. + use_log2: Whether to apply log2 transformation before normalization. + sep: Delimiter used in the input file. + header: Whether the input file has a header row. + """ + input_path = Path(input_file) + output_path = Path(output_file) + + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + if remove_extreme not in ["none", "left", "right", "both"]: + return {"error": "remove_extreme must be one of: none, left, right, both"} + + r_script = f""" + data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}")) + normalized_data <- normalize.quantiles.robust( + data, + remove.extreme="{remove_extreme}", + n.remove={n_remove}, + use.log2={str(use_log2).upper()} + ) + write.table(normalized_data, "{output_path}", sep="{sep}", col.names={str(header).upper()}, row.names=TRUE, quote=FALSE) + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "normalize.quantiles.robust", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def preprocesscore_background_correct( + input_file: str, + output_file: str, + method: str = "rma", + sep: str = ",", + header: bool = True +): + """ + Perform background correction on a matrix of intensities. + + Args: + input_file: Path to the input CSV/TSV file. + output_file: Path for the output file. + method: Correction method (typically 'rma'). + sep: Delimiter used in the input file. + header: Whether the input file has a header row. + """ + input_path = Path(input_file) + output_path = Path(output_file) + + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_script = f""" + data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}")) + corrected_data <- background.correct(data, method="{method}") + write.table(corrected_data, "{output_path}", sep="{sep}", col.names={str(header).upper()}, row.names=TRUE, quote=FALSE) + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": f"background.correct(method='{method}')", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def preprocesscore_sub_col_summarize_median_polish( + input_file: str, + output_file: str, + group_labels: List[int], + sep: str = ",", + header: bool = True +): + """ + Summarize columns of a matrix using Median Polish based on group labels. + + Args: + input_file: Path to the input CSV/TSV file. + output_file: Path for the output file. + group_labels: A list of integers representing the group for each column (e.g., [1, 1, 2, 2]). + sep: Delimiter used in the input file. + header: Whether the input file has a header row. + """ + input_path = Path(input_file) + output_path = Path(output_file) + + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + # Convert Python list to R vector string + r_groups = f"c({','.join(map(str, group_labels))})" + + r_script = f""" + data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}")) + groups <- as.integer({r_groups}) + summarized <- subColSummarizeMedianPolish(data, groups) + write.table(summarized, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "subColSummarizeMedianPolish", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def preprocesscore_sub_col_summarize_log_avg( + input_file: str, + output_file: str, + group_labels: List[int], + sep: str = ",", + header: bool = True +): + """ + Summarize columns of a matrix using Log-Average based on group labels. + + Args: + input_file: Path to the input CSV/TSV file. + output_file: Path for the output file. + group_labels: A list of integers representing the group for each column. + """ + input_path = Path(input_file) + output_path = Path(output_file) + + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_groups = f"c({','.join(map(str, group_labels))})" + + r_script = f""" + data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}")) + groups <- as.integer({r_groups}) + summarized <- subColSummarizeLogAvg(data, groups) + write.table(summarized, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "subColSummarizeLogAvg", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def preprocesscore_sub_col_summarize_log_median( + input_file: str, + output_file: str, + group_labels: List[int], + sep: str = ",", + header: bool = True +): + """ + Summarize columns of a matrix using Log-Median based on group labels. + + Args: + input_file: Path to the input CSV/TSV file. + output_file: Path for the output file. + group_labels: A list of integers representing the group for each column. + """ + input_path = Path(input_file) + output_path = Path(output_file) + + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_groups = f"c({','.join(map(str, group_labels))})" + + r_script = f""" + data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}")) + groups <- as.integer({r_groups}) + summarized <- subColSummarizeLogMedian(data, groups) + write.table(summarized, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "subColSummarizeLogMedian", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def preprocesscore_sub_col_summarize_biweight_midavg( + input_file: str, + output_file: str, + group_labels: List[int], + sep: str = ",", + header: bool = True +): + """ + Summarize columns of a matrix using Biweight Mid-average based on group labels. + + Args: + input_file: Path to the input CSV/TSV file. + output_file: Path for the output file. + group_labels: A list of integers representing the group for each column. + """ + input_path = Path(input_file) + output_path = Path(output_file) + + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_groups = f"c({','.join(map(str, group_labels))})" + + r_script = f""" + data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}")) + groups <- as.integer({r_groups}) + summarized <- subColSummarizeBiweightMidavg(data, groups) + write.table(summarized, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "subColSummarizeBiweightMidavg", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b17c42fb3906d5f8515f158588ed44dd7192c773 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_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-preprocesscore/app/bioconductor-preprocesscore_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_preprocesscore' + + +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/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e344031a5676f11d324f8a07e7dbcf4341d74455 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-preprocesscore: + build: . + image: mcp-bioconductor-preprocesscore:latest + container_name: mcp-bioconductor-preprocesscore + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-preprocesscore + 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/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9a3892f6e80633f97fad970e2fc73523e6b13dc8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-preprocesscore + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-preprocesscore/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..adbf3ebc54fccef2f2bf508538755a4d5a89b24e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py b/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..90b31cb06cbc02c8ee3218b223749aa9db7f4913 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..593b3d2dfe83e0a6468ed0bfffc56b3651c63976 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8ac5970dd6840a7998007627da87e4f60be9c51 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac7f8e4fe821d39719f5a0a64a7123c5d0691d97 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-protgenerics/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-protgenerics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3f2bf309ffe7ffbc844c764b6d238665b9b9f7d6 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py b/Biomni/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..66bf7a1b0ec4d3de2a87d88e5dd02a170b925a2a --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc227bf149b246d7c1f8e2d78cba137dfd42da4 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-protgenerics/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-protgenerics/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..47e13413587e0d6524543a5a4c25700d07c47e08 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-protgenerics/app/requirements.txt @@ -0,0 +1 @@ +mcp==1.27.0 diff --git a/Biomni/mcp_generated/mcp_bioconductor-protgenerics/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-protgenerics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8e1d8d8096c32ba24e5823365e99b8573189e31a --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-protgenerics/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-protgenerics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d17c7b69d3b821e749569b909c88ec485482063c --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-protgenerics/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-protgenerics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..062b47df16d08f6173721af25952519f73dfcafa --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-protgenerics/requirements.txt @@ -0,0 +1,3 @@ +mcp==1.27.0 +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-qvalue/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-qvalue/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..68578d8d110651dfd83095374a2f5205aead0fd1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-qvalue/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-qvalue via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-qvalue -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-qvalue_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-qvalue_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-qvalue_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-qvalue/app/bioconductor-qvalue_server.py b/Biomni/mcp_generated/mcp_bioconductor-qvalue/app/bioconductor-qvalue_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c6d480ed1b78c7522883f33e5331a3dfa1b553f3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-qvalue/app/bioconductor-qvalue_server.py @@ -0,0 +1,226 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def mcp_tool_decorator(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type('mcp', (), {'tool': mcp_tool_decorator}) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_qvalue' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_qvalue( + p_values_file: Path, + output_dir: Path, + output_prefix: str = "qvalue_results", + fdr_level: Optional[float] = None, + pfdr: bool = False, + lfdr_out: bool = True, + pi0_method: str = "smoother", + smooth_df: int = 3, + smooth_log_pi0: bool = False, + lambda_seq: Optional[str] = None, + plot_results: bool = True, +) -> Dict[str, Any]: + """ + Estimates q-values and local FDRs from a list of p-values using the bioconductor-qvalue R package. + + This tool takes a list of p-values and estimates their q-values and local FDR values. + The q-value of a test measures the proportion of false positives incurred (the false + discovery rate) when that particular test is called significant. The local FDR measures + the posterior probability the null hypothesis is true given the test's p-value. + + Args: + p_values_file: Path to a file containing a single column of p-values without a header. + output_dir: Path to the directory where output files will be saved. + output_prefix: Prefix for the output files. + fdr_level: The level at which to control the False Discovery Rate (FDR). Must be between 0 and 1. + pfdr: An indicator of whether the p-values are already sorted (p-value false discovery rate). + lfdr_out: If True, local FDR values will be calculated and included in the output. + pi0_method: Method for estimating pi0, the proportion of true null hypotheses. + Must be one of 'smoother' or 'bootstrap'. + smooth_df: Degrees of freedom to use in the smoother spline fit. Only used if pi0_method is 'smoother'. + smooth_log_pi0: If True and pi0_method is 'smoother', the spline is fit to log(pi0) instead of pi0. + lambda_seq: A comma-separated string of tuning parameter values for pi0 estimation (e.g., "0.1,0.2,0.3"). + If not provided, the default R sequence `seq(0, 0.95, 0.01)` is used. + plot_results: If True, generates a PDF with diagnostic plots. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # 1. Input Validation + if not p_values_file.is_file(): + raise FileNotFoundError(f"Input file not found: {p_values_file}") + + if fdr_level is not None and not (0 <= fdr_level <= 1): + raise ValueError("fdr_level must be between 0 and 1.") + + if pi0_method not in ["smoother", "bootstrap"]: + raise ValueError("pi0_method must be either 'smoother' or 'bootstrap'.") + + if pi0_method == "smoother" and smooth_df < 3: + raise ValueError("smooth_df must be an integer >= 3 when using the 'smoother' method.") + + if lambda_seq: + try: + # Validate that all parts of the comma-separated string are numbers + [float(x) for x in lambda_seq.split(',')] + except ValueError: + raise ValueError("lambda_seq must be a comma-separated string of valid numbers.") + + # 2. File Path Handling + output_dir.mkdir(parents=True, exist_ok=True) + output_prefix_path = output_dir / output_prefix + + # 3. Prepare R script + # Convert Python types to R-compatible strings + r_fdr_level = "NULL" if fdr_level is None else str(fdr_level) + r_pfdr = "TRUE" if pfdr else "FALSE" + r_lfdr_out = "TRUE" if lfdr_out else "FALSE" + r_smooth_log_pi0 = "TRUE" if smooth_log_pi0 else "FALSE" + r_plot_results = "TRUE" if plot_results else "FALSE" + r_lambda_seq = "NULL" if lambda_seq is None else f"c({lambda_seq})" + + r_script_content = f""" + # Load required library + library(qvalue) + + # --- Parameters --- + p_values_file <- "{p_values_file.resolve()}" + output_prefix <- "{output_prefix_path.resolve()}" + + # --- Read Input Data --- + # Using tryCatch for robust error handling on file read + p_values <- tryCatch({{ + read.table(p_values_file, header = FALSE, col.names = c("pvalue"))$pvalue + }}, error = function(e) {{ + stop(paste("Error reading p-values file:", e$message)) + }}) + + # --- Build Argument List for qvalue() --- + qvalue_args <- list( + p = p_values, + fdr.level = {r_fdr_level}, + pfdr = {r_pfdr}, + lfdr.out = {r_lfdr_out}, + pi0.method = "{pi0_method}", + smooth.df = {smooth_df}, + smooth.log.pi0 = {r_smooth_log_pi0} + ) + + # Only add lambda if it was provided by the user to allow R default to be used + r_lambda_val <- {r_lambda_seq} + if (!is.null(r_lambda_val)) {{ + qvalue_args$lambda <- r_lambda_val + }} + + # --- Run qvalue Analysis --- + qobj <- tryCatch({{ + do.call(qvalue, qvalue_args) + }}, error = function(e) {{ + stop(paste("Error during qvalue execution:", e$message)) + }}) + + # --- Save Outputs --- + # 1. Main results table + results_df <- data.frame(p_values = qobj$pvalues, q_values = qobj$qvalues) + if ({r_lfdr_out} && "lfdr" %in% names(qobj) && !is.null(qobj$lfdr)) {{ + results_df$lfdr <- qobj$lfdr + }} + write.table( + results_df, + file = paste0(output_prefix, ".tsv"), + sep = "\\t", + row.names = FALSE, + quote = FALSE + ) + + # 2. Summary file + summary_file <- paste0(output_prefix, "_summary.txt") + sink(summary_file) + print(summary(qobj)) + sink() + + # 3. Plots if requested + if ({r_plot_results}) {{ + pdf(paste0(output_prefix, "_plots.pdf")) + plot(qobj) + dev.off() + }} + """ + + # 4. Subprocess Execution + command = [] + stdout_str, stderr_str = "", "" + output_files: List[str] = [] + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script: + r_script.write(r_script_content) + r_script_path = r_script.name + + command = ["Rscript", r_script_path] + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + # 5. Collect output files + results_tsv = output_prefix_path.with_suffix(".tsv") + if results_tsv.exists(): + output_files.append(str(results_tsv)) + + summary_txt = output_dir / f"{output_prefix}_summary.txt" + if summary_txt.exists(): + output_files.append(str(summary_txt)) + + if plot_results: + plots_pdf = output_prefix_path.with_suffix("_plots.pdf") + if plots_pdf.exists(): + output_files.append(str(plots_pdf)) + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [], + } + except Exception as e: + # Catch other potential errors like file I/O + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": str(e), + "return_code": 1, + "output_files": [], + } + finally: + # Clean up the temporary R script + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + # 6. Return Structured Output + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-qvalue/app/bioconductor-qvalue_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-qvalue/app/bioconductor-qvalue_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1279a3193537cab7bf2351ea0888037c788f2f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-qvalue/app/bioconductor-qvalue_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-qvalue/app/bioconductor-qvalue_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_qvalue' + + +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/Biomni/mcp_generated/mcp_bioconductor-qvalue/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-qvalue/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-qvalue/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-qvalue/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-qvalue/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5fcace032ea1df85f3bedfe442d3c60483ba2189 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-qvalue/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-qvalue: + build: . + image: mcp-bioconductor-qvalue:latest + container_name: mcp-bioconductor-qvalue + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-qvalue + 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/Biomni/mcp_generated/mcp_bioconductor-qvalue/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-qvalue/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e840a1e9a6841c8ba1b594eedc004de5ad52dc0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-qvalue/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-qvalue + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-qvalue/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-qvalue/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-qvalue/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rbgl/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rbgl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..53e2341acd3b052248da950dc9a85edca62d94d0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rbgl/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-rbgl via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rbgl -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-rbgl_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-rbgl_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-rbgl_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py b/Biomni/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..027c8b4f141ddbb6a7163ed87d3b281391f9fef5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py @@ -0,0 +1,137 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# No mcp import needed as per instructions + +# The bioconductor-rbgl package is an R library and does not expose a direct +# command-line interface with subcommands or parameters that can be parsed +# from standard CLI help. The provided documentation confirms this by showing +# an Rscript error and directing users to R-specific documentation (vignettes, +# reference manual) for usage. +# +# To interact with RBGL, one typically writes an R script that loads the +# package and calls its functions. Since the specific R functions, their +# arguments, and return types are not detailed in the provided documentation, +# it is impossible to create individual MCP tools for "EVERY internal functions" +# of the RBGL package. +# +# This MCP tool provides a generic interface to execute R code, allowing users +# to leverage RBGL's functionality by supplying the necessary R script. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_rbgl' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def execute_rbgl_r_code( + r_code: str, + output_file_patterns: Optional[List[str]] = None, + r_args: Optional[List[str]] = None, + working_directory: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes R code that can utilize the Bioconductor RBGL package. + + This tool provides a generic interface to run R scripts that leverage + the RBGL library for graph algorithms. Since RBGL is an R package and + does not expose a direct command-line interface, users are expected + to provide the R code directly. The R code should typically include + `library(RBGL)` to load the package. + + Args: + r_code: A string containing the R code to execute. This code should + include `library(RBGL)` and calls to RBGL functions as needed. + output_file_patterns: An optional list of glob patterns (e.g., "*.csv", "output_*.txt") + to identify and collect output files generated by the R script + within the working directory. + r_args: Optional list of additional arguments to pass to Rscript. + These can be accessed within the R script via `commandArgs(trailingOnly=TRUE)`. + working_directory: Optional path to a directory where the R script + should be executed. If not provided, a temporary + directory will be used. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + a list of any output files generated. + """ + if not r_code: + raise ValueError("R code cannot be empty.") + + command = ["Rscript", "-e", r_code] + + if r_args: + command.extend(r_args) + + output_files: List[Path] = [] + temp_dir: Optional[tempfile.TemporaryDirectory] = None + actual_working_dir: Path + + try: + if working_directory: + if not working_directory.is_dir(): + raise ValueError(f"Working directory '{working_directory}' does not exist or is not a directory.") + actual_working_dir = working_directory + else: + temp_dir = tempfile.TemporaryDirectory() + actual_working_dir = Path(temp_dir.name) + + process = subprocess.run( + command, + cwd=actual_working_dir, + capture_output=True, + text=True, + check=True + ) + + # Collect output files based on provided patterns or list all if no patterns + if output_file_patterns: + for pattern in output_file_patterns: + for f in actual_working_dir.glob(pattern): + if f.is_file(): + output_files.append(f) + else: + # If no patterns, collect all non-hidden files in the working directory + for f in actual_working_dir.iterdir(): + if f.is_file() and not f.name.startswith("."): + output_files.append(f) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(f) for f in output_files] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: Rscript command not found. Is R installed and in PATH?", + "error": "Rscript command not found", + "output_files": [] + } + except ValueError as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": str(e), + "error": "Input validation error", + "output_files": [] + } + finally: + if temp_dir: + temp_dir.cleanup() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a4bcbd638957fe106a6847e91d9575c628f3929d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_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-rbgl/app/bioconductor-rbgl_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rbgl' + + +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/Biomni/mcp_generated/mcp_bioconductor-rbgl/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rbgl/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rbgl/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-rbgl/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rbgl/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..08a18e7897455296f14df20991ebb996529e7791 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rbgl/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rbgl: + build: . + image: mcp-bioconductor-rbgl:latest + container_name: mcp-bioconductor-rbgl + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rbgl + 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/Biomni/mcp_generated/mcp_bioconductor-rbgl/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rbgl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8476e0fe29a2433391cebe3367ae4506229d61e0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rbgl/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rbgl + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rbgl/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rbgl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rbgl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a70a7575b3d2098adb631cc68af8591f602439f8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/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-reactomegsa.data via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-reactomegsa.data -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-reactomegsa.data_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-reactomegsa.data_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-reactomegsa.data_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b745015a1c26661592b7c4de48237bbc4f35b61 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py @@ -0,0 +1,120 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_reactomegsa_data' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def get_citation( + rscript_path: Path = Path("Rscript"), + output_file: Optional[Path] = None, +) -> dict: + """ + Retrieves the citation information for the bioconductor-reactomegsa.data R package. + + This package is a Bioconductor data package for the R environment and does not + expose direct command-line subcommands in the traditional sense. This function + wraps an Rscript call to ensure the package and its manager (BiocManager) are + installed, then loads the package, and finally extracts its citation information. + + Args: + rscript_path: Path to the Rscript executable. Defaults to 'Rscript', + assuming it's in the system's PATH. + output_file: Optional path to save the citation output to a file. + If not provided, the citation will be returned in stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + a list of any output files. + """ + # Validate rscript_path + rscript_executable: str + if not rscript_path.is_absolute(): + try: + # Check if 'Rscript' is in PATH + subprocess.run(["which", "Rscript"], check=True, capture_output=True) + rscript_executable = "Rscript" + except subprocess.CalledProcessError: + raise FileNotFoundError( + f"Rscript not found in system PATH. Please ensure R is installed " + "and Rscript is accessible, or provide an absolute path to Rscript." + ) + elif not rscript_path.is_file(): + raise FileNotFoundError(f"Rscript not found at the specified path: {rscript_path}") + else: + rscript_executable = str(rscript_path) + + # R command to: + # 1. Install BiocManager if not already installed. + # 2. Install ReactomeGSA.data if not already installed (using BiocManager). + # 3. Load the ReactomeGSA.data library. + # 4. Print the citation information. + r_code = ( + 'if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager"); ' + 'if (!require("ReactomeGSA.data", quietly = TRUE)) BiocManager::install("ReactomeGSA.data", update = FALSE, ask = FALSE); ' + 'library(ReactomeGSA.data); ' + 'print(citation("ReactomeGSA.data"))' + ) + + command = [ + rscript_executable, + "-e", + r_code + ] + + stdout_capture = "" + stderr_capture = "" + output_files_list: List[str] = [] + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True + ) + stdout_capture = process.stdout + stderr_capture = process.stderr + + if output_file: + output_file.parent.mkdir(parents=True, exist_ok=True) + output_file.write_text(stdout_capture) + output_files_list.append(str(output_file)) + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Rscript execution failed with exit code {e.returncode}. Stderr: {e.stderr}" + } + except FileNotFoundError as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": str(e), + "output_files": [], + "error": f"Executable not found: {e}" + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": [], + "error": f"An unexpected error occurred: {str(e)}" + } + + return { + "command_executed": " ".join(command), + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files_list + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0d1ff24b3e4c830afe24e4f9f50df4d988ac618a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_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-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_reactomegsa_data' + + +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/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..60dee9c55100465544eb8f835941791188519aa1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-reactomegsa.data: + build: . + image: mcp-bioconductor-reactomegsa.data:latest + container_name: mcp-bioconductor-reactomegsa.data + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-reactomegsa.data + 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/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac58425c4535a7f2f525163a6ee1f38aff304abc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-reactomegsa.data + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-reactomegsa.data/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-regionalst/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-regionalst/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c15f24ba075f7a6d16db8ee68a73783ae7f0e06b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-regionalst/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-regionalst via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-regionalst -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-regionalst_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-regionalst_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-regionalst_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-regionalst/app/bioconductor-regionalst_server.py b/Biomni/mcp_generated/mcp_bioconductor-regionalst/app/bioconductor-regionalst_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9df12ead43fe0701354246247b9bd3bd56b03a8a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-regionalst/app/bioconductor-regionalst_server.py @@ -0,0 +1,467 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Dict, Any + +# MCP decorators are omitted as per the instructions, but would be present in a real MCP file. +# from mcp import tool + +# --- R Script Templates --- +# These strings contain self-contained R scripts that will be executed. +# They use the 'optparse' library to accept command-line arguments. + +REGIONAL_LIMMA_RSCRIPT = """ +# R script to run regionalST::regional_limma +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(regionalST)) +suppressPackageStartupMessages(library(SpatialExperiment)) + +option_list <- list( + make_option(c("-i", "--input_rds"), type="character", help="Path to input SpatialExperiment RDS file."), + make_option(c("-o", "--output_csv"), type="character", help="Path for the output CSV file."), + make_option(c("--col_group"), type="character", help="Column name for grouping variable."), + make_option(c("--group1"), type="character", help="Name of the first group for comparison."), + make_option(c("--group2"), type="character", default=NULL, help="Name of the second group (optional)."), + make_option(c("--col_covariate"), type="character", default=NULL, help="Comma-separated column names for covariates (optional)."), + make_option(c("--n_neighbors"), type="integer", default=6, help="Number of neighbors."), + make_option(c("--log2fc_threshold"), type="double", default=0, help="Log2 fold change threshold."), + make_option(c("--pval_threshold"), type="double", default=1, help="P-value threshold."), + make_option(c("--assay_name"), type="character", default="logcounts", help="Name of the assay to use.") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$input_rds) || is.null(opt$output_csv) || is.null(opt$col_group) || is.null(opt$group1)) { + print_help(opt_parser) + stop("Missing required arguments: --input_rds, --output_csv, --col_group, --group1", call.=FALSE) +} + +spe <- readRDS(opt$input_rds) + +covariates <- NULL +if (!is.null(opt$col_covariate)) { + covariates <- strsplit(opt$col_covariate, ",")[[1]] +} + +results <- regional_limma( + spe = spe, + col_group = opt$col_group, + col_covariate = covariates, + group1 = opt$group1, + group2 = opt$group2, + n_neighbors = opt$n_neighbors, + log2fc_threshold = opt$log2fc_threshold, + pval_threshold = opt$pval_threshold, + assay_name = opt$assay_name +) + +write.csv(as.data.frame(results), file = opt$output_csv, row.names = FALSE) + +cat("regional_limma analysis complete. Results saved to", opt$output_csv, "\\n") +""" + +REGIONAL_VOOM_RSCRIPT = """ +# R script to run regionalST::regional_voom +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(regionalST)) +suppressPackageStartupMessages(library(SpatialExperiment)) + +option_list <- list( + make_option(c("-i", "--input_rds"), type="character", help="Path to input SpatialExperiment RDS file."), + make_option(c("-o", "--output_csv"), type="character", help="Path for the output CSV file."), + make_option(c("--col_group"), type="character", help="Column name for grouping variable."), + make_option(c("--group1"), type="character", help="Name of the first group for comparison."), + make_option(c("--group2"), type="character", default=NULL, help="Name of the second group (optional)."), + make_option(c("--col_covariate"), type="character", default=NULL, help="Comma-separated column names for covariates (optional)."), + make_option(c("--n_neighbors"), type="integer", default=6, help="Number of neighbors."), + make_option(c("--log2fc_threshold"), type="double", default=0, help="Log2 fold change threshold."), + make_option(c("--pval_threshold"), type="double", default=1, help="P-value threshold."), + make_option(c("--assay_name"), type="character", default="counts", help="Name of the assay to use.") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$input_rds) || is.null(opt$output_csv) || is.null(opt$col_group) || is.null(opt$group1)) { + print_help(opt_parser) + stop("Missing required arguments: --input_rds, --output_csv, --col_group, --group1", call.=FALSE) +} + +spe <- readRDS(opt$input_rds) + +covariates <- NULL +if (!is.null(opt$col_covariate)) { + covariates <- strsplit(opt$col_covariate, ",")[[1]] +} + +results <- regional_voom( + spe = spe, + col_group = opt$col_group, + col_covariate = covariates, + group1 = opt$group1, + group2 = opt$group2, + n_neighbors = opt$n_neighbors, + log2fc_threshold = opt$log2fc_threshold, + pval_threshold = opt$pval_threshold, + assay_name = opt$assay_name +) + +write.csv(as.data.frame(results), file = opt$output_csv, row.names = FALSE) + +cat("regional_voom analysis complete. Results saved to", opt$output_csv, "\\n") +""" + +REGIONAL_NONPARAMETRIC_RSCRIPT_TEMPLATE = """ +# R script to run regionalST non-parametric tests +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(regionalST)) +suppressPackageStartupMessages(library(SpatialExperiment)) + +option_list <- list( + make_option(c("-i", "--input_rds"), type="character", help="Path to input SpatialExperiment RDS file."), + make_option(c("-o", "--output_csv"), type="character", help="Path for the output CSV file."), + make_option(c("--col_group"), type="character", help="Column name for grouping variable."), + make_option(c("--group1"), type="character", help="Name of the first group for comparison."), + make_option(c("--group2"), type="character", default=NULL, help="Name of the second group (optional)."), + make_option(c("--n_neighbors"), type="integer", default=6, help="Number of neighbors."), + make_option(c("--log2fc_threshold"), type="double", default=0, help="Log2 fold change threshold."), + make_option(c("--pval_threshold"), type="double", default=1, help="P-value threshold."), + make_option(c("--assay_name"), type="character", default="logcounts", help="Name of the assay to use."), + make_option(c("--test_function"), type="character", help="The R function to call (e.g., 'regional_wilcox').") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$input_rds) || is.null(opt$output_csv) || is.null(opt$col_group) || is.null(opt$group1) || is.null(opt$test_function)) { + print_help(opt_parser) + stop("Missing required arguments: --input_rds, --output_csv, --col_group, --group1, --test_function", call.=FALSE) +} + +spe <- readRDS(opt$input_rds) + +# Dynamically get the function from the regionalST package +test_func <- get(opt$test_function, asNamespace("regionalST")) + +results <- test_func( + spe = spe, + col_group = opt$col_group, + group1 = opt$group1, + group2 = opt$group2, + n_neighbors = opt$n_neighbors, + log2fc_threshold = opt$log2fc_threshold, + pval_threshold = opt$pval_threshold, + assay_name = opt$assay_name +) + +write.csv(as.data.frame(results), file = opt$output_csv, row.names = FALSE) + +cat(paste(opt$test_function, "analysis complete. Results saved to", opt$output_csv, "\\n")) +""" + +def _run_regionalst_script( + script_content: str, + cmd_args: List[str], + output_filename: str +) -> Dict[str, Any]: + """ + Internal helper to execute a regionalST R script. + + This function sets up a temporary environment, writes the provided R script + to a file, executes it with Rscript, and captures the output. It is not + intended to be an MCP tool itself. + + Args: + script_content: A string containing the R script to execute. + cmd_args: A list of command-line arguments for the R script. + output_filename: The name of the output file to be generated. + + Returns: + A dictionary containing execution details and output file paths. + """ + if not shutil.which("Rscript"): + raise RuntimeError( + "Rscript executable not found in system PATH. " + "Please install R and ensure Rscript is accessible." + ) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "run_script.R" + output_csv_path = temp_path / output_filename + + r_script_path.write_text(script_content) + + command = [ + "Rscript", str(r_script_path), + *cmd_args, + "--output_csv", str(output_csv_path) + ] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=temp_path, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results_csv": str(output_csv_path)} + } + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_regionalst' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def regional_limma( + input_rds: Path, + col_group: str, + group1: str, + group2: Optional[str] = None, + col_covariate: Optional[List[str]] = None, + n_neighbors: int = 6, + log2fc_threshold: float = 0.0, + pval_threshold: float = 1.0, + assay_name: str = "logcounts", +) -> Dict[str, Any]: + """ + Performs regional differential expression analysis using limma. + + This function wraps `regional_limma` from the R package `regionalST`, suitable + for analyzing microarray data or transformed RNA-seq data (e.g., log-CPM). + It requires R, Rscript, and the Bioconductor packages `regionalST`, + `SpatialExperiment`, and `optparse` to be installed. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + col_group: The column name in `colData` that defines the groups to compare. + group1: The name of the first group for comparison. + group2: The name of the second group. If not provided, performs a one-vs-all comparison. + col_covariate: List of column names in `colData` to use as covariates. + n_neighbors: The number of nearest neighbors to consider for each spot. + log2fc_threshold: The log2 fold change threshold for determining significance. + pval_threshold: The p-value threshold for determining significance. + assay_name: The name of the assay in the SpatialExperiment object to use. + + Returns: + A dictionary with the command, stdout, stderr, and output CSV file path. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if not (0.0 <= pval_threshold <= 1.0): + raise ValueError("pval_threshold must be between 0.0 and 1.0.") + + cmd_args = [ + "--input_rds", str(input_rds), + "--col_group", col_group, + "--group1", group1, + "--n_neighbors", str(n_neighbors), + "--log2fc_threshold", str(log2fc_threshold), + "--pval_threshold", str(pval_threshold), + "--assay_name", assay_name, + ] + if group2: + cmd_args.extend(["--group2", group2]) + if col_covariate: + cmd_args.extend(["--col_covariate", ",".join(col_covariate)]) + + return _run_regionalst_script( + script_content=REGIONAL_LIMMA_RSCRIPT, + cmd_args=cmd_args, + output_filename="regional_limma_results.csv" + ) + +@mcp.tool() +def regional_voom( + input_rds: Path, + col_group: str, + group1: str, + group2: Optional[str] = None, + col_covariate: Optional[List[str]] = None, + n_neighbors: int = 6, + log2fc_threshold: float = 0.0, + pval_threshold: float = 1.0, + assay_name: str = "counts", +) -> Dict[str, Any]: + """ + Performs regional differential expression analysis using voom. + + This function wraps `regional_voom` from `regionalST`, suitable for RNA-seq + count data. It requires R, Rscript, and the Bioconductor packages `regionalST`, + `SpatialExperiment`, and `optparse` to be installed. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + col_group: The column name in `colData` that defines the groups to compare. + group1: The name of the first group for comparison. + group2: The name of the second group. If not provided, performs a one-vs-all comparison. + col_covariate: List of column names in `colData` to use as covariates. + n_neighbors: The number of nearest neighbors to consider for each spot. + log2fc_threshold: The log2 fold change threshold for determining significance. + pval_threshold: The p-value threshold for determining significance. + assay_name: The name of the assay containing raw counts. + + Returns: + A dictionary with the command, stdout, stderr, and output CSV file path. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if not (0.0 <= pval_threshold <= 1.0): + raise ValueError("pval_threshold must be between 0.0 and 1.0.") + + cmd_args = [ + "--input_rds", str(input_rds), + "--col_group", col_group, + "--group1", group1, + "--n_neighbors", str(n_neighbors), + "--log2fc_threshold", str(log2fc_threshold), + "--pval_threshold", str(pval_threshold), + "--assay_name", assay_name, + ] + if group2: + cmd_args.extend(["--group2", group2]) + if col_covariate: + cmd_args.extend(["--col_covariate", ",".join(col_covariate)]) + + return _run_regionalst_script( + script_content=REGIONAL_VOOM_RSCRIPT, + cmd_args=cmd_args, + output_filename="regional_voom_results.csv" + ) + +@mcp.tool() +def regional_wilcox( + input_rds: Path, + col_group: str, + group1: str, + group2: Optional[str] = None, + n_neighbors: int = 6, + log2fc_threshold: float = 0.0, + pval_threshold: float = 1.0, + assay_name: str = "logcounts", +) -> Dict[str, Any]: + """ + Performs regional DE analysis using the Wilcoxon rank-sum test. + + This function wraps `regional_wilcox` from `regionalST`, a non-parametric test. + It requires R, Rscript, and the Bioconductor packages `regionalST`, + `SpatialExperiment`, and `optparse` to be installed. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + col_group: The column name in `colData` that defines the groups to compare. + group1: The name of the first group for comparison. + group2: The name of the second group. If not provided, performs a one-vs-all comparison. + n_neighbors: The number of nearest neighbors to consider for each spot. + log2fc_threshold: The log2 fold change threshold for determining significance. + pval_threshold: The p-value threshold for determining significance. + assay_name: The name of the assay to use for analysis. + + Returns: + A dictionary with the command, stdout, stderr, and output CSV file path. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if not (0.0 <= pval_threshold <= 1.0): + raise ValueError("pval_threshold must be between 0.0 and 1.0.") + + cmd_args = [ + "--input_rds", str(input_rds), + "--col_group", col_group, + "--group1", group1, + "--n_neighbors", str(n_neighbors), + "--log2fc_threshold", str(log2fc_threshold), + "--pval_threshold", str(pval_threshold), + "--assay_name", assay_name, + "--test_function", "regional_wilcox", + ] + if group2: + cmd_args.extend(["--group2", group2]) + + return _run_regionalst_script( + script_content=REGIONAL_NONPARAMETRIC_RSCRIPT_TEMPLATE, + cmd_args=cmd_args, + output_filename="regional_wilcox_results.csv" + ) + +@mcp.tool() +def regional_ttest( + input_rds: Path, + col_group: str, + group1: str, + group2: Optional[str] = None, + n_neighbors: int = 6, + log2fc_threshold: float = 0.0, + pval_threshold: float = 1.0, + assay_name: str = "logcounts", +) -> Dict[str, Any]: + """ + Performs regional differential expression analysis using a t-test. + + This function wraps `regional_ttest` from `regionalST`, a parametric test. + It requires R, Rscript, and the Bioconductor packages `regionalST`, + `SpatialExperiment`, and `optparse` to be installed. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + col_group: The column name in `colData` that defines the groups to compare. + group1: The name of the first group for comparison. + group2: The name of the second group. If not provided, performs a one-vs-all comparison. + n_neighbors: The number of nearest neighbors to consider for each spot. + log2fc_threshold: The log2 fold change threshold for determining significance. + pval_threshold: The p-value threshold for determining significance. + assay_name: The name of the assay to use for analysis. + + Returns: + A dictionary with the command, stdout, stderr, and output CSV file path. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if not (0.0 <= pval_threshold <= 1.0): + raise ValueError("pval_threshold must be between 0.0 and 1.0.") + + cmd_args = [ + "--input_rds", str(input_rds), + "--col_group", col_group, + "--group1", group1, + "--n_neighbors", str(n_neighbors), + "--log2fc_threshold", str(log2fc_threshold), + "--pval_threshold", str(pval_threshold), + "--assay_name", assay_name, + "--test_function", "regional_ttest", + ] + if group2: + cmd_args.extend(["--group2", group2]) + + return _run_regionalst_script( + script_content=REGIONAL_NONPARAMETRIC_RSCRIPT_TEMPLATE, + cmd_args=cmd_args, + output_filename="regional_ttest_results.csv" + ) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-regionalst/app/bioconductor-regionalst_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-regionalst/app/bioconductor-regionalst_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f2e32154195811b8dac902be8be236b0e532fb9d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-regionalst/app/bioconductor-regionalst_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-regionalst/app/bioconductor-regionalst_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_regionalst' + + +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/Biomni/mcp_generated/mcp_bioconductor-regionalst/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-regionalst/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eea8e47f483f78be375b2bc87e47096e74695d82 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-regionalst/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-regionalst: + build: . + image: mcp-bioconductor-regionalst:latest + container_name: mcp-bioconductor-regionalst + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-regionalst + 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/Biomni/mcp_generated/mcp_bioconductor-regionalst/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-regionalst/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7df595636a62837fd9e58013cae1ae3021f57043 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-regionalst/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-regionalst + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-regionalst/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-regionalst/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-regionalst/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0490536356ac972684113e03f94ef6e5a5ed5edb --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_server.py b/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..11851eb51bc71813affd06c1385fe37f7a179070 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6ec748f5d4b2bc3601abc5e90c0e4a8b274b9c0a --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8777e2825f2c61ac247216ca6df83d0b77132802 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..add6d6abe9185029b539778ee50f8561cb2dbfcc --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rforproteomics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d6c698e62ad8b91053eed83fd9f8d55d7f0f868 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/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-rgraphviz via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rgraphviz -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-rgraphviz_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-rgraphviz_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-rgraphviz_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_server.py b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bfdbec4a9a5f716e4a459c2f09e4bce0ac814a04 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_server.py @@ -0,0 +1,204 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Dict, List, Optional + +# In a real MCP environment, this would be imported. +# from mcp import tool as mcp_tool +# For the purpose of this exercise, we define a placeholder. +class mcp: + @staticmethod + def tool(func=None, **kwargs): + if func: + return func + return lambda f: f + +@mcp.tool +def plot_graph( + graph_file: Path, + output_file: Path, + layout_engine: str = "dot", + output_format: str = "png", + graph_attributes: Optional[str] = None, + node_attributes: Optional[str] = None, + edge_attributes: Optional[str] = None, +) -> Dict: + """ + Generates a graph visualization using the Rgraphviz library. + + This tool takes a graph defined in a simple edge list format (CSV with 'from' + and 'to' headers) and uses Rgraphviz to create a visual representation, + saving it to a specified output file. + + Args: + graph_file: Path to the input graph file. Must be a CSV with 'from' and 'to' columns. + output_file: Path to save the output image file. + layout_engine: The Graphviz layout algorithm to use. + Valid options: 'dot', 'neato', 'twopi', 'circo', 'fdp'. + output_format: The format of the output image. + Valid options: 'png', 'pdf', 'svg', 'jpg'. + graph_attributes: Semicolon-separated key-value pairs for global graph attributes + (e.g., "rankdir=LR;bgcolor=lightblue;"). + node_attributes: Semicolon-separated key-value pairs for global node attributes + (e.g., "shape=ellipse;color=blue;"). + edge_attributes: Semicolon-separated key-value pairs for global edge attributes + (e.g., "color=red;"). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not graph_file.is_file(): + raise FileNotFoundError(f"Input graph file not found: {graph_file}") + + allowed_layouts = ["dot", "neato", "twopi", "circo", "fdp"] + if layout_engine not in allowed_layouts: + raise ValueError(f"Invalid layout_engine '{layout_engine}'. Must be one of {allowed_layouts}.") + + allowed_formats = ["png", "pdf", "svg", "jpg"] + if output_format not in allowed_formats: + raise ValueError(f"Invalid output_format '{output_format}'. Must be one of {allowed_formats}.") + + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + # 2. R Script Generation + r_script_content = textwrap.dedent(""" + # Load required libraries + # Suppress startup messages for cleaner output + suppressPackageStartupMessages(library(graph)) + suppressPackageStartupMessages(library(Rgraphviz)) + + # Get command line arguments + args <- commandArgs(trailingOnly = TRUE) + if (length(args) < 4) { + stop("Usage: Rscript plot_script.R [graph_attrs] [node_attrs] [edge_attrs]", call. = FALSE) + } + + inputFile <- args[1] + outputFile <- args[2] + layoutEngine <- args[3] + outputFormat <- args[4] + + # Read the edge list + edge_df <- read.csv(inputFile, header = TRUE, stringsAsFactors = FALSE) + + # Check for correct columns + if (!all(c("from", "to") %in% names(edge_df))) { + stop("Input CSV must have 'from' and 'to' columns.", call. = FALSE) + } + + # Create a graphNEL object from the edge list + g <- ftM2graphNEL(as.matrix(edge_df), edgemode = "directed") + + # Helper function to parse attribute strings like "key1=val1;key2=val2" + parse_attrs <- function(attr_string) { + if (is.na(attr_string) || nchar(attr_string) == 0) { + return(list()) + } + # Split by semicolon, but not if it's inside quotes + pairs <- strsplit(attr_string, ";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", perl=TRUE)[[1]] + attrs <- list() + for (pair in pairs) { + if (grepl("=", pair)) { + kv <- strsplit(pair, "=")[[1]] + key <- trimws(kv[1]) + value <- trimws(kv[2]) + # Try to convert to numeric if possible, otherwise keep as string + if (!is.na(suppressWarnings(as.numeric(value)))) { + attrs[[key]] <- as.numeric(value) + } else { + # Remove quotes if they exist + attrs[[key]] <- gsub('^"|"$', '', value) + } + } + } + return(attrs) + } + + graphAttrs <- if (length(args) >= 5) parse_attrs(args[5]) else list() + nodeAttrs <- if (length(args) >= 6) parse_attrs(args[6]) else list() + edgeAttrs <- if (length(args) >= 7) parse_attrs(args[7]) else list() + + # Open the correct graphics device based on output format + if (outputFormat == "png") { + png(outputFile, width=1024, height=768, res=100) + } else if (outputFormat == "pdf") { + pdf(outputFile) + } else if (outputFormat == "svg") { + svg(outputFile) + } else if (outputFormat == "jpg") { + jpeg(outputFile, width=1024, height=768, res=100) + } else { + stop(paste("Unsupported output format:", outputFormat), call. = FALSE) + } + + # Plot the graph with specified attributes + plot(g, layoutEngine, attrs=list(graph=graphAttrs, node=nodeAttrs, edge=edgeAttrs)) + + # Close the device + dev.off() + + cat(paste("Graph successfully plotted to", outputFile, "\\n")) + """) + + # 3. Subprocess Execution + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + cmd = [ + "Rscript", + str(r_script_path), + str(graph_file), + str(output_file), + layout_engine, + output_format, + ] + + # Add optional attributes to the command if they are provided + # Pass them as single arguments to prevent shell interpretation issues + cmd.append(graph_attributes if graph_attributes else "") + cmd.append(node_attributes if node_attributes else "") + cmd.append(edge_attributes if edge_attributes else "") + + command_executed = " ".join(f'"{arg}"' if ' ' in arg else arg for arg in cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = result.stdout + stderr = result.stderr + output_files = [str(output_file)] if output_file.exists() else [] + + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R 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": [] + } + finally: + # Clean up the temporary R script + if r_script_path.exists(): + r_script_path.unlink() + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d65bba4879e97544a0db1697b0c1ea29643bd77a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_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-rgraphviz/app/bioconductor-rgraphviz_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rgraphviz' + + +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/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..514d8237e7a05487cd9859004648dfd4d5d2c069 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rgraphviz: + build: . + image: mcp-bioconductor-rgraphviz:latest + container_name: mcp-bioconductor-rgraphviz + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rgraphviz + 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/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a125a84e5394fe87afdc748ab441a528f3c24a44 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rgraphviz + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rgraphviz/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..23b2b83e0e1daf22cc0c286cbebf06a5f2214728 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/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-rhdf5 via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rhdf5 -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-rhdf5_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-rhdf5_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-rhdf5_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c55252dadd675d264d417fe1298bafbb74b31d8c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py @@ -0,0 +1,192 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Note: The 'mcp' import is omitted as per instructions, but @mcp.tool() is used. + +def _check_rscript_available() -> None: + """Checks if Rscript is available in the system's PATH.""" + try: + subprocess.run(["Rscript", "--version"], check=True, capture_output=True, text=True) + except FileNotFoundError: + raise RuntimeError( + "Rscript command not found. Please ensure R is installed and Rscript is in your system's PATH." + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript command found but returned an error: {e.stderr.strip()}" + ) + except Exception as e: + raise RuntimeError(f"An unexpected error occurred while checking Rscript: {e}") + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_rhdf5' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_rhdf5_r_script( + r_script_content: str, + input_files: Optional[List[Path]] = None, + output_dir: Optional[Path] = None, + r_args: Optional[List[str]] = None, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script that can utilize the bioconductor-rhdf5 package. + + Note: bioconductor-rhdf5 is an R package, not a standalone command-line tool. + This MCP tool provides a mechanism to run arbitrary R scripts that use rhdf5 + by executing them via the 'Rscript' command-line utility. + Users are expected to provide the R script content directly, ensuring it + includes `library(rhdf5)` and performs the desired HDF5 operations. + + Args: + r_script_content: A string containing the R script to be executed. + This script should include `library(rhdf5)` and + perform the desired HDF5 operations. + input_files: An optional list of Path objects pointing to input files + that the R script might need. These files will be symlinked + into the working directory where the R script is executed, + making them accessible by their base names. + output_dir: An optional Path object specifying the directory where + the R script should write its output files. If not provided, + a temporary directory will be created for outputs. + r_args: Optional list of additional arguments to pass to Rscript. + These arguments will be available in the R script via `commandArgs(trailingOnly=TRUE)`. + verbose: If True, Rscript will print verbose output during execution. + + Returns: + A dictionary containing execution details: + - command_executed: The full command string executed. + - stdout: Standard output from the Rscript execution. + - stderr: Standard error from the Rscript execution. + - output_files: A list of Path objects for any files found in the output directory. + - error: Optional error message if the Rscript execution fails. + """ + _check_rscript_available() + + if not r_script_content or not r_script_content.strip(): + raise ValueError("R script content cannot be empty.") + + # Validate input files + if input_files: + for f in input_files: + if not isinstance(f, Path): + raise TypeError(f"Input file path must be a Path object, got {type(f)}") + if not f.is_file(): + raise FileNotFoundError(f"Input file not found: {f}") + + # Prepare output directory + temp_output_dir_obj: Optional[tempfile.TemporaryDirectory] = None + if output_dir: + if not isinstance(output_dir, Path): + raise TypeError(f"Output directory path must be a Path object, got {type(output_dir)}") + output_dir.mkdir(parents=True, exist_ok=True) + else: + temp_output_dir_obj = tempfile.TemporaryDirectory() + output_dir = Path(temp_output_dir_obj.name) + + temp_r_script_path: Optional[Path] = None + stdout_data = "" + stderr_data = "" + output_files_list: List[Path] = [] + error_message: Optional[str] = None + command_executed_str = "" + + try: + # Write the R script content to a temporary file + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R", encoding="utf-8") as temp_r_script_file: + temp_r_script_file.write(r_script_content) + temp_r_script_path = Path(temp_r_script_file.name) + + command = ["Rscript"] + if verbose: + command.append("--verbose") + command.append(str(temp_r_script_path)) + + if r_args: + if not isinstance(r_args, list) or not all(isinstance(arg, str) for arg in r_args): + raise TypeError("r_args must be a list of strings.") + command.extend(r_args) + + command_executed_str = " ".join(command) + + # Create symlinks for input files in the output directory + # This makes them easily accessible by their base name from the R script + for f in (input_files or []): + target_path = output_dir / f.name + if not target_path.exists(): # Avoid overwriting existing files or symlinks + try: + target_path.symlink_to(f.resolve()) # Use resolve() for absolute path + except OSError as e: + # Handle cases where symlinking might not be supported or fails + # Fallback to copying if symlink fails, or just log a warning + print(f"Warning: Could not symlink {f} to {target_path}. Error: {e}") + # Optionally, copy the file instead: + # import shutil + # shutil.copy(f, target_path) + + process = subprocess.run( + command, + cwd=output_dir, # Execute Rscript in the output directory + check=True, + capture_output=True, + text=True, + encoding="utf-8", + ) + stdout_data = process.stdout + stderr_data = process.stderr + + # Collect output files from the output directory + # Exclude the temporary R script and any symlinked input files + for f in output_dir.iterdir(): + if f.is_file() and f != temp_r_script_path and (input_files is None or f not in [output_dir / i.name for i in input_files]): + output_files_list.append(f) + + except FileNotFoundError: + error_message = "Rscript command not found. Please ensure R is installed and Rscript is in your system's PATH." + stderr_data = error_message + except subprocess.CalledProcessError as e: + error_message = f"Rscript execution failed with exit code {e.returncode}." + stdout_data = e.stdout + stderr_data = e.stderr + except ValueError as e: + error_message = f"Input validation error: {e}" + stderr_data = str(e) + except TypeError as e: + error_message = f"Type error: {e}" + stderr_data = str(e) + except Exception as e: + error_message = f"An unexpected error occurred: {e}" + stderr_data = str(e) + finally: + # Clean up the temporary R script file + if temp_r_script_path and temp_r_script_path.exists(): + try: + temp_r_script_path.unlink() + except OSError as e: + print(f"Warning: Failed to delete temporary R script {temp_r_script_path}: {e}") + + # Clean up temporary output directory if it was created by the tool + if temp_output_dir_obj: + try: + temp_output_dir_obj.cleanup() + except Exception as e: + # Log cleanup error if necessary, but don't fail the tool + print(f"Warning: Failed to clean up temporary directory {temp_output_dir_obj.name}: {e}") + + result = { + "command_executed": command_executed_str, + "stdout": stdout_data, + "stderr": stderr_data, + "output_files": [str(f) for f in output_files_list], + } + if error_message: + result["error"] = error_message + + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5f01840c51c6ab60e7c5e64891c7ff6d803397da --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_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-rhdf5/app/bioconductor-rhdf5_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rhdf5' + + +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/Biomni/mcp_generated/mcp_bioconductor-rhdf5/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..371502a90b6b0e642754aebfdcfbed6956a61c7d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rhdf5: + build: . + image: mcp-bioconductor-rhdf5:latest + container_name: mcp-bioconductor-rhdf5 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rhdf5 + 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/Biomni/mcp_generated/mcp_bioconductor-rhdf5/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cee49d16e0b5556057e50c59af4bc0cf5ee744b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rhdf5 + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..70ad418d4a9082937d70718a7a788888f0f4525b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/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-rhdf5filters via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rhdf5filters -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-rhdf5filters_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-rhdf5filters_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-rhdf5filters_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_server.py b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0f0736b143afb43ad4371abc491eaa320ada41bd --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_server.py @@ -0,0 +1,78 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Dict, Any, List + +# MCP decorator is commented out as per instructions +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_rhdf5filters' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def check_installation() -> Dict[str, Any]: + """ + Verifies the installation of the bioconductor-rhdf5filters R library. + + bioconductor-rhdf5filters is an R library that provides HDF5 compression + filters and does not have a direct command-line interface. This function + executes a simple R script to confirm that the library is installed and + can be loaded in the R environment, and it reports the installed version. + """ + # Pre-flight check for Rscript executable + if not shutil.which("Rscript"): + raise FileNotFoundError("Rscript executable not found in PATH. R is required to run this tool.") + + r_script_content = """ + if (!requireNamespace("rhdf5filters", quietly = TRUE)) { + cat("Error: The 'rhdf5filters' package is not installed.\\n", file = stderr()) + quit(status = 1) + } + ver <- as.character(packageVersion("rhdf5filters")) + cat(paste0("Successfully loaded 'rhdf5filters' version: ", ver, "\\n")) + quit(status = 0) + """ + + command_executed = "" + script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as tmp_r_script: + script_path = tmp_r_script.name + tmp_r_script.write(r_script_content) + + cmd: List[str] = ["Rscript", script_path] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + # This will catch the case where the R script exits with a non-zero status + # (e.g., package not installed) and return a structured error. + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "R script execution failed. The 'rhdf5filters' package may not be installed or accessible." + } + finally: + # Ensure the temporary file is cleaned up + if script_path and Path(script_path).exists(): + Path(script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c6d68edcaba3fee0b41e2e9817d7d05eee254d58 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_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-rhdf5filters/app/bioconductor-rhdf5filters_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rhdf5filters' + + +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/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..81832d0f80640700360671a525f10b97f2382efa --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rhdf5filters: + build: . + image: mcp-bioconductor-rhdf5filters:latest + container_name: mcp-bioconductor-rhdf5filters + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rhdf5filters + 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/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a0adbb1473ea9468bd807b23ff418eeac7f03f44 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rhdf5filters + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5filters/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..092f3d6b4424cc3647a52adc9af228e1cb8277d7 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/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-rhdf5lib via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rhdf5lib -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-rhdf5lib_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-rhdf5lib_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-rhdf5lib_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..13b68eed5256245769e3e0b77bcff4c62d34a6b0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py @@ -0,0 +1,33 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# NOTE: The 'mcp' import is not included as per the instructions. +# import mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_rhdf5lib' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def rhdf5lib_info(): + """ + Provides information about the bioconductor-rhdf5lib package. + + This package is a library and does not provide any command-line executables. + It offers the HDF5 C and C++ libraries for other R packages to link against. + Therefore, this function is for informational purposes only and does not + execute any subprocess. + """ + # This is a library package with no executable. + # The return dictionary reflects that no command can be executed. + return { + "command_executed": "N/A (bioconductor-rhdf5lib is a library, not a command-line tool)", + "stdout": "This package provides C and C++ HDF5 libraries for use within the R environment. It has no direct command-line interface.", + "stderr": "", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be58be4673ae03c74476c95791c724eeb10ff8ca --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_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-rhdf5lib/app/bioconductor-rhdf5lib_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rhdf5lib' + + +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/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..76b1d4811a976df2b79fe83db8d4a84fd0ba1942 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rhdf5lib: + build: . + image: mcp-bioconductor-rhdf5lib:latest + container_name: mcp-bioconductor-rhdf5lib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rhdf5lib + 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/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..017af4d64e893f7c7b7ba39e41e213740bfc4479 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rhdf5lib + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhdf5lib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhtslib/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..06606fbc87c7cc914c960f63ba38650caa95bbc6 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/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-rhtslib via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rhtslib -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-rhtslib_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-rhtslib_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-rhtslib_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..762e321547e970dc0b72e430cae52eac7804a399 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py @@ -0,0 +1,128 @@ +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__) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_rhtslib' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def rscript_run( + script_file: Optional[Path] = None, + expression: Optional[str] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + vanilla: bool = False, + no_save: bool = False, + no_restore_data: bool = False, + no_restore_history: bool = False, + no_restore: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + slave: bool = False, + arch: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes an R script or expression using the Rscript command-line tool. + + This tool serves as a wrapper for Rscript, the non-interactive R interpreter. + It is suitable for running scripts that utilize Bioconductor packages like + bioconductor-rhtslib, which is a library and does not have its own + direct command-line interface. You must provide either a script file or an + R expression to execute. + """ + # --- Input Validation --- + if not (script_file is None) ^ (expression is None): + raise ValueError("Exactly one of 'script_file' or 'expression' must be provided.") + + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # --- Command Construction --- + command = ["Rscript"] + + if verbose: + command.append("--verbose") + if default_packages: + command.extend(["--default-packages", default_packages]) + if vanilla: + command.append("--vanilla") + if no_save: + command.append("--no-save") + if no_restore_data: + command.append("--no-restore-data") + if no_restore_history: + command.append("--no-restore-history") + if no_restore: + command.append("--no-restore") + 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 slave: + command.append("--slave") + if arch: + command.extend(["--arch", arch]) + + if expression: + command.extend(["-e", expression]) + 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}") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + error_msg = "Error: Rscript command not found. Please ensure R is installed and in your system's PATH." + logger.error(error_msg) + return { + "command_executed": command_str, + "stdout": "", + "stderr": error_msg, + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"Rscript execution failed with return code {e.returncode}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + # Rscript itself doesn't manage output files; the executed script does. + # We return an empty list as this wrapper cannot know what files the script might create. + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..42f9ec80c583c076ee2e7079c8643d2914f34cdd --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_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-rhtslib/app/bioconductor-rhtslib_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rhtslib' + + +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/Biomni/mcp_generated/mcp_bioconductor-rhtslib/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhtslib/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e3490324c687de6f1d638054610292218df8d093 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rhtslib: + build: . + image: mcp-bioconductor-rhtslib:latest + container_name: mcp-bioconductor-rhtslib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rhtslib + 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/Biomni/mcp_generated/mcp_bioconductor-rhtslib/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d9fd1f10209694d0af1705cd86798274dadc35c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rhtslib + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rhtslib/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rhtslib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsamtools/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0d3c706e4910bc3c14bf2f9ad377de8d3d4f6d71 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/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-rsamtools via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rsamtools -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-rsamtools_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-rsamtools_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-rsamtools_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_server.py b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7cc02f52af25da42af40460bc49622b2108bc931 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_server.py @@ -0,0 +1,377 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# Mock decorator for standalone execution +class mcp: + def tool(func): + return func + +@mcp.tool +def rsamtools_index_bam( + input_bam: Path, +) -> dict: + """ + Creates a BAI index for a BAM file using Rsamtools::indexBam. + + This function corresponds to the 'samtools index' command. The output + index file will be created in the same directory as the input BAM file, + with a '.bai' extension. + + Args: + input_bam: Path to the input coordinate-sorted BAM file. + + Returns: + A dictionary containing the execution command, stdout, stderr, + and the path to the generated index file. + """ + if not input_bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + if input_bam.suffix != ".bam": + raise ValueError(f"Input file must be a BAM file with a .bam extension: {input_bam}") + + output_index = input_bam.with_suffix(".bam.bai") + + # Construct the R command to be executed + r_command = f'library(Rsamtools); indexBam(files="{input_bam}")' + + cmd = ["Rscript", "-e", r_command] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + if not output_index.is_file(): + raise FileNotFoundError( + f"Expected index file was not created: {output_index}. " + f"Rsamtools stderr: {result.stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"bam_index": str(output_index)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Rsamtools indexBam failed.", + "return_code": e.returncode + } + +@mcp.tool +def rsamtools_sort_bam( + input_bam: Path, + output_prefix: str, + by_qname: bool = False, + max_memory: int = 1024, +) -> dict: + """ + Sorts a BAM file by coordinate or query name using Rsamtools::sortBam. + + This function corresponds to the 'samtools sort' command. + + Args: + input_bam: Path to the input BAM file. + output_prefix: The prefix for the output sorted BAM file. '.bam' will be appended. + by_qname: If True, sort by query name. Otherwise, sort by coordinate. + max_memory: Maximum memory per thread, in megabytes. + + Returns: + A dictionary containing the execution command, stdout, stderr, + and the path to the generated sorted BAM file. + """ + if not input_bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + if max_memory <= 0: + raise ValueError("max_memory must be a positive integer.") + + output_bam = Path(f"{output_prefix}.bam") + + # R booleans are TRUE/FALSE + r_by_qname = "TRUE" if by_qname else "FALSE" + + r_command = ( + f'library(Rsamtools); ' + f'sortBam(file="{input_bam}", destination="{output_prefix}", ' + f'byQname={r_by_qname}, maxMemory={max_memory})' + ) + + cmd = ["Rscript", "-e", r_command] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + if not output_bam.is_file(): + raise FileNotFoundError( + f"Expected sorted BAM file was not created: {output_bam}. " + f"Rsamtools stderr: {result.stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"sorted_bam": str(output_bam)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Rsamtools sortBam failed.", + "return_code": e.returncode + } + +@mcp.tool +def rsamtools_merge_bam( + input_bams: List[Path], + output_bam: Path, + index_destination: bool = True, + overwrite: bool = False, +) -> dict: + """ + Merges multiple BAM files into a single file using Rsamtools::mergeBam. + + This function corresponds to the 'samtools merge' command. Input BAM files + must be sorted by coordinate and have the same header. + + Args: + input_bams: A list of paths to coordinate-sorted BAM files to merge. + output_bam: Path for the merged output BAM file. + index_destination: If True, create an index for the merged BAM file. + overwrite: If True, overwrite the destination file if it exists. + + Returns: + A dictionary containing the execution command, stdout, stderr, + and paths to the output BAM and its index (if created). + """ + if not input_bams: + raise ValueError("At least one input BAM file is required.") + for bam_file in input_bams: + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + + # Create an R character vector string: c("file1.bam", "file2.bam", ...) + r_files_vector = 'c(' + ', '.join(f'"{f}"' for f in input_bams) + ')' + r_index_destination = "TRUE" if index_destination else "FALSE" + r_overwrite = "TRUE" if overwrite else "FALSE" + + r_command = ( + f'library(Rsamtools); ' + f'mergeBam(files={r_files_vector}, destination="{output_bam}", ' + f'indexDestination={r_index_destination}, overwrite={r_overwrite})' + ) + + cmd = ["Rscript", "-e", r_command] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + if not output_bam.is_file(): + raise FileNotFoundError( + f"Expected merged BAM file was not created: {output_bam}. " + f"Rsamtools stderr: {result.stderr}" + ) + + output_files = {"merged_bam": str(output_bam)} + output_index = output_bam.with_suffix(".bam.bai") + if index_destination and output_index.is_file(): + output_files["bam_index"] = str(output_index) + + 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": "Rsamtools mergeBam failed.", + "return_code": e.returncode + } + +@mcp.tool +def rsamtools_idxstats_bam( + input_bam: Path, +) -> dict: + """ + Retrieves BAM index statistics using Rsamtools::idxstatsBam. + + This function corresponds to the 'samtools idxstats' command. It returns + a tab-separated table with reference sequence name, sequence length, + number of mapped reads, and number of unmapped reads. + + Args: + input_bam: Path to the input BAM file. An index must exist. + + Returns: + A dictionary containing the execution command, stdout (the stats table), + stderr, and no output files. + """ + if not input_bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + + index_file = input_bam.with_suffix(".bam.bai") + if not index_file.is_file(): + raise FileNotFoundError(f"BAM index file not found for {input_bam}. Please run rsamtools_index_bam first.") + + # The R function returns a data.frame. We need to print it to stdout + # in a standard format to capture it in Python. + r_command = ( + f'library(Rsamtools); ' + f'stats <- idxstatsBam(files="{input_bam}"); ' + f'write.table(stats, file=stdout(), sep="\\t", row.names=FALSE, col.names=FALSE, quote=FALSE)' + ) + + cmd = ["Rscript", "-e", r_command] + 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": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Rsamtools idxstatsBam failed.", + "return_code": e.returncode + } + +@mcp.tool +def rsamtools_pileup( + input_bam: Path, + output_file: Path, + max_depth: int = 250, + min_base_quality: int = 13, + min_map_quality: int = 0, + distinguish_strands: bool = True, + distinguish_nucleotides: bool = True, + ignore_query_ns: bool = True, + include_deletions: bool = True, + include_insertions: bool = False, +) -> dict: + """ + Generates a pileup from a BAM file using Rsamtools::pileup. + + This function corresponds to 'samtools mpileup' but provides a structured + data frame output. The output is saved to a CSV file. + + Args: + input_bam: Path to the input BAM file. An index must exist. + output_file: Path to save the output CSV pileup results. + max_depth: The maximum depth at any position. + min_base_quality: The minimum base quality for a nucleotide to be included. + min_map_quality: The minimum mapping quality for an alignment to be included. + distinguish_strands: Report counts on forward and reverse strands separately. + distinguish_nucleotides: Report counts for each nucleotide separately. + ignore_query_ns: Ignore 'N's in the query sequence. + include_deletions: Include deletions in the pileup. + include_insertions: Include insertions in the pileup. + + Returns: + A dictionary containing the execution command, stdout, stderr, + and the path to the output pileup CSV file. + """ + if not input_bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + index_file = input_bam.with_suffix(".bam.bai") + if not index_file.is_file(): + raise FileNotFoundError(f"BAM index file not found for {input_bam}. Please run rsamtools_index_bam first.") + + # Convert Python bools to R TRUE/FALSE + r_bools = { + "distinguish_strands": "TRUE" if distinguish_strands else "FALSE", + "distinguish_nucleotides": "TRUE" if distinguish_nucleotides else "FALSE", + "ignore_query_ns": "TRUE" if ignore_query_ns else "FALSE", + "include_deletions": "TRUE" if include_deletions else "FALSE", + "include_insertions": "TRUE" if include_insertions else "FALSE", + } + + # Construct the PileupParam object in R + param_command = ( + f'param <- PileupParam(max_depth={max_depth}, ' + f'min_base_quality={min_base_quality}, ' + f'min_map_quality={min_map_quality}, ' + f'distinguish_strands={r_bools["distinguish_strands"]}, ' + f'distinguish_nucleotides={r_bools["distinguish_nucleotides"]}, ' + f'ignore_query_ns={r_bools["ignore_query_ns"]}, ' + f'include_deletions={r_bools["include_deletions"]}, ' + f'include_insertions={r_bools["include_insertions"]})' + ) + + # Construct the main pileup command and write output to a CSV + pileup_command = ( + f'p_result <- pileup(file="{input_bam}", pileupParam=param); ' + f'write.csv(p_result, file="{output_file}", row.names=FALSE, quote=FALSE)' + ) + + r_command = f'library(Rsamtools); {param_command}; {pileup_command}' + + cmd = ["Rscript", "-e", r_command] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + if not output_file.is_file() or output_file.stat().st_size == 0: + raise FileNotFoundError( + f"Expected pileup file was not created or is empty: {output_file}. " + f"Rsamtools stderr: {result.stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"pileup_csv": str(output_file)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Rsamtools pileup failed.", + "return_code": e.returncode + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9f6d9035320b6a9d13edf78ef6c84a798bee7ee9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_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-rsamtools/app/bioconductor-rsamtools_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rsamtools' + + +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/Biomni/mcp_generated/mcp_bioconductor-rsamtools/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsamtools/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d651c7cf7814b6fdfba82ac2f2145cb67d0099d2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rsamtools: + build: . + image: mcp-bioconductor-rsamtools:latest + container_name: mcp-bioconductor-rsamtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rsamtools + 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/Biomni/mcp_generated/mcp_bioconductor-rsamtools/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5c153912d63628e3c8ea76360f2d3f0afac07118 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rsamtools + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsamtools/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsamtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsubread/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rsubread/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4dec6ab2174115a3f1326b6fd37bc802e9c6b00 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsubread/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-rsubread via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rsubread -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-rsubread_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-rsubread_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-rsubread_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py b/Biomni/mcp_generated/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c0511e467738b789b0138f423a705373287d4f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py @@ -0,0 +1,322 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +def run_r_command(command: str): + """Helper to execute R commands via Rscript""" + try: + # We use -e to execute the expression directly + full_cmd = ["Rscript", "-e", f"library(Rsubread); {command}"] + result = subprocess.run(full_cmd, capture_output=True, text=True, check=True) + return result.stdout, result.stderr + except subprocess.CalledProcessError as e: + raise RuntimeError(f"Rsubread execution failed: {e.stderr}") + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_rsubread' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def rsubread_buildindex( + basename: str, + reference: str, + gapped_index: bool = False, + index_memory: int = 8000, + colorspace: bool = False, + split_index: bool = False +): + """ + Builds an index for a reference genome. + + Args: + basename: Base name of the index files to be generated. + reference: Path to the reference genome file (FASTA format). + gapped_index: If True, a gapped index will be built (saves memory). + index_memory: Memory usage in MB. + colorspace: If True, index is built for color-space reads (SOLiD). + split_index: If True, the index will be split into multiple blocks. + """ + ref_path = Path(reference) + if not ref_path.exists(): + return {"error": f"Reference file {reference} not found."} + + # Construct R command + r_cmd = ( + f"buildindex(basename='{basename}', reference='{reference}', " + f"gappedIndex={'TRUE' if gapped_index else 'FALSE'}, " + f"indexMemory={index_memory}, colorspace={'TRUE' if colorspace else 'FALSE'}, " + f"splitIndex={'TRUE' if split_index else 'FALSE'})" + ) + + try: + stdout, stderr = run_r_command(r_cmd) + return { + "command_executed": f"Rsubread::buildindex({basename})", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(Path(f"{basename}.{ext}")) for ext in ["files"]] # Rsubread creates multiple files + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def rsubread_align( + index: str, + readfile1: str, + readfile2: Optional[str] = None, + output_file: str = "output.bam", + input_format: str = "gzFASTQ", + output_format: str = "BAM", + nthreads: int = 1, + type: str = "dna", + phred_offset: int = 33, + unique: bool = False, + n_best_locations: int = 1, + max_mismatches: int = 3 +): + """ + Aligns reads to a reference genome using the Subread aligner. + + Args: + index: Base name of the index. + readfile1: Path to the first read file. + readfile2: Path to the second read file (for paired-end). + output_file: Name of the output file. + input_format: Format of input reads ('FASTQ', 'gzFASTQ', 'SAM', 'BAM'). + output_format: Format of output ('BAM', 'SAM'). + nthreads: Number of threads to use. + type: Type of sequencing ('dna' or 'rna'). + phred_offset: Phred score offset (33 or 64). + unique: If True, only uniquely mapped reads are reported. + n_best_locations: Number of best mapping locations to report. + max_mismatches: Maximum number of mismatches allowed. + """ + if not Path(readfile1).exists(): + return {"error": f"Read file {readfile1} not found."} + + read2_param = f"'{readfile2}'" if readfile2 else "NULL" + + r_cmd = ( + f"align(index='{index}', readfile1='{readfile1}', readfile2={read2_param}, " + f"output_file='{output_file}', input_format='{input_format}', output_format='{output_format}', " + f"nthreads={nthreads}, type='{type}', phredOffset={phred_offset}, " + f"unique={'TRUE' if unique else 'FALSE'}, nBestLocations={n_best_locations}, " + f"maxMismatches={max_mismatches})" + ) + + try: + stdout, stderr = run_r_command(r_cmd) + return { + "command_executed": "Rsubread::align", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def rsubread_subjunc( + index: str, + readfile1: str, + readfile2: Optional[str] = None, + output_file: str = "output_subjunc.bam", + input_format: str = "gzFASTQ", + output_format: str = "BAM", + nthreads: int = 1, + phred_offset: int = 33, + unique: bool = False +): + """ + Aligns RNA-seq reads and detects exon-exon junctions using the Subjunc aligner. + + Args: + index: Base name of the index. + readfile1: Path to the first read file. + readfile2: Path to the second read file (for paired-end). + output_file: Name of the output file. + input_format: Format of input reads. + output_format: Format of output. + nthreads: Number of threads. + phred_offset: Phred score offset. + unique: If True, only uniquely mapped reads are reported. + """ + read2_param = f"'{readfile2}'" if readfile2 else "NULL" + + r_cmd = ( + f"subjunc(index='{index}', readfile1='{readfile1}', readfile2={read2_param}, " + f"output_file='{output_file}', input_format='{input_format}', output_format='{output_format}', " + f"nthreads={nthreads}, phredOffset={phred_offset}, unique={'TRUE' if unique else 'FALSE'})" + ) + + try: + stdout, stderr = run_r_command(r_cmd) + return { + "command_executed": "Rsubread::subjunc", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def rsubread_featurecounts( + files: List[str], + annot_ext: str, + is_gtf_annotation_file: bool = True, + gtf_feature_type: str = "exon", + gtf_attr_type: str = "gene_id", + use_meta_features: bool = True, + allow_multi_overlap: bool = False, + is_paired_end: bool = False, + nthreads: int = 1, + strand_specific: int = 0, + count_multi_mapping_reads: bool = False +): + """ + Assigns mapped reads to genomic features (e.g. genes, exons). + + Args: + files: List of paths to alignment files (BAM/SAM). + annot_ext: Path to the annotation file (GTF/GFF/SAF). + is_gtf_annotation_file: Whether the annotation file is in GTF format. + gtf_feature_type: Feature type in GTF to be used (e.g. 'exon'). + gtf_attr_type: Attribute type in GTF to be used (e.g. 'gene_id'). + use_meta_features: If True, reads are counted for meta-features (e.g. genes). + allow_multi_overlap: If True, a read is allowed to be assigned to multiple features. + is_paired_end: If True, reads are treated as paired-end. + nthreads: Number of threads. + strand_specific: Strand specificity (0: unstranded, 1: stranded, 2: reversely stranded). + count_multi_mapping_reads: If True, multi-mapping reads will be counted. + """ + # Convert Python list to R vector + files_r = "c(" + ",".join([f"'{f}'" for f in files]) + ")" + + r_cmd = ( + f"fc <- featureCounts(files={files_r}, annot.ext='{annot_ext}', " + f"isGTFAnnotationFile={'TRUE' if is_gtf_annotation_file else 'FALSE'}, " + f"GTF.featureType='{gtf_feature_type}', GTF.attrType='{gtf_attr_type}', " + f"useMetaFeatures={'TRUE' if use_meta_features else 'FALSE'}, " + f"allowMultiOverlap={'TRUE' if allow_multi_overlap else 'FALSE'}, " + f"isPairedEnd={'TRUE' if is_paired_end else 'FALSE'}, " + f"nthreads={nthreads}, strandSpecific={strand_specific}, " + f"countMultiMappingReads={'TRUE' if count_multi_mapping_reads else 'FALSE'}); " + f"write.table(fc$counts, file='counts.txt', sep='\\t', quote=FALSE); " + f"write.table(fc$stat, file='stats.txt', sep='\\t', quote=FALSE)" + ) + + try: + stdout, stderr = run_r_command(r_cmd) + return { + "command_executed": "Rsubread::featureCounts", + "stdout": stdout, + "stderr": stderr, + "output_files": ["counts.txt", "stats.txt"] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def rsubread_qualityscores( + filename: str, + input_format: str = "gzFASTQ", + offset: int = 33, + nreads: int = 10000 +): + """ + Extracts quality scores from a read file. + + Args: + filename: Path to the read file. + input_format: Format of the input file. + offset: Phred score offset. + nreads: Number of reads to extract quality scores from. + """ + if not Path(filename).exists(): + return {"error": f"File {filename} not found."} + + r_cmd = ( + f"qs <- qualityScores(filename='{filename}', input_format='{input_format}', " + f"offset={offset}, nreads={nreads}); " + f"write.table(qs, file='quality_scores.txt', sep='\\t', quote=FALSE)" + ) + + try: + stdout, stderr = run_r_command(r_cmd) + return { + "command_executed": "Rsubread::qualityScores", + "stdout": stdout, + "stderr": stderr, + "output_files": ["quality_scores.txt"] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def rsubread_atgccontent( + filename: str, + input_format: str = "gzFASTQ", + basewise: bool = True +): + """ + Calculates ATGC content of reads. + + Args: + filename: Path to the read file. + input_format: Format of the input file. + basewise: If True, calculate content for each base position. + """ + r_cmd = ( + f"atgc <- atgcContent(filename='{filename}', input_format='{input_format}', " + f"basewise={'TRUE' if basewise else 'FALSE'}); " + f"write.table(atgc, file='atgc_content.txt', sep='\\t', quote=FALSE)" + ) + + try: + stdout, stderr = run_r_command(r_cmd) + return { + "command_executed": "Rsubread::atgcContent", + "stdout": stdout, + "stderr": stderr, + "output_files": ["atgc_content.txt"] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def rsubread_propmapped( + files: List[str], + count_multi_mapping_reads: bool = False +): + """ + Calculates the proportion of mapped reads in BAM/SAM files. + + Args: + files: List of paths to alignment files. + count_multi_mapping_reads: Whether to include multi-mapping reads. + """ + files_r = "c(" + ",".join([f"'{f}'" for f in files]) + ")" + + r_cmd = ( + f"pm <- propMapped(files={files_r}, " + f"countMultiMappingReads={'TRUE' if count_multi_mapping_reads else 'FALSE'}); " + f"write.table(pm, file='prop_mapped.txt', sep='\\t', quote=FALSE, row.names=FALSE)" + ) + + try: + stdout, stderr = run_r_command(r_cmd) + return { + "command_executed": "Rsubread::propMapped", + "stdout": stdout, + "stderr": stderr, + "output_files": ["prop_mapped.txt"] + } + except Exception as e: + return {"error": str(e)} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsubread/app/bioconductor-rsubread_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rsubread/app/bioconductor-rsubread_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..61a4db6756b948241f2f00ce7ba70d886e6b5057 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsubread/app/bioconductor-rsubread_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-rsubread/app/bioconductor-rsubread_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rsubread' + + +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/Biomni/mcp_generated/mcp_bioconductor-rsubread/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rsubread/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsubread/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsubread/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rsubread/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e2725ed890f216390d4ca45f72fe80e813511c82 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsubread/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rsubread: + build: . + image: mcp-bioconductor-rsubread:latest + container_name: mcp-bioconductor-rsubread + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rsubread + 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/Biomni/mcp_generated/mcp_bioconductor-rsubread/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rsubread/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fdd1061efad1bac463df38b14d847bf8a1798168 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsubread/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rsubread + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rsubread/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rsubread/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rsubread/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rtracklayer copy/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer copy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer copy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc4c0991514cc01e8dac3cd11c123168bf61c81a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/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-rtracklayer via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rtracklayer -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-rtracklayer_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-rtracklayer_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-rtracklayer_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_server.py b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d68fa4f35a1715e991d5843bb988c2cb66583da9 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_server.py @@ -0,0 +1,340 @@ +import subprocess +import tempfile +import re +from pathlib import Path +from typing import Optional, List + +# @mcp.tool() is a placeholder for the actual decorator. +# The code is written to be compatible with the MCP framework. + +def mcp_tool_placeholder(): + def decorator(func): + return func + return decorator + +@mcp_tool_placeholder() +def rtracklayer_convert( + input_file: Path, + output_file: Path, + input_format: Optional[str] = None, + output_format: Optional[str] = None, + which: Optional[str] = None, + genome: Optional[str] = None, + gff_feature_type_filter: Optional[str] = None, + gff_version: Optional[str] = None, + export_source: Optional[str] = None, + index_output: bool = False, +): + """ + Converts genomic data files from one format to another using rtracklayer. + + This tool wraps the core import() and export() functionality of the rtracklayer + R package, allowing for conversion between formats like BED, GFF, GTF, WIG, + and BigWig. It also supports filtering by genomic region. + + Args: + input_file: Path to the input genomic data file. + output_file: Path to write the converted output file. + input_format: The format of the input file (e.g., 'bed', 'gff', 'bigWig'). + If not provided, rtracklayer will guess from the file extension. + output_format: The format for the output file. If not provided, rtracklayer + will guess from the file extension. + which: A specific genomic region to process, in the format 'chr:start-end' + (e.g., 'chr1:1000-2000'). This is highly effective for indexed files. + genome: The genome assembly name (e.g., 'hg19', 'mm10'). + gff_feature_type_filter: For GFF/GTF import, a comma-separated list of + feature types to keep (e.g., 'exon,gene'). + gff_version: Specify the GFF version ('1', '2', or '3') for import/export. + export_source: The 'source' field to use for GFF/GTF export. + index_output: If True, create a tabix index (.tbi) for the output file. + Applicable to formats like BED and GFF. + """ + # 1. Input Validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + ALLOWED_FORMATS = ["bed", "gff", "gff1", "gff2", "gff3", "gtf", "wig", "bigWig", "bedGraph", "2bit", "fasta"] + if input_format and input_format not in ALLOWED_FORMATS: + raise ValueError(f"Invalid input_format '{input_format}'. Allowed formats: {ALLOWED_FORMATS}") + if output_format and output_format not in ALLOWED_FORMATS: + raise ValueError(f"Invalid output_format '{output_format}'. Allowed formats: {ALLOWED_FORMATS}") + + if gff_version and gff_version not in ["1", "2", "3"]: + raise ValueError("gff_version must be one of '1', '2', or '3'.") + + if which and not re.match(r"^\w+:\d+-\d+$", which): + raise ValueError("Invalid 'which' format. Expected 'chr:start-end' (e.g., 'chr1:1000-5000').") + + # 2. Build R Script + r_script_lines = [ + "suppressPackageStartupMessages(library(rtracklayer))", + "suppressPackageStartupMessages(library(GenomicRanges))", + "", + "# --- Import Arguments ---", + f"import_args <- list(con = '{input_file.resolve()}')", + ] + if input_format: + r_script_lines.append(f"import_args$format <- '{input_format}'") + if which: + r_script_lines.append(f"import_args$which <- GRanges('{which}')") + if genome: + r_script_lines.append(f"import_args$genome <- '{genome}'") + if gff_feature_type_filter: + r_vector = 'c(' + ', '.join([f'"{f.strip()}"' for f in gff_feature_type_filter.split(',')]) + ')' + r_script_lines.append(f"import_args$feature.type <- {r_vector}") + if gff_version: + r_script_lines.append(f"import_args$version <- '{gff_version}'") + + r_script_lines.extend([ + "", + "# --- Import Data ---", + "gr_object <- do.call(rtracklayer::import, import_args)", + "", + "# --- Export Arguments ---", + f"export_args <- list(object = gr_object, con = '{output_file.resolve()}')", + ]) + + if output_format: + r_script_lines.append(f"export_args$format <- '{output_format}'") + if export_source: + r_script_lines.append(f"export_args$source <- '{export_source}'") + if gff_version: + r_script_lines.append(f"export_args$version <- '{gff_version}'") + if index_output: + r_script_lines.append("export_args$index <- TRUE") + + r_script_lines.extend([ + "", + "# --- Export Data ---", + "do.call(rtracklayer::export, export_args)", + "cat('Conversion successful.\\n')" + ]) + + r_script = "\n".join(r_script_lines) + + # 3. Execute R Script + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=".") as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script) + + command = ["Rscript", str(script_path.name)] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=Path.cwd() + ) + + output_files = [str(output_file)] + index_file = Path(f"{output_file}.tbi") + if index_output and index_file.exists(): + output_files.append(str(index_file)) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with return code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + finally: + script_path.unlink() + + +@mcp_tool_placeholder() +def rtracklayer_liftover( + input_file: Path, + output_file: Path, + chain_file: Path, + input_format: Optional[str] = None, + unmapped_output_file: Optional[Path] = None, +): + """ + Lifts over genomic coordinates from one assembly to another using a chain file. + + This tool wraps the liftOver() function from rtracklayer, which is essential + for translating genomic features between different reference genome versions + (e.g., hg18 to hg19). + + Args: + input_file: Path to the input genomic data file (e.g., BED, GFF) with + coordinates to be lifted over. + output_file: Path to write the output file with lifted coordinates. + chain_file: Path to the liftOver chain file (.chain or .chain.gz). + input_format: The format of the input file (e.g., 'bed', 'gff'). If not + provided, rtracklayer will guess from the file extension. + unmapped_output_file: Optional path to write features that could not be + mapped to the new assembly. + """ + # 1. Input Validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not chain_file.exists(): + raise FileNotFoundError(f"Chain file not found: {chain_file}") + + # 2. Build R Script + r_script_lines = [ + "suppressPackageStartupMessages(library(rtracklayer))", + "", + "# --- Import Data ---", + f"ch <- rtracklayer::import.chain('{chain_file.resolve()}')", + f"gr <- rtracklayer::import('{input_file.resolve()}'" + (f", format = '{input_format}'" if input_format else "") + ")", + "", + "# --- Perform LiftOver ---", + "lifted_grl <- rtracklayer::liftOver(gr, ch)", + "lifted_gr <- unlist(lifted_grl)", + "", + "# --- Export Lifted Data ---", + f"rtracklayer::export(lifted_gr, '{output_file.resolve()}')", + ] + + if unmapped_output_file: + r_script_lines.extend([ + "", + "# --- Handle Unmapped Regions ---", + "unmapped_indices <- elementNROWS(lifted_grl) == 0", + "unmapped_gr <- gr[unmapped_indices]", + f"if (length(unmapped_gr) > 0) {{", + f" rtracklayer::export(unmapped_gr, '{unmapped_output_file.resolve()}')", + f"}}", + ]) + + r_script_lines.append("cat('LiftOver successful.\\n')") + r_script = "\n".join(r_script_lines) + + # 3. Execute R Script + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=".") as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script) + + command = ["Rscript", str(script_path.name)] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=Path.cwd() + ) + + output_files = [str(output_file)] + if unmapped_output_file and unmapped_output_file.exists(): + output_files.append(str(unmapped_output_file)) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with return code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + finally: + script_path.unlink() + + +@mcp_tool_placeholder() +def rtracklayer_ucsc_query( + output_file: Path, + genome: str, + track: str, + which: Optional[str] = None, + output_format: Optional[str] = None, +): + """ + Downloads data directly from the UCSC Table Browser. + + This tool provides an interface to query and download genomic tracks from the + UCSC database, saving them to a local file in a specified format. + + Args: + output_file: Path to write the downloaded data. + genome: The UCSC genome assembly to query (e.g., 'hg19', 'mm10'). + track: The name of the track/table to download (e.g., 'knownGene', 'cpgIslandExt'). + which: A specific genomic region to query, in the format 'chr:start-end' + (e.g., 'chr1:1000-2000'). If not provided, the whole genome is queried. + output_format: The format for the output file (e.g., 'bed', 'gff'). If not + provided, rtracklayer will guess from the file extension. + """ + # 1. Input Validation + if which and not re.match(r"^\w+:\d+-\d+$", which): + raise ValueError("Invalid 'which' format. Expected 'chr:start-end' (e.g., 'chr1:1000-5000').") + + # 2. Build R Script + r_script_lines = [ + "suppressPackageStartupMessages(library(rtracklayer))", + "suppressPackageStartupMessages(library(GenomicRanges))", + "", + "# --- Build UCSC Data Source ---", + f"ucsc_args <- list(genome = '{genome}', tablename = '{track}')", + ] + if which: + r_script_lines.append(f"ucsc_args$range <- GRanges('{which}')") + + r_script_lines.extend([ + "ucsc_data_source <- do.call(UCSCData, ucsc_args)", + "", + "# --- Import Data from UCSC ---", + "gr_object <- rtracklayer::import(ucsc_data_source)", + "", + "# --- Export Data to File ---", + f"export_args <- list(object = gr_object, con = '{output_file.resolve()}')", + ]) + if output_format: + r_script_lines.append(f"export_args$format <- '{output_format}'") + + r_script_lines.extend([ + "do.call(rtracklayer::export, export_args)", + "cat('UCSC data downloaded successfully.\\n')" + ]) + r_script = "\n".join(r_script_lines) + + # 3. Execute R Script + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=".") as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script) + + command = ["Rscript", str(script_path.name)] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=Path.cwd() + ) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with return code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + finally: + script_path.unlink() \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0b9e4af98097e0dcb76085679fcd4bf6b7142d1c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_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-rtracklayer/app/bioconductor-rtracklayer_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rtracklayer' + + +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/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..157e572f2f12f56aa788b6b9d1f6cae0a70d2ee0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rtracklayer: + build: . + image: mcp-bioconductor-rtracklayer:latest + container_name: mcp-bioconductor-rtracklayer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rtracklayer + 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/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a856295b3e4e95df8ebc94bdd0203c76011ff269 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rtracklayer + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-rtracklayer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-s4vectors/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-s4vectors/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-s4vectors/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..862c5654ed91a4cfaa8e41acd84193b7855f55c1 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/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-scaledmatrix via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scaledmatrix -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-scaledmatrix_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-scaledmatrix_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-scaledmatrix_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_server.py b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eb9533ee14f0c5741365e742324dfaa3e58641f8 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_server.py @@ -0,0 +1,288 @@ +from typing import Optional, List, Union +import subprocess +from pathlib import Path +import json +import tempfile + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_scaledmatrix' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def create_scaled_matrix( + input_path: str, + output_path: str, + center: bool = True, + scale: bool = True, + center_vector: Optional[List[float]] = None, + scale_vector: Optional[List[float]] = None, + input_format: str = "rds" +): + """ + Creates a ScaledMatrix object (a DelayedMatrix of scaled and centered values). + The result is equivalent to using the scale() function but avoids explicit realization of a dense matrix. + + Args: + input_path: Path to the input matrix file (RDS, CSV, or TSV). + output_path: Path to save the resulting ScaledMatrix object as an RDS file. + center: Whether to center the columns. Ignored if center_vector is provided. + scale: Whether to scale the columns. Ignored if scale_vector is provided. + center_vector: Specific numeric vector to use for centering (length must match number of columns). + scale_vector: Specific numeric vector to use for scaling (length must match number of columns). + input_format: Format of the input file ('rds', 'csv', 'tsv'). + """ + input_p = Path(input_path) + output_p = Path(output_path) + + if not input_p.exists(): + return {"error": f"Input file not found: {input_path}"} + + # Prepare R arguments for center and scale + r_center = "TRUE" if center else "FALSE" + if center_vector is not None: + r_center = f"c({','.join(map(str, center_vector))})" + + r_scale = "TRUE" if scale else "FALSE" + if scale_vector is not None: + r_scale = f"c({','.join(map(str, scale_vector))})" + + # Construct R script + r_script = f""" + library(ScaledMatrix) + library(Matrix) + + # Load input + if ("{input_format}" == "rds") {{ + x <- readRDS("{input_path}") + }} else if ("{input_format}" == "csv") {{ + x <- as.matrix(read.csv("{input_path}", row.names=1)) + }} else if ("{input_format}" == "tsv") {{ + x <- as.matrix(read.table("{input_path}", sep="\\t", header=TRUE, row.names=1)) + }} else {{ + stop("Unsupported input format") + }} + + # Create ScaledMatrix + sm <- ScaledMatrix(x, center = {r_center}, scale = {r_scale}) + + # Save object + saveRDS(sm, "{output_path}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": f"ScaledMatrix(x, center={r_center}, scale={r_scale})", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_p)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def realize_scaled_matrix( + input_rds_path: str, + output_path: str, + output_format: str = "csv" +): + """ + Realizes a ScaledMatrix object into a dense matrix and saves it to a file. + Use this to get the actual computed values after scaling/centering. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + output_path: Path to save the realized matrix. + output_format: Format of the output file ('csv', 'tsv', 'rds'). + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + mat <- as.matrix(sm) + + if ("{output_format}" == "csv") {{ + write.csv(mat, "{output_path}") + }} else if ("{output_format}" == "tsv") {{ + write.table(mat, "{output_path}", sep="\\t", quote=FALSE) + }} else if ("{output_format}" == "rds") {{ + saveRDS(mat, "{output_path}") + }} + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": "as.matrix(sm)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def get_centering_vector(input_rds_path: str): + """ + Extracts the centering vector from a ScaledMatrix object. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + cat(jsonlite::toJSON(CenteringVector(sm))) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "centering_vector": json.loads(result.stdout), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def get_scaling_factor(input_rds_path: str): + """ + Extracts the scaling factors from a ScaledMatrix object. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + cat(jsonlite::toJSON(ScalingFactor(sm))) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "scaling_factors": json.loads(result.stdout), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def get_unscaled_matrix(input_rds_path: str, output_path: str): + """ + Extracts the original unscaled matrix from a ScaledMatrix object. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + output_path: Path to save the unscaled matrix (as RDS). + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + unscaled_mat <- unscaled(sm) + saveRDS(unscaled_mat, "{output_path}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": "unscaled(sm)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def get_scaled_matrix_metadata(input_rds_path: str): + """ + Returns metadata about the ScaledMatrix object, including dimensions and whether it is centered/scaled. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + info <- list( + dim = dim(sm), + is_centered = !is.null(CenteringVector(sm)), + is_scaled = !is.null(ScalingFactor(sm)), + class = class(sm)[1] + ) + cat(jsonlite::toJSON(info, auto_unbox=TRUE)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "metadata": json.loads(result.stdout), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..78b88833291d53cbc8a95fc0f2ccd98183d6875e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_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-scaledmatrix/app/bioconductor-scaledmatrix_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scaledmatrix' + + +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/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..579e240112737466516689b1a6b524bd1197a6da --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scaledmatrix: + build: . + image: mcp-bioconductor-scaledmatrix:latest + container_name: mcp-bioconductor-scaledmatrix + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scaledmatrix + 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/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..878ec71749037ad915d6b8be492005dbf6be2188 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scaledmatrix + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scaledmatrix/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scalign/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scalign/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b59bf89a693f43400c771a6d529f61bafc3eafa5 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scalign/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-scalign via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scalign -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-scalign_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-scalign_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-scalign_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scalign/app/bioconductor-scalign_server.py b/Biomni/mcp_generated/mcp_bioconductor-scalign/app/bioconductor-scalign_server.py new file mode 100644 index 0000000000000000000000000000000000000000..94598a7833ec0225c8d424ca8723337f8a93142f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scalign/app/bioconductor-scalign_server.py @@ -0,0 +1,224 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Literal + +# NOTE: The `@mcp.tool` decorator is a placeholder. +# In a real MCP environment, it would be provided by the MCP framework. +# For this code to be executable standalone, you would need to define or remove the decorator. +class _MCP: + def tool(self, *args, **kwargs): + def decorator(func): + return func + return decorator +mcp = _MCP() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_scalign' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def scalign( + sce_objects: List[Path], + output_prefix: str, + genes_use_file: Optional[Path] = None, + data_use: str = "counts", + architecture: Literal["small", "medium", "large", "large_deep"] = "large_deep", + num_dim: int = 32, + mini_batch_size: int = 256, + num_steps: int = 10000, + learning_rate: float = 0.001, + log_every: int = 100, + run_tsne: bool = True, + tsne_dims: int = 2, + tsne_perplexity: int = 30, + seed: Optional[int] = None, +) -> dict: + """ + Aligns multiple single-cell datasets using the scAlign R package. + + This tool is a wrapper for the Bioconductor package scAlign, which performs + unsupervised deep learning to align and integrate single-cell genomic data + across different conditions, tissues, or species. The primary input is a list + of SingleCellExperiment objects saved in RDS format. + + Args: + sce_objects: A list of paths to input SingleCellExperiment objects stored in RDS format. + output_prefix: The prefix for all output files. The main output will be an RDS file + named `{output_prefix}_aligned.rds`. + genes_use_file: An optional path to a file containing a list of genes to use for + alignment, one gene per line. If not provided, all shared genes are used. + data_use: The assay name from the SingleCellExperiment objects to use for alignment + (e.g., 'counts', 'logcounts'). + architecture: The neural network architecture to use for the alignment model. + num_dim: The number of dimensions in the latent space. + mini_batch_size: The size of mini-batches for training the neural network. + num_steps: The total number of training steps. + learning_rate: The learning rate for the Adam optimizer. + log_every: The frequency (in steps) to log training progress. + run_tsne: If True, run t-SNE on the aligned cell embeddings. + tsne_dims: The number of dimensions for the t-SNE embedding. + tsne_perplexity: The perplexity parameter for t-SNE. + seed: An optional integer seed for reproducibility. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of + output file paths. + """ + # --- Input Validation --- + if not sce_objects: + raise ValueError("At least one SingleCellExperiment object path must be provided in sce_objects.") + for p in sce_objects: + if not p.is_file(): + raise FileNotFoundError(f"Input file not found: {p}") + + if genes_use_file and not genes_use_file.is_file(): + raise FileNotFoundError(f"Genes file not found: {genes_use_file}") + + if num_dim <= 0: + raise ValueError("num_dim must be a positive integer.") + if mini_batch_size <= 0: + raise ValueError("mini_batch_size must be a positive integer.") + if num_steps <= 0: + raise ValueError("num_steps must be a positive integer.") + if learning_rate <= 0: + raise ValueError("learning_rate must be a positive float.") + if log_every <= 0: + raise ValueError("log_every must be a positive integer.") + if tsne_dims <= 0: + raise ValueError("tsne_dims must be a positive integer.") + if tsne_perplexity <= 0: + raise ValueError("tsne_perplexity must be a positive integer.") + + # --- R Script Generation --- + # This script will be executed by Rscript. It loads the data, runs scAlign, + # and saves the results. + r_script_content = f""" + # Load necessary libraries + library(scAlign) + library(SingleCellExperiment) + + # --- Parse Arguments --- + args <- commandArgs(trailingOnly = TRUE) + output_prefix <- args[1] + data_use <- args[2] + architecture <- args[3] + num_dim <- as.integer(args[4]) + mini_batch_size <- as.integer(args[5]) + num_steps <- as.integer(args[6]) + learning_rate <- as.numeric(args[7]) + log_every <- as.integer(args[8]) + run_tsne <- as.logical(args[9]) + tsne_dims <- as.integer(args[10]) + tsne_perplexity <- as.integer(args[11]) + seed_val <- args[12] + genes_file_path <- args[13] + sce_paths <- args[14:length(args)] + + # --- Set Seed for Reproducibility --- + if (seed_val != "NULL") {{ + set.seed(as.integer(seed_val)) + }} + + # --- Load Data --- + message("Loading SingleCellExperiment objects...") + sce.objects <- lapply(sce_paths, readRDS) + message(paste("Loaded", length(sce.objects), "objects.")) + + # --- Load Genes --- + genes.use <- NULL + if (genes_file_path != "NULL") {{ + message(paste("Reading genes from:", genes_file_path)) + genes.use <- readLines(genes_file_path) + }} + + # --- Run scAlign --- + message("Running scAlign alignment...") + scAlign.result <- scAlign( + sce.objects = sce.objects, + genes.use = genes.use, + data.use = data_use, + options = scAlignOptions( + architecture = architecture, + num.dim = num_dim, + mini.batch.size = mini_batch_size, + num.steps = num_steps, + learning.rate = learning_rate, + log.every = log_every + ), + run.tsne = run_tsne, + tsne.dims = tsne_dims, + tsne.perplexity = tsne_perplexity + ) + message("scAlign finished.") + + # --- Save Output --- + output_rds_path <- paste0(output_prefix, "_aligned.rds") + message(paste("Saving aligned object to:", output_rds_path)) + saveRDS(scAlign.result, file = output_rds_path) + message("Script finished successfully.") + """ + + # --- Subprocess Execution --- + r_script_path = "" + command_executed = "" + try: + 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 + + cmd = [ + "Rscript", + r_script_path, + output_prefix, + data_use, + architecture, + str(num_dim), + str(mini_batch_size), + str(num_steps), + str(learning_rate), + str(log_every), + str(run_tsne).upper(), # R expects TRUE/FALSE + str(tsne_dims), + str(tsne_perplexity), + str(seed) if seed is not None else "NULL", + str(genes_use_file) if genes_use_file is not None else "NULL", + ] + cmd.extend([str(p.resolve()) for p in sce_objects]) + + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [f"{output_prefix}_aligned.rds"] + + 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": "scAlign execution failed.", + "return_code": e.returncode, + "output_files": [], + } + 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/Biomni/mcp_generated/mcp_bioconductor-scalign/app/bioconductor-scalign_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scalign/app/bioconductor-scalign_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..21a60e42a875c84d5b82d24936ed3142b32f0447 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scalign/app/bioconductor-scalign_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-scalign/app/bioconductor-scalign_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scalign' + + +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/Biomni/mcp_generated/mcp_bioconductor-scalign/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-scalign/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b197320002adf2df3eed71f0358d144c8e308035 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scalign/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scalign: + build: . + image: mcp-bioconductor-scalign:latest + container_name: mcp-bioconductor-scalign + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scalign + 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/Biomni/mcp_generated/mcp_bioconductor-scalign/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-scalign/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b20c4d1e54e4c60f5efb46364108fdf4f769534 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scalign/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scalign + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scalign/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scalign/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scalign/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2a2ae6de9292099994cb6deedf1e0671bc84fe9c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/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-scarray.sat via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scarray.sat -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-scarray.sat_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-scarray.sat_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-scarray.sat_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_server.py b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a64e65c8ea3e318e6c41dec8f5e6518aad7a83c3 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_server.py @@ -0,0 +1,146 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, Optional + +# MCP decorator is assumed to be available from the environment +# import mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_scarray_sat' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def create_gds_seurat_object( + input_dir: Path, + output_rds: Path, + output_gds: Path, + project_name: str = "scproject", + min_cells: int = 3, + min_features: int = 200, +) -> Dict: + """ + Creates a GDS-backed Seurat object from 10x Genomics data using SCArray.sat. + + This tool wraps the bioconductor-scarray.sat R package to convert a standard + 10x Genomics count matrix directory (containing matrix.mtx, features.tsv, + and barcodes.tsv files) into a Seurat object. The key feature is that the + count matrix is stored in a memory-efficient Genomic Data Structure (GDS) file, + making it suitable for very large datasets. + + Args: + input_dir: Path to the input directory containing 10x Genomics data files + (e.g., 'matrix.mtx.gz', 'features.tsv.gz', 'barcodes.tsv.gz'). + output_rds: Path to save the output Seurat object (.rds file). + output_gds: Path to save the generated Genomic Data Structure (.gds file). + project_name: Name for the Seurat project. + min_cells: Include features detected in at least this many cells. + min_features: Include cells with at least this many detected features. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a + dictionary of output file paths. + """ + # --- Input Validation --- + if not input_dir.is_dir(): + raise ValueError(f"Input directory '{input_dir}' does not exist or is not a directory.") + + # Check for required 10x files (allowing for .gz extension and alternative names) + barcodes_path = next(input_dir.glob("barcodes.tsv*"), None) + features_path = next(input_dir.glob("features.tsv*"), None) or next(input_dir.glob("genes.tsv*"), None) + matrix_path = next(input_dir.glob("matrix.mtx*"), None) + + if not all([barcodes_path, features_path, matrix_path]): + raise FileNotFoundError( + "The input directory must contain 'barcodes.tsv', 'features.tsv' (or 'genes.tsv'), " + "and 'matrix.mtx'. Compressed versions (.gz) are accepted." + ) + + if min_cells < 0: + raise ValueError("min_cells must be a non-negative integer.") + if min_features < 0: + raise ValueError("min_features must be a non-negative integer.") + + # --- R Script Generation --- + # This script performs the core logic using the R libraries. + r_script_content = f""" + # Load required libraries + library(Seurat) + library(SCArray.sat) + library(SCArray) + + # Define parameters passed from the Python wrapper + input_dir_path <- "{input_dir.resolve()}" + output_rds_path <- "{output_rds.resolve()}" + output_gds_path <- "{output_gds.resolve()}" + project_id <- "{project_name}" + min_cell_count <- {min_cells} + min_feature_count <- {min_features} + + # Read the 10X data. Read10X handles compressed files automatically. + counts <- Seurat::Read10X(data.dir = input_dir_path) + + # Create the GDS file from the count matrix. This is the main step + # provided by the SCArray package. + SCArray::scarray_create(output_gds_path, counts, verbose = TRUE) + + # Create the Seurat object using the GDS-backed matrix. + # The scarray() function loads the GDS file as a DelayedMatrix object. + seurat_obj <- Seurat::CreateSeuratObject( + counts = SCArray::scarray(output_gds_path), + project = project_id, + min.cells = min_cell_count, + min.features = min_feature_count + ) + + # Save the final Seurat object to an RDS file for later use in R. + saveRDS(seurat_obj, file = output_rds_path) + + cat("Successfully created GDS-backed Seurat object and saved to RDS.\\n") + """ + + # --- Subprocess Execution --- + # Use a temporary file to hold the R script + 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) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + # --- Return Structured Output --- + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "seurat_object_rds": str(output_rds.resolve()), + "gds_file": str(output_gds.resolve()) + } + } + except subprocess.CalledProcessError as e: + # --- Error Handling --- + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "R script execution failed. Please check the logs for details from Seurat or SCArray." + } + finally: + # Ensure the temporary R script is cleaned up + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..929731a485bdf666500546a79b7a218be493bb89 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_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-scarray.sat/app/bioconductor-scarray.sat_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scarray_sat' + + +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/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..db5d8105ceb8dd08e531d26a061c149becd2a8cb --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scarray.sat: + build: . + image: mcp-bioconductor-scarray.sat:latest + container_name: mcp-bioconductor-scarray.sat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scarray.sat + 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/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..af4e00630553847553f47ff1414b313f83f1b409 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scarray.sat + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scarray.sat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scater/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scater/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ecac8858d36b4624367e8f98d559c4516e813f36 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scater/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-scater via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scater -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-scater_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-scater_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-scater_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_server.py b/Biomni/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_server.py new file mode 100644 index 0000000000000000000000000000000000000000..073da0c304d07ed6cf2081cc74be6357b8e69b36 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_server.py @@ -0,0 +1,215 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import List, Optional + + +def _validate_r_input(input_path: Path): + """Check if the input file exists and has a .rds extension.""" + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_path}") + if input_path.suffix.lower() != ".rds": + raise ValueError(f"Input file must be an RDS file (*.rds), but got: {input_path}") + +# @mcp.tool() decorator would be here in a real MCP environment +def run_scater_workflow( + input_sce_rds: Path, + output_prefix: str = "scater_analysis", + mito_pattern: str = "^MT-", + nmads: float = 3.0, + min_library_size: Optional[int] = None, + min_features: Optional[int] = None, + max_mito_percent: Optional[float] = None, + run_pca: bool = True, + n_pca_components: int = 50, + run_tsne: bool = True, + tsne_perplexity: int = 30, + run_umap: bool = True, + umap_n_neighbors: int = 15, + n_top_features_plot: int = 20, + plot_format: str = "png", +) -> dict: + """ + Executes a standard scRNA-seq QC and visualization workflow using the scater R package. + + This tool takes a SingleCellExperiment object (in RDS format), calculates quality + control metrics, performs filtering, normalizes the data, runs dimensionality + reduction (PCA, t-SNE, UMAP), and generates diagnostic plots. + + Args: + input_sce_rds: Path to the input SingleCellExperiment object saved as an RDS file. + output_prefix: Prefix for all output files (e.g., plots, processed RDS). + mito_pattern: Regex pattern to identify mitochondrial genes for QC. + nmads: Number of median absolute deviations (MADs) to use for adaptive thresholding in QC filtering. + min_library_size: If set, filters cells with a total library size (sum of counts) below this value. Overrides MAD-based filtering for library size. + min_features: If set, filters cells with a number of detected features below this value. Overrides MAD-based filtering for features. + max_mito_percent: If set, filters cells with a mitochondrial read percentage above this value. Overrides MAD-based filtering for mito percent. + run_pca: Whether to perform Principal Component Analysis (PCA). + n_pca_components: Number of principal components to compute. + run_tsne: Whether to perform t-SNE dimensionality reduction. + tsne_perplexity: Perplexity parameter for the t-SNE algorithm. + run_umap: Whether to perform UMAP dimensionality reduction. + umap_n_neighbors: Number of neighbors parameter for the UMAP algorithm. + n_top_features_plot: Number of top expressed features to include in the summary plot. + plot_format: The file format for the output plots ('png', 'pdf', 'svg'). + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # --- Input Validation --- + _validate_r_input(input_sce_rds) + if n_pca_components <= 0: + raise ValueError("n_pca_components must be a positive integer.") + if tsne_perplexity <= 0: + raise ValueError("tsne_perplexity must be a positive integer.") + if umap_n_neighbors <= 0: + raise ValueError("umap_n_neighbors must be a positive integer.") + if n_top_features_plot <= 0: + raise ValueError("n_top_features_plot must be a positive integer.") + if plot_format.lower() not in ["png", "pdf", "svg"]: + raise ValueError("plot_format must be one of 'png', 'pdf', or 'svg'.") + + # --- R Script Generation --- + # Note: Modern scater relies heavily on scuttle for QC and normalization. + # The script reflects current best practices. + r_script_content = textwrap.dedent(f""" + # Load necessary libraries + suppressPackageStartupMessages(library(scater)) + suppressPackageStartupMessages(library(scuttle)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + suppressPackageStartupMessages(library(ggplot2)) + suppressPackageStartupMessages(library(BiocParallel)) + + # Set a seed for reproducibility + set.seed(42) + + # --- 1. Load Data --- + cat("Loading input SingleCellExperiment object from {input_sce_rds}\\n") + sce <- readRDS("{input_sce_rds}") + + # --- 2. Quality Control --- + cat("Calculating per-cell QC metrics...\\n") + mito_genes <- grepl("{mito_pattern}", rownames(sce)) + sce <- addPerCellQC(sce, subsets=list(Mito=mito_genes), BPPARAM=SerialParam()) + + # --- 3. Filtering --- + cat("Filtering low-quality cells...\\n") + # Using isOutlier from scuttle for adaptive filtering + qc_reasons <- perCellQCFilters(sce, sub.fields="subsets_Mito_percent", nmads={nmads}) + + # Override with fixed thresholds if provided + if (!is.null({min_library_size if min_library_size is not None else 'NULL'})) {{ + qc_reasons$low_libsize <- sce$sum < {min_library_size} + }} + if (!is.null({min_features if min_features is not None else 'NULL'})) {{ + qc_reasons$low_n_features <- sce$detected < {min_features} + }} + if (!is.null({max_mito_percent if max_mito_percent is not None else 'NULL'})) {{ + qc_reasons$high_subsets_Mito_percent <- sce$subsets_Mito_percent > {max_mito_percent} + }} + + # Combine filters and subset the object + colData(sce)$discard <- qc_reasons$discard + sce_filtered <- sce[, !sce$discard] + cat(paste("Removed", sum(sce$discard), "cells out of", ncol(sce), "\\n")) + cat(paste("Remaining cells:", ncol(sce_filtered), "\\n")) + + # --- 4. Normalization --- + cat("Performing log-normalization...\\n") + sce_filtered <- logNormCounts(sce_filtered) + + # --- 5. Dimensionality Reduction --- + if ({str(run_pca).upper()}) {{ + cat("Running PCA...\\n") + sce_filtered <- runPCA(sce_filtered, ncomponents={n_pca_components}) + }} + if ({str(run_tsne).upper()}) {{ + cat("Running t-SNE...\\n") + sce_filtered <- runTSNE(sce_filtered, dimred="PCA", perplexity={tsne_perplexity}, BPPARAM=SerialParam()) + }} + if ({str(run_umap).upper()}) {{ + cat("Running UMAP...\\n") + sce_filtered <- runUMAP(sce_filtered, dimred="PCA", n_neighbors={umap_n_neighbors}) + }} + + # --- 6. Visualization --- + cat("Generating plots...\\n") + plot_ext <- ".{plot_format.lower()}" + + # Plot QC metrics on original data + p1 <- plotColData(sce, x="sum", y="detected", colour_by="discard", + other_fields="subsets_Mito_percent") + + scale_x_log10() + scale_y_log10() + + labs(title="QC: Library Size vs Features", x="Total Counts (log10)", y="Detected Features (log10)") + + guides(colour=guide_legend(title="Discarded"), size=guide_legend(title="Mito %")) + ggsave(paste0("{output_prefix}_qc_metrics", plot_ext), p1, width=7, height=5) + + # Plot highest expressed features + p2 <- plotHighestExprs(sce_filtered, n={n_top_features_plot}) + + labs(title="Top Expressed Features") + ggsave(paste0("{output_prefix}_highest_exprs", plot_ext), p2, width=8, height=6) + + # Plot reduced dimensions + if ({str(run_pca).upper()}) {{ + p_pca <- plotReducedDim(sce_filtered, "PCA", colour_by="sum") + + labs(title="PCA colored by Library Size") + ggsave(paste0("{output_prefix}_pca", plot_ext), p_pca, width=6, height=5) + }} + if ({str(run_tsne).upper()}) {{ + p_tsne <- plotReducedDim(sce_filtered, "TSNE", colour_by="detected") + + labs(title="t-SNE colored by Detected Features") + ggsave(paste0("{output_prefix}_tsne", plot_ext), p_tsne, width=6, height=5) + }} + if ({str(run_umap).upper()}) {{ + p_umap <- plotReducedDim(sce_filtered, "UMAP", colour_by="subsets_Mito_percent") + + labs(title="UMAP colored by Mito %") + ggsave(paste0("{output_prefix}_umap", plot_ext), p_umap, width=6, height=5) + }} + + # --- 7. Save Processed Object --- + output_rds_path <- paste0("{output_prefix}_processed.rds") + cat(paste("Saving processed SingleCellExperiment object to", output_rds_path, "\\n")) + saveRDS(sce_filtered, file=output_rds_path) + + cat("Workflow completed successfully.\\n") + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "scater_script.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=temp_path, # Run in temp_dir to catch output files + ) + + # --- Collect Output Files --- + output_files: List[str] = [] + for f in temp_path.glob(f"{output_prefix}*"): + # In a real scenario, you'd move these to a persistent output directory + output_files.append(str(f.resolve())) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Scater R script execution failed.", + "return_code": e.returncode, + } diff --git a/Biomni/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c47cf4739272b6fa86f0c3b477265ef4fd21fdcb --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_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-scater/app/bioconductor-scater_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scater' + + +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/Biomni/mcp_generated/mcp_bioconductor-scater/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scater/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scater/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-scater/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-scater/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2cee130eee4b88d8d1c1eb77ebf9173ae81d9e07 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scater/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scater: + build: . + image: mcp-bioconductor-scater:latest + container_name: mcp-bioconductor-scater + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scater + 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/Biomni/mcp_generated/mcp_bioconductor-scater/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-scater/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e2a13db73602caa732ca760f80d8e2a9c6c4493 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scater/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scater + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scater/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scater/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scater/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scbfa/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scbfa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..94ff6db8337a62074ee000d9331841b428126b2e --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_server.py b/Biomni/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b179a68910946e7b326ce16ef4b74822ce00516 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scbfa/app/bioconductor-scbfa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..91f0c1c503f49e85d297d4362ccd9526c5b99401 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scbfa/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-scbfa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8ddfddb024ad9c91d3fc9d4cd013f1cb9d9e00b1 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scbfa/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-scbfa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0e5aaa29f0c7f136ee493fe61a322bcf41a2787f --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scbfa/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scbfa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scbfa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..41a95da8aa5b5a70f34d14b5821dab5b2ac86b27 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/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-scbubbletree via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scbubbletree -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-scbubbletree_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-scbubbletree_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-scbubbletree_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_server.py b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_server.py new file mode 100644 index 0000000000000000000000000000000000000000..64a2256111ce5f28dc044b2be5c4624d8ff98d31 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_server.py @@ -0,0 +1,217 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Per the user's instructions, the mcp decorator is assumed to be available +# in the execution environment, so no import is needed. +# For local testing, a dummy decorator can be used: +# class mcp: +# @staticmethod +# def tool(): +# def decorator(func): +# return func +# return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_scbubbletree' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def scbubbletree( + sce_file: Path, + output_file: Path, + group: str, + feature: str, + node_level: str, + node_color: Optional[str] = None, + node_label: Optional[str] = None, + node_size: Optional[str] = None, + node_shape: Optional[str] = None, + edge_label: Optional[str] = None, + edge_width: Optional[str] = None, + edge_arrow_size: Optional[float] = None, + layout: str = "tree", + direction: str = "down", + scale: str = "log", + plot_width: float = 10.0, + plot_height: float = 8.0, +): + """ + Generates a bubble tree plot for visualizing hierarchical relationships in single-cell data. + + This tool is a wrapper around the R/Bioconductor package 'scBubbleTree'. It takes a + SingleCellExperiment object (in RDS format) and various plotting parameters to + create a customizable bubble tree visualization. The main function covered is scBubbleTree(). + + Args: + sce_file: Path to the input SingleCellExperiment object saved in RDS format. + output_file: Path to save the output plot file (e.g., 'plot.pdf', 'plot.png'). + group: The name of the column in colData(sce) that contains the cell group information. + feature: A comma-separated string of feature names (e.g., genes) to be plotted. + node_level: The name of the column in colData(sce) that contains the node level information for the tree structure. + node_color: The name of the column in colData(sce) to be used for coloring the nodes. + node_label: The name of the column in colData(sce) to be used for labeling the nodes. + node_size: The name of the column in colData(sce) to be used for sizing the nodes. + node_shape: The name of the column in colData(sce) to be used for the shape of the nodes. + edge_label: The name of the column in colData(sce) to be used for labeling the edges. + edge_width: The name of the column in colData(sce) to be used for the width of the edges. + edge_arrow_size: A numeric value indicating the size of the arrowheads on the edges. + layout: The layout of the tree (default: 'tree'). Passed to ggraph. + direction: The direction of the tree layout (default: 'down'). + scale: The scale to be used for the bubble size (default: 'log'). + plot_width: The width of the output plot in inches (default: 10.0). + plot_height: The height of the output plot in inches (default: 8.0). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not sce_file.is_file(): + raise FileNotFoundError(f"Input SCE file not found: {sce_file}") + + if not output_file.parent.exists(): + logger.info(f"Output directory {output_file.parent} does not exist. Creating it.") + output_file.parent.mkdir(parents=True, exist_ok=True) + elif not output_file.parent.is_dir(): + raise NotADirectoryError(f"The parent path of the output file is not a directory: {output_file.parent}") + + if not feature: + raise ValueError("The 'feature' parameter cannot be an empty string.") + + if plot_width <= 0 or plot_height <= 0: + raise ValueError("Plot width and height must be positive values.") + + if edge_arrow_size is not None and edge_arrow_size < 0: + raise ValueError("Edge arrow size must be a non-negative value if specified.") + + # --- R Script Generation --- + def r_format(value): + """Helper to convert Python types to R-compatible string representations.""" + if value is None: + return "NULL" + elif isinstance(value, (str, Path)): + # Escape backslashes and quotes for R string + clean_value = str(value).replace('\\', '\\\\').replace('"', '\\"') + return f'"{clean_value}"' + else: + return str(value) + + r_script_content = f""" + # Ensure all required packages are installed and loaded + packages <- c("scBubbleTree", "SingleCellExperiment", "ggplot2") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) {{ + stop(paste("Package '", pkg, "' is not installed. Please install it."), call. = FALSE) + }} + }} + library(scBubbleTree) + library(SingleCellExperiment) + library(ggplot2) + + # --- Read Inputs from Python wrapper --- + sce_file_path <- {r_format(sce_file)} + output_file_path <- {r_format(output_file)} + + # Read the SingleCellExperiment object + sce <- readRDS(sce_file_path) + + # Parse features from comma-separated string + features <- unlist(strsplit({r_format(feature)}, ",")) + + # --- Build Argument List for scBubbleTree --- + sc_args <- list( + sce = sce, + group = {r_format(group)}, + feature = features, + node.level = {r_format(node_level)}, + node.color = {r_format(node_color)}, + node.label = {r_format(node_label)}, + node.size = {r_format(node_size)}, + node.shape = {r_format(node_shape)}, + edge.label = {r_format(edge_label)}, + edge.width = {r_format(edge_width)}, + edge.arrow.size = {r_format(edge_arrow_size)}, + layout = {r_format(layout)}, + direction = {r_format(direction)}, + scale = {r_format(scale)} + ) + + # Remove NULL arguments from the list to use R function defaults + sc_args <- sc_args[!sapply(sc_args, is.null)] + + # --- Execute scBubbleTree and Save Plot --- + tryCatch({{ + # Generate the plot object + p <- do.call(scBubbleTree, sc_args) + + # Save the plot to the specified file + ggsave( + filename = output_file_path, + plot = p, + width = {plot_width}, + height = {plot_height}, + units = "in", + dpi = 300 + ) + + cat("Successfully generated and saved the bubble tree plot to:", output_file_path, "\\n") + + }}, error = function(e) {{ + # Print a more informative error message to stderr + write(paste("Error in scBubbleTree execution:", e$message), stderr()) + quit(status = 1, save = "no") + }}) + """ + + # --- Subprocess Execution --- + command = [] + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + command = ["Rscript", script_path] + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.") + except subprocess.CalledProcessError as e: + logger.error(f"R script failed with exit code {e.returncode}.") + logger.error(f"STDOUT: {e.stdout}") + logger.error(f"STDERR: {e.stderr}") + raise RuntimeError( + f"R script execution failed. Please check the logs and input parameters.\n" + f"Command: {' '.join(command)}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up the temporary R script file + if script_path and Path(script_path).exists(): + Path(script_path).unlink() + + # --- Structured Result Return --- + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_file)] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..acae180cab70f7d208c247de3a5da7728c5f6814 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_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-scbubbletree/app/bioconductor-scbubbletree_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scbubbletree' + + +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/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a6a5d46ad7336b70ac46e4328d13acb8f021e3af --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scbubbletree: + build: . + image: mcp-bioconductor-scbubbletree:latest + container_name: mcp-bioconductor-scbubbletree + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scbubbletree + 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/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ae5e1881049c0646c50d3c1d832049326b49d71 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scbubbletree + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scbubbletree/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-sccb2/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-sccb2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ef9f5c761e496cb49c647c4b468c551764238a6f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-sccb2/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-sccb2 via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-sccb2 -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-sccb2_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-sccb2_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-sccb2_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-sccb2/app/bioconductor-sccb2_server.py b/Biomni/mcp_generated/mcp_bioconductor-sccb2/app/bioconductor-sccb2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..24a6e8ec5dd199871036095be14deef4f459d48f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-sccb2/app/bioconductor-sccb2_server.py @@ -0,0 +1,143 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# In a real MCP environment, the 'mcp' object with the 'tool' decorator +# would be provided by the MCP framework. +# from mcp import tool +# +# For demonstration purposes, a placeholder is defined. +class _MCP: + def tool(self, *args, **kwargs): + def decorator(f): + return f + return decorator +mcp = _MCP() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_sccb2' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_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, +): + """ + Executes an R script using the Rscript command-line interface. + + This tool is a generic wrapper for the 'Rscript' command, designed to run scripts + from Bioconductor packages like 'sccb2' or any other R script. You can either + provide a path to an R script file or a list of R expressions to be executed directly. + + Args: + script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute using the '-e' flag. Mutually exclusive with 'script_file'. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, prints information on progress. Corresponds to the --verbose flag. + default_packages: A comma-separated string of package names to be loaded. Corresponds to --default-packages. + save: If True, saves the workspace at the end of the session. Corresponds to --save. + no_environ: If True, does not read the site and user environment files. Corresponds to --no-environ. + no_site_file: If True, does not read the site-wide Rprofile. Corresponds to --no-site-file. + no_init_file: If True, does not read 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. + This option overrides the individual flags if set. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Note: 'output_files' will be empty as the script's outputs are not known beforehand. + """ + # --- Input Validation --- + if script_file and expressions: + raise ValueError("Parameters 'script_file' and 'expressions' are mutually exclusive. Please provide only one.") + if not script_file and not expressions: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"Input script file not found at: {script_file}") + + # --- Command Construction --- + base_command = "Rscript" + command = [base_command] + + # Handle R session options + 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") + + # Handle Rscript-specific options + if verbose: + command.append("--verbose") + if default_packages: + command.extend(["--default-packages", default_packages]) + + # Add expressions or script file to the command + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + elif script_file: + command.append(str(script_file)) + + # Add arguments for the R script + if script_args: + command.extend(script_args) + + command_str = " ".join(command) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + + except FileNotFoundError: + raise RuntimeError(f"Error: '{base_command}' not found. Is R installed and in your system's PATH?") + except subprocess.CalledProcessError as e: + # The process failed. Return a structured error with captured output. + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + # Since the output files are determined by the R script itself, + # we cannot predict them here. We return an empty list. + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-sccb2/app/bioconductor-sccb2_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-sccb2/app/bioconductor-sccb2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..98d8e30154308a0c0fe8948488877961fbeead5f --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-sccb2/app/bioconductor-sccb2_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-sccb2/app/bioconductor-sccb2_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_sccb2' + + +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/Biomni/mcp_generated/mcp_bioconductor-sccb2/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-sccb2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..64f80f2c0b9fee1954c7a433abd544684a676332 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-sccb2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-sccb2: + build: . + image: mcp-bioconductor-sccb2:latest + container_name: mcp-bioconductor-sccb2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-sccb2 + 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/Biomni/mcp_generated/mcp_bioconductor-sccb2/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-sccb2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f49b35fc0692ce48114a48bf1bbad3003d57ff13 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-sccb2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-sccb2 + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-sccb2/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-sccb2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-sccb2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scclassifr/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0199e6470eb8a2609d41ef0bd1ef8f0982c7c79b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/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-scclassifr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scclassifr -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-scclassifr_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-scclassifr_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-scclassifr_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_server.py b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9a367ac0358f8cbc21bdff55a46dc0de7fe299c2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_server.py @@ -0,0 +1,439 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Literal, Optional, List, Dict, Any + +# This is a placeholder for the actual MCP decorator as per the instructions. +# In a real MCP environment, you would use `from mcp import tool`. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +# Define the available algorithms as a Literal type for type safety and validation +Algorithm = Literal["logistic", "svm", "randomforest", "dlda", "scmap", "scsorter", "seurat"] + +# --- R Script Templates --- +# These scripts are executed by the Python functions to interact with the scClassifR library. + +R_TRAIN_SCRIPT = """ +# R script to train a scClassifR model +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(scClassifR)) + +option_list <- list( + make_option(c("-e", "--expr_mat"), type="character", default=NULL, + help="Path to the expression matrix CSV file (cells as columns, genes as rows)", metavar="character"), + make_option(c("-c", "--cell_types"), type="character", default=NULL, + help="Path to the cell types CSV file (two columns: cell_id, cell_type)", metavar="character"), + make_option(c("-a", "--algorithm"), type="character", default="logistic", + help="Classification algorithm to use", metavar="character"), + make_option(c("-o", "--output_model"), type="character", default="model.rds", + help="Path to save the output model RDS file", metavar="character") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$expr_mat) || is.null(opt$cell_types)){ + print_help(opt_parser) + stop("Expression matrix and cell types files must be supplied.", call.=FALSE) +} + +# Read data +message("Reading expression matrix...") +expr_mat <- as.matrix(read.csv(opt$expr_mat, row.names=1, check.names=FALSE)) +message("Reading cell types...") +cell_types_df <- read.csv(opt$cell_types) + +# Align cell types with expression matrix columns +if (ncol(cell_types_df) < 2) { + stop("Cell types file must have at least two columns (e.g., cell_id, cell_type).", call.=FALSE) +} +colnames(cell_types_df)[1:2] <- c("cell_id", "cell_type") +cell_types_vec <- cell_types_df$cell_type +names(cell_types_vec) <- cell_types_df$cell_id +cell_types_aligned <- cell_types_vec[colnames(expr_mat)] + +if(any(is.na(cell_types_aligned))) { + warning("Some cells in the expression matrix do not have a corresponding cell type. These will be ignored.") + valid_cells <- !is.na(cell_types_aligned) + expr_mat <- expr_mat[, valid_cells] + cell_types_aligned <- cell_types_aligned[valid_cells] +} + +# Train model +message("Training model with algorithm: ", opt$algorithm) +fit <- run_scClassifR(expr_mat = expr_mat, + cell_type = cell_types_aligned, + algorithm = opt$algorithm) + +# Save model +message("Saving model to: ", opt$output_model) +saveRDS(fit, file = opt$output_model) + +message("Training complete.") +""" + +R_PREDICT_SCRIPT = """ +# R script to predict using a trained scClassifR model +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(scClassifR)) + +option_list <- list( + make_option(c("-t", "--test_data"), type="character", default=NULL, + help="Path to the test data matrix CSV file (cells as columns, genes as rows)", metavar="character"), + make_option(c("-m", "--model"), type="character", default=NULL, + help="Path to the trained model RDS file", metavar="character"), + make_option(c("-o", "--output_predictions"), type="character", default="predictions.csv", + help="Path to save the output predictions CSV file", metavar="character") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$test_data) || is.null(opt$model)){ + print_help(opt_parser) + stop("Test data and model file must be supplied.", call.=FALSE) +} + +# Read data and model +message("Reading test data from: ", opt$test_data) +test_data <- as.matrix(read.csv(opt$test_data, row.names=1, check.names=FALSE)) + +message("Loading model from: ", opt$model) +fit <- readRDS(opt$model) + +# Predict +message("Predicting cell types...") +predictions <- predict_scClassifR(test_data = test_data, + fit = fit) + +# Standardize and save predictions +pred_df <- data.frame(cell_id = colnames(test_data), + predicted_cell_type = predictions$pred_labs) + +message("Saving predictions to: ", opt$output_predictions) +write.csv(pred_df, file = opt$output_predictions, row.names = FALSE) + +message("Prediction complete.") +""" + +R_CLASSIFY_SCRIPT = """ +# R script to train and predict with scClassifR in one step +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(scClassifR)) + +option_list <- list( + make_option(c("--train_data"), type="character", default=NULL, + help="Path to the training expression matrix CSV file", metavar="character"), + make_option(c("--train_cell_types"), type="character", default=NULL, + help="Path to the training cell types CSV file", metavar="character"), + make_option(c("--test_data"), type="character", default=NULL, + help="Path to the test expression matrix CSV file", metavar="character"), + make_option(c("-a", "--algorithm"), type="character", default="logistic", + help="Classification algorithm to use", metavar="character"), + make_option(c("-o", "--output_predictions"), type="character", default="predictions.csv", + help="Path to save the output predictions CSV file", metavar="character"), + make_option(c("-m", "--output_model"), type="character", default=NULL, + help="Optional path to save the trained model RDS file", metavar="character") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$train_data) || is.null(opt$train_cell_types) || is.null(opt$test_data)){ + print_help(opt_parser) + stop("Training data, training cell types, and test data must be supplied.", call.=FALSE) +} + +# Read training data +message("Reading training data...") +train_data <- as.matrix(read.csv(opt$train_data, row.names=1, check.names=FALSE)) +train_cell_types_df <- read.csv(opt$train_cell_types) + +# Align training cell types +if (ncol(train_cell_types_df) < 2) { + stop("Training cell types file must have at least two columns (e.g., cell_id, cell_type).", call.=FALSE) +} +colnames(train_cell_types_df)[1:2] <- c("cell_id", "cell_type") +train_cell_types_vec <- train_cell_types_df$cell_type +names(train_cell_types_vec) <- train_cell_types_df$cell_id +train_cell_types_aligned <- train_cell_types_vec[colnames(train_data)] + +if(any(is.na(train_cell_types_aligned))) { + warning("Some cells in the training expression matrix do not have a corresponding cell type. These will be ignored.") + valid_cells <- !is.na(train_cell_types_aligned) + train_data <- train_data[, valid_cells] + train_cell_types_aligned <- train_cell_types_aligned[valid_cells] +} + +# Read test data +message("Reading test data...") +test_data <- as.matrix(read.csv(opt$test_data, row.names=1, check.names=FALSE)) + +# Classify +message("Running classification with algorithm: ", opt$algorithm) +results <- classify_scClassifR(train_data = train_data, + train_cell_type = train_cell_types_aligned, + test_data = test_data, + algorithm = opt$algorithm) + +# Save predictions +pred_df <- data.frame(cell_id = colnames(test_data), + predicted_cell_type = results$pred_labs) + +message("Saving predictions to: ", opt$output_predictions) +write.csv(pred_df, file = opt$output_predictions, row.names = FALSE) + +# Optionally save model +if (!is.null(opt$output_model)) { + message("Saving model to: ", opt$output_model) + saveRDS(results$fit, file = opt$output_model) +} + +message("Classification complete.") +""" + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_scclassifr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def scclassifr_train( + expression_matrix: Path, + cell_types: Path, + output_model_path: Path, + algorithm: Algorithm = "logistic", +) -> Dict[str, Any]: + """ + Trains a scClassifR model on a given expression matrix and cell type labels. + + This tool requires R to be installed in the environment, along with the + Bioconductor package 'scClassifR' and the CRAN package 'optparse'. + + Args: + expression_matrix: Path to the expression matrix CSV file. The first column + should be gene names/IDs (and set as row names), and + subsequent columns should be cell IDs. + cell_types: Path to the cell types CSV file. It must contain at least + two columns: the first for cell IDs (matching the expression + matrix) and the second for cell type labels. + output_model_path: Path to save the trained model as an RDS file. + algorithm: The classification algorithm to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + the path to the output model file. + """ + # Input validation + if not expression_matrix.is_file(): + raise FileNotFoundError(f"Expression matrix file not found: {expression_matrix}") + if not cell_types.is_file(): + raise FileNotFoundError(f"Cell types file not found: {cell_types}") + + command_executed = "" + r_script_path_str = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(R_TRAIN_SCRIPT) + r_script_path_str = r_script_file.name + + cmd = [ + "Rscript", + r_script_path_str, + "--expr_mat", str(expression_matrix.resolve()), + "--cell_types", str(cell_types.resolve()), + "--algorithm", algorithm, + "--output_model", str(output_model_path.resolve()), + ] + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_model_path.resolve())] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + finally: + if r_script_path_str and Path(r_script_path_str).exists(): + Path(r_script_path_str).unlink() + +@mcp.tool() +def scclassifr_predict( + test_data: Path, + model: Path, + output_predictions_path: Path, +) -> Dict[str, Any]: + """ + Predicts cell types for a test dataset using a pre-trained scClassifR model. + + This tool requires R to be installed in the environment, along with the + Bioconductor package 'scClassifR' and the CRAN package 'optparse'. + + Args: + test_data: Path to the test data expression matrix CSV file. Format should + match the training data (genes as rows, cells as columns). + model: Path to the pre-trained model RDS file generated by scclassifr_train. + output_predictions_path: Path to save the prediction results as a CSV file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + the path to the output predictions file. + """ + # Input validation + if not test_data.is_file(): + raise FileNotFoundError(f"Test data file not found: {test_data}") + if not model.is_file(): + raise FileNotFoundError(f"Model file not found: {model}") + + command_executed = "" + r_script_path_str = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(R_PREDICT_SCRIPT) + r_script_path_str = r_script_file.name + + cmd = [ + "Rscript", + r_script_path_str, + "--test_data", str(test_data.resolve()), + "--model", str(model.resolve()), + "--output_predictions", str(output_predictions_path.resolve()), + ] + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_predictions_path.resolve())] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + finally: + if r_script_path_str and Path(r_script_path_str).exists(): + Path(r_script_path_str).unlink() + +@mcp.tool() +def scclassifr_classify( + train_data: Path, + train_cell_types: Path, + test_data: Path, + output_predictions_path: Path, + algorithm: Algorithm = "logistic", + output_model_path: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Trains a scClassifR model and predicts on a test set in a single step. + + This tool requires R to be installed in the environment, along with the + Bioconductor package 'scClassifR' and the CRAN package 'optparse'. + + Args: + train_data: Path to the training expression matrix CSV file. + train_cell_types: Path to the training cell types CSV file. + test_data: Path to the test expression matrix CSV file. + output_predictions_path: Path to save the prediction results as a CSV file. + algorithm: The classification algorithm to use. + output_model_path: Optional path to save the trained model as an RDS file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + paths to the output files (predictions and optionally the model). + """ + # Input validation + if not train_data.is_file(): + raise FileNotFoundError(f"Training data file not found: {train_data}") + if not train_cell_types.is_file(): + raise FileNotFoundError(f"Training cell types file not found: {train_cell_types}") + if not test_data.is_file(): + raise FileNotFoundError(f"Test data file not found: {test_data}") + + command_executed = "" + r_script_path_str = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(R_CLASSIFY_SCRIPT) + r_script_path_str = r_script_file.name + + cmd = [ + "Rscript", + r_script_path_str, + "--train_data", str(train_data.resolve()), + "--train_cell_types", str(train_cell_types.resolve()), + "--test_data", str(test_data.resolve()), + "--algorithm", algorithm, + "--output_predictions", str(output_predictions_path.resolve()), + ] + + if output_model_path: + cmd.extend(["--output_model", str(output_model_path.resolve())]) + + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + output_files = [str(output_predictions_path.resolve())] + if output_model_path: + output_files.append(str(output_model_path.resolve())) + + 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"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + finally: + if r_script_path_str and Path(r_script_path_str).exists(): + Path(r_script_path_str).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3bda7540168bde12a7c4fa6c97f9e99050e2803b --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_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-scclassifr/app/bioconductor-scclassifr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scclassifr' + + +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/Biomni/mcp_generated/mcp_bioconductor-scclassifr/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f82f48002d24d6289d3b99f9fba2179a4f651aae --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scclassifr: + build: . + image: mcp-bioconductor-scclassifr:latest + container_name: mcp-bioconductor-scclassifr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scclassifr + 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/Biomni/mcp_generated/mcp_bioconductor-scclassifr/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3fb43e58b7333525a1ea7c834d4fb1019f2b9276 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scclassifr + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scclassifr/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scclassifr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scdataviz/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scdataviz/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c926501a4fd661158e18096512c4e1f1481c6b4a --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_server.py b/Biomni/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6262e5ea82010f6d2290e68c395b98fca31465c2 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae6d36752c30e737cf704bf9bcfccc71b2e9591 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scdataviz/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-scdataviz/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c505a0ca6bc8f3d61067bbe38ad54952de78ce99 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scdataviz/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-scdataviz/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6dcce732cd877fc501a28cde5132e3bd3d44d826 --- /dev/null +++ b/Biomni/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/Biomni/mcp_generated/mcp_bioconductor-scdataviz/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scdataviz/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scdataviz/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scdotplot/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3d4c868a815aa829265425f503d9268db6cc690e --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/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-scdotplot via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scdotplot -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-scdotplot_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-scdotplot_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-scdotplot_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_server.py b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..529c7f8de6c5b17dd6802bc546bcb9e635f3ba8a --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_server.py @@ -0,0 +1,273 @@ +import subprocess +import tempfile +import json +from pathlib import Path +from typing import List, Optional, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_scdotplot' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def sc_dot_plot( + input_path: str, + features: List[str], + group_by: str, + output_path: str = "dotplot.pdf", + cluster_cols: bool = True, + cluster_rows: bool = True, + assay: str = "RNA", + slot: str = "data", + scale: bool = True, + cap: float = 2.5, + annotation_cols: Optional[List[str]] = None, + annotation_rows: Optional[List[str]] = None, +) -> dict: + """ + Generate a clustered single-cell RNA-seq dot plot using the scDotPlot package. + + Args: + input_path: Path to the input file (RDS format containing Seurat or SingleCellExperiment object). + features: List of gene names or features to plot. + group_by: Metadata column name to group cells by (e.g., 'ident' or 'cluster'). + output_path: Path where the resulting plot (PDF, PNG, etc.) will be saved. + cluster_cols: Whether to perform hierarchical clustering on the columns (features). + cluster_rows: Whether to perform hierarchical clustering on the rows (cell groups). + assay: Name of the assay to use (for Seurat objects). + slot: Name of the slot to use (e.g., 'data', 'counts'). + scale: Whether to scale the expression data. + cap: Value at which to cap the scaled expression data. + annotation_cols: Optional list of metadata columns to use for annotating the columns. + annotation_rows: Optional list of metadata columns to use for annotating the rows. + """ + # Input validation + input_file = Path(input_path) + if not input_file.exists(): + return {"error": f"Input file not found: {input_path}"} + + output_file = Path(output_path) + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script + features_r = ", ".join([f"'{f}'" for f in features]) + + # Handle optional annotations + ann_cols_r = "NULL" + if annotation_cols: + ann_cols_r = "c(" + ", ".join([f"'{a}'" for a in annotation_cols]) + ")" + + ann_rows_r = "NULL" + if annotation_rows: + ann_rows_r = "c(" + ", ".join([f"'{a}'" for a in annotation_rows]) + ")" + + r_script = f""" + library(scDotPlot) + library(Seurat) + library(SingleCellExperiment) + library(ggplot2) + + # Load object + obj <- readRDS('{input_path}') + + # Generate plot + p <- scDotPlot( + object = obj, + features = c({features_r}), + group.by = '{group_by}', + cluster.cols = {str(cluster_cols).upper()}, + cluster.rows = {str(cluster_rows).upper()}, + assay = '{assay}', + slot = '{slot}', + scale = {str(scale).upper()}, + cap = {cap}, + annotation_cols = {ann_cols_r}, + annotation_rows = {ann_rows_r} + ) + + # Save plot + ggsave('{output_path}', plot = p) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"scDotPlot on {input_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": f"Rscript {tmp_path}" + } + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def sc_dot_plot_data( + input_path: str, + features: List[str], + group_by: str, + output_csv: str = "dotplot_data.csv", + assay: str = "RNA", + slot: str = "data", + scale: bool = True, + cap: float = 2.5, +) -> dict: + """ + Extract the underlying data frame used for generating a scDotPlot. + + Args: + input_path: Path to the input file (RDS format). + features: List of gene names or features. + group_by: Metadata column name to group cells by. + output_csv: Path to save the extracted data as a CSV file. + assay: Name of the assay to use. + slot: Name of the slot to use. + scale: Whether to scale the expression data. + cap: Value at which to cap the scaled expression data. + """ + input_file = Path(input_path) + if not input_file.exists(): + return {"error": f"Input file not found: {input_path}"} + + features_r = ", ".join([f"'{f}'" for f in features]) + + r_script = f""" + library(scDotPlot) + library(Seurat) + library(SingleCellExperiment) + + obj <- readRDS('{input_path}') + + # Extract data using the internal data preparation logic + plot_data <- scDotPlotData( + object = obj, + features = c({features_r}), + group.by = '{group_by}', + assay = '{assay}', + slot = '{slot}', + scale = {str(scale).upper()}, + cap = {cap} + ) + + write.csv(plot_data, '{output_csv}', row.names = FALSE) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"scDotPlotData on {input_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(output_csv).absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def sc_dot_plot_custom_df( + data_path: str, + features_col: str, + groups_col: str, + avg_exp_col: str, + pct_exp_col: str, + output_path: str = "dotplot_from_df.pdf", + cluster_cols: bool = True, + cluster_rows: bool = True, +) -> dict: + """ + Generate a clustered dot plot from a pre-calculated data frame instead of a Seurat/SCE object. + + Args: + data_path: Path to a CSV file containing the summarized expression data. + features_col: Column name in the CSV containing gene/feature names. + groups_col: Column name in the CSV containing cell group/cluster names. + avg_exp_col: Column name in the CSV containing average expression values. + pct_exp_col: Column name in the CSV containing percent of cells expressing the gene. + output_path: Path where the resulting plot will be saved. + cluster_cols: Whether to perform hierarchical clustering on columns. + cluster_rows: Whether to perform hierarchical clustering on rows. + """ + data_file = Path(data_path) + if not data_file.exists(): + return {"error": f"Data file not found: {data_path}"} + + r_script = f""" + library(scDotPlot) + library(ggplot2) + + # Load data frame + df <- read.csv('{data_path}') + + # Generate plot using the data frame method + # Note: scDotPlot handles data frames by mapping columns + p <- scDotPlot( + object = df, + features = '{features_col}', + group.by = '{groups_col}', + avg.exp = '{avg_exp_col}', + pct.exp = '{pct_exp_col}', + cluster.cols = {str(cluster_cols).upper()}, + cluster.rows = {str(cluster_rows).upper()} + ) + + ggsave('{output_path}', plot = p) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"scDotPlot on data frame {data_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(output_path).absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + Path(tmp_path).unlink(missing_ok=True) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomni/mcp_generated/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..193ae85627d294bd324cb66c7627176ff2da21e2 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_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-scdotplot/app/bioconductor-scdotplot_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scdotplot' + + +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/Biomni/mcp_generated/mcp_bioconductor-scdotplot/app/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomni/mcp_generated/mcp_bioconductor-scdotplot/docker-compose.yml b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..75f17138ca6bc36ee85fef8d3f0095d8611fcb9c --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scdotplot: + build: . + image: mcp-bioconductor-scdotplot:latest + container_name: mcp-bioconductor-scdotplot + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scdotplot + 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/Biomni/mcp_generated/mcp_bioconductor-scdotplot/environment.yaml b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a13eaadf703def4a3951f4ee0662665909ca7c19 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scdotplot + - python=3.10 + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scdotplot/requirements.txt b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scdotplot/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomni/mcp_generated/mcp_bioconductor-scfeatures/Dockerfile b/Biomni/mcp_generated/mcp_bioconductor-scfeatures/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..30151fe7846b8c0045d8f7ed6d3d8c9f985c48ba --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scfeatures/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-scfeatures via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scfeatures -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-scfeatures_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-scfeatures_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-scfeatures_server.py"] + \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_server.py b/Biomni/mcp_generated/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b405addb0f5e2f10530051dedc15ef8f5158fba --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_server.py @@ -0,0 +1,242 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# 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): + # In a real scenario, the MCP framework would handle + # registration, UI generation, and execution. + print(f"Executing tool: {func.__name__}") + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def scfeatures( + input_object: Path, + output_rds: Path, + features: List[str], + species: str = "human", + gene_set_file: Optional[Path] = None, + gene_set_name: str = "custom_gene_set", + n_cores: int = 1, + log_transformed: bool = False, + group_by: Optional[str] = None, + cor_method: str = "spearman", + mito_pattern: str = "^MT-", + ribo_pattern: str = "^RP[SL]", + reduction: Optional[str] = None, +) -> Dict[str, Any]: + """ + Generates multi-view representations of single-cell and spatial data using scFeatures. + + This tool wraps the main `scFeatures()` function from the R/Bioconductor package. + It takes a Seurat or SingleCellExperiment object (in .rds format) and computes + a specified set of features, saving the updated object to a new .rds file. + + Args: + input_object: Path to the input RDS file containing a Seurat or SingleCellExperiment object. + output_rds: Path to save the output RDS file with added features. + features: A list of feature types to compute. + Valid options: 'cell_cell_communication_Spatalk', 'cell_cycle', + 'gene_body_tms', 'gene_gene_correlation', 'gene_set_aucell', + 'gene_set_gsva', 'ligand_receptor_gsea', 'metabolic_pathway_gsea', + 'number_of_genes', 'number_of_umis', 'percent_mito', 'percent_ribo', + 'phate', 'pseudotime', 'spatial_autocorrelation', + 'spatial_cross_correlation', 'spatial_enrichment'. + species: The species of the data. Used for gene set-based features. + Defaults to "human". + gene_set_file: Optional path to a custom gene set file in GMT format. + Required for 'gene_set_aucell' or 'gene_set_gsva' if not using default sets. + gene_set_name: The name for the custom gene set list when using `gene_set_file`. + Defaults to "custom_gene_set". + n_cores: Number of cores to use for parallel processing. Defaults to 1. + log_transformed: Set to True if the input data is already log-transformed. + Defaults to False. + group_by: Metadata column name to group cells by for features like + 'gene_gene_correlation' or 'pseudotime'. + cor_method: Correlation method for 'gene_gene_correlation'. + Defaults to "spearman". + mito_pattern: Regex pattern to identify mitochondrial genes for 'percent_mito'. + Defaults to "^MT-". + ribo_pattern: Regex pattern to identify ribosomal genes for 'percent_ribo'. + Defaults to "^RP[SL]". + reduction: Name of the dimensionality reduction to use for 'pseudotime' calculation. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + + if species not in ["human", "mouse"]: + raise ValueError(f"Invalid species: '{species}'. Must be 'human' or 'mouse'.") + + if cor_method not in ["spearman", "pearson", "kendall"]: + raise ValueError(f"Invalid cor_method: '{cor_method}'. Must be 'spearman', 'pearson', or 'kendall'.") + + valid_features = { + 'cell_cell_communication_Spatalk', 'cell_cycle', 'gene_body_tms', + 'gene_gene_correlation', 'gene_set_aucell', 'gene_set_gsva', + 'ligand_receptor_gsea', 'metabolic_pathway_gsea', 'number_of_genes', + 'number_of_umis', 'percent_mito', 'percent_ribo', 'phate', + 'pseudotime', 'spatial_autocorrelation', 'spatial_cross_correlation', + 'spatial_enrichment' + } + for feature in features: + if feature not in valid_features: + raise ValueError(f"Invalid feature '{feature}'. Please choose from the list of valid features.") + + if gene_set_file and not gene_set_file.is_file(): + raise FileNotFoundError(f"Gene set file not found: {gene_set_file}") + + # 2. R Script Generation + # This script will be executed by Rscript. It loads the data, runs scFeatures, + # and saves the result. + r_script_content = f""" + # Load necessary libraries + suppressPackageStartupMessages(library(optparse)) + suppressPackageStartupMessages(library(scFeatures)) + suppressPackageStartupMessages(library(Seurat)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + suppressPackageStartupMessages(library(BiocParallel)) + suppressPackageStartupMessages(library(GSEABase)) # For reading GMT files + + # Define command-line options + option_list <- list( + make_option(c("-i", "--input_object"), type="character", help="Input RDS file path"), + make_option(c("-o", "--output_rds"), type="character", help="Output RDS file path"), + make_option(c("-f", "--features"), type="character", help="Comma-separated list of features"), + make_option(c("-s", "--species"), type="character", default="human", help="Species"), + make_option(c("--gene_set_file"), type="character", default=NULL, help="Path to GMT gene set file"), + make_option(c("--gene_set_name"), type="character", default="custom_gene_set", help="Name for custom gene set"), + make_option(c("-n", "--n_cores"), type="integer", default=1, help="Number of cores"), + make_option(c("--log_transformed"), action="store_true", default=FALSE, help="Flag for log-transformed data"), + make_option(c("--group_by"), type="character", default=NULL, help="Metadata column for grouping"), + make_option(c("--cor_method"), type="character", default="spearman", help="Correlation method"), + make_option(c("--mito_pattern"), type="character", default="^MT-", help="Mitochondrial gene pattern"), + make_option(c("--ribo_pattern"), type="character", default="^RP[SL]", help="Ribosomal gene pattern"), + make_option(c("--reduction"), type="character", default=NULL, help="Reduction for pseudotime") + ) + + # Parse options + opt_parser <- OptionParser(option_list=option_list) + opt <- parse_args(opt_parser) + + # Read input object + message("Reading input object from: ", opt$input_object) + input_obj <- readRDS(opt$input_object) + + # Parse features string into a character vector + features_to_run <- strsplit(opt$features, ",")[[1]] + message("Features to compute: ", paste(features_to_run, collapse=", ")) + + # Set up parallel processing + bpparam <- MulticoreParam(workers = opt$n_cores) + + # Prepare arguments for scFeatures function + scfeatures_args <- list( + object = input_obj, + features = features_to_run, + species = opt$species, + log_transformed = opt$log_transformed, + cor_method = opt$cor_method, + mito_pattern = opt$mito_pattern, + ribo_pattern = opt$ribo_pattern, + BPPARAM = bpparam + ) + + # Add optional arguments if they are provided + if (!is.null(opt$group_by)) {{ + scfeatures_args$group_by <- opt$group_by + }} + if (!is.null(opt$reduction)) {{ + scfeatures_args$reduction <- opt$reduction + }} + if (!is.null(opt$gene_set_file)) {{ + message("Reading custom gene sets from: ", opt$gene_set_file) + gmt <- getGmt(opt$gene_set_file) + gene_sets <- geneIds(gmt) + gene_set_list <- list(gene_sets) + names(gene_set_list) <- opt$gene_set_name + scfeatures_args$gene_set_list <- gene_set_list + }} + + # Run scFeatures with the constructed arguments + message("Running scFeatures...") + output_obj <- do.call(scFeatures, scfeatures_args) + message("scFeatures finished.") + + # Save the resulting object + message("Saving output object to: ", opt$output_rds) + saveRDS(output_obj, file = opt$output_rds) + + message("Successfully completed.") + """ + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_scfeatures.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + # 3. Subprocess Execution + cmd = [ + "Rscript", + str(r_script_path), + "--input_object", str(input_object), + "--output_rds", str(output_rds), + "--features", ",".join(features), + "--species", species, + "--n_cores", str(n_cores), + "--cor_method", cor_method, + "--mito_pattern", mito_pattern, + "--ribo_pattern", ribo_pattern, + ] + + if log_transformed: + cmd.append("--log_transformed") + if group_by: + cmd.extend(["--group_by", group_by]) + if reduction: + cmd.extend(["--reduction", reduction]) + if gene_set_file: + cmd.extend(["--gene_set_file", str(gene_set_file)]) + cmd.extend(["--gene_set_name", gene_set_name]) + + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=temp_dir, + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + # 4. Error Handling + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"scFeatures execution failed with return code {e.returncode}", + } + + # 5. Structured Result Return + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds)], + } \ No newline at end of file diff --git a/Biomni/mcp_generated/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_shim_server.py b/Biomni/mcp_generated/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..363956631fe7c4f60d0f7b0304cd254221de306d --- /dev/null +++ b/Biomni/mcp_generated/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_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-scfeatures/app/bioconductor-scfeatures_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scfeatures' + + +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")