diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..50b12bc8047f8991312c0813274193fff3435c15 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7ac92aa3ac867a1e40b1b540b63d25deaa0df288 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py @@ -0,0 +1,230 @@ +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" +] + + +@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 diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bcb5f269c3334f2110d0ecb9677b954c2c79ec62 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_multtest' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6bc264787603248074bf059e0399068f89fd919a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f686d7fe95f83931ab22a680f054decfb3dd5756 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0f63490caed08cf51637c5ae1864b93d17c928e8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5295e932dc7a992900fd6461eb5abd11d276f55e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_server.py @@ -0,0 +1,177 @@ +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}) + + +@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)}, + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f4649ffc0c4e73ece724c7a4f3c3f99642cfd7d4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_nebulosa' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..791e3c6938d43d81317b2e40924857ae6bb3b39c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b24fe111257cb3c281a4ef0fe14bb4737b81aeba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0236be3dad1e86c4a1134b86ae90e82892bbbc78 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..aad7afa4d56156051b0f2ac09fa329fce396e79b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py @@ -0,0 +1,413 @@ +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 + +@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, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dc61146114d0b77eec53aa06b8730dfc18961fcd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_noiseq' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f800395ced0511dc9c22d1332037d8d07bbe14f4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..96a600a3aa5d094c29ef4b5908e396f15643085f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4063797cda67f7442fa6031a699b1ed32b5b26f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..98e9cd9bcb0b3cc04ad6fe8b9e8ab574b9d54407 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py @@ -0,0 +1,187 @@ +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() + +@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) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..266df6adc735d13db8bcc4915c3392a18657213e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_org_hs_eg_db' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4eb289ab819090371a3aacbde6c3d48a7e26bd78 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ddb7785c9c4ce5c193d1ada773c1d53f4a86a89 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5d64bfc9fbcdf57b66b8b29d69a8daf28afcedea --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1ee223cd7d38c3f06a91d427e094665296ba059b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8a4c862186e0b04b12cbc584ea7e142c5ba4e75b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_phemd' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f82513ed1769a4b84a85581aaaacf609b91acc19 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..700f5ac3e3d4b4a8d8d5a4f369e9b148ababb84b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a575fb7871cf3df2022dfe794a043ce28ce6f649 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py new file mode 100644 index 0000000000000000000000000000000000000000..56e0b0e457cc95d644072ef6e2c55b8b53ecab5c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py @@ -0,0 +1,332 @@ +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) + +@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)} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..207ac82a8dd22712c0b714d90a5b3a08bfbed251 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_preprocesscore' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e344031a5676f11d324f8a07e7dbcf4341d74455 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9a3892f6e80633f97fad970e2fc73523e6b13dc8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..adbf3ebc54fccef2f2bf508538755a4d5a89b24e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..90b31cb06cbc02c8ee3218b223749aa9db7f4913 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dae826bd202cfc587302172994341cb964750257 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_proteomicsannotationhubdata' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8ac5970dd6840a7998007627da87e4f60be9c51 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac7f8e4fe821d39719f5a0a64a7123c5d0691d97 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3f2bf309ffe7ffbc844c764b6d238665b9b9f7d6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..66bf7a1b0ec4d3de2a87d88e5dd02a170b925a2a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..11e0736926fce52850e0a15bd7828269749d3d45 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_protgenerics' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..47e13413587e0d6524543a5a4c25700d07c47e08 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/requirements.txt @@ -0,0 +1 @@ +mcp==1.27.0 diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8e1d8d8096c32ba24e5823365e99b8573189e31a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d17c7b69d3b821e749569b909c88ec485482063c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..062b47df16d08f6173721af25952519f73dfcafa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/requirements.txt @@ -0,0 +1,3 @@ +mcp==1.27.0 +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0490536356ac972684113e03f94ef6e5a5ed5edb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..11851eb51bc71813affd06c1385fe37f7a179070 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6983bd35269d523f5a5199a49f1afe547f96af05 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/app/bioconductor-rforproteomics_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_rforproteomics' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8777e2825f2c61ac247216ca6df83d0b77132802 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..add6d6abe9185029b539778ee50f8561cb2dbfcc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rforproteomics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..23b2b83e0e1daf22cc0c286cbebf06a5f2214728 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cc30a312df2d214c7c9088bf9411aa990f01c819 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py @@ -0,0 +1,184 @@ +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}") + +@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 \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc45627e94f1a5956122356fc518493a9dce1d2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_rhdf5' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..371502a90b6b0e642754aebfdcfbed6956a61c7d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cee49d16e0b5556057e50c59af4bc0cf5ee744b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhdf5/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..06606fbc87c7cc914c960f63ba38650caa95bbc6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0b5bb28c98191937f3201d841970f7d861d91a51 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py @@ -0,0 +1,120 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +@mcp.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": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5133663518de585f8b51b2d412ccd94e182459d0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_rhtslib' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e3490324c687de6f1d638054610292218df8d093 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d9fd1f10209694d0af1705cd86798274dadc35c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rhtslib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0d3c706e4910bc3c14bf2f9ad377de8d3d4f6d71 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7cc02f52af25da42af40460bc49622b2108bc931 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b365f469e3b786ca79f7ac5efaba748e27c1faca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_rsamtools' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d651c7cf7814b6fdfba82ac2f2145cb67d0099d2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5c153912d63628e3c8ea76360f2d3f0afac07118 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsamtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4dec6ab2174115a3f1326b6fd37bc802e9c6b00 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ba1b38286725ea5b9101ff371ee79579eb2c7d72 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py @@ -0,0 +1,314 @@ +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}") + +@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)} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7bda888c6bb1f569b842195b1c9b9dbc56172ae8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_rsubread' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e2725ed890f216390d4ca45f72fe80e813511c82 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fdd1061efad1bac463df38b14d847bf8a1798168 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rsubread/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc4c0991514cc01e8dac3cd11c123168bf61c81a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d68fa4f35a1715e991d5843bb988c2cb66583da9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f221860110800b53e421855fc9c7fa929a826c9c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/app/bioconductor-rtracklayer_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_rtracklayer' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..157e572f2f12f56aa788b6b9d1f6cae0a70d2ee0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a856295b3e4e95df8ebc94bdd0203c76011ff269 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-rtracklayer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-s4vectors/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-s4vectors/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-s4vectors/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..94ff6db8337a62074ee000d9331841b428126b2e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/app/bioconductor-scbfa_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/app/bioconductor-scbfa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b179a68910946e7b326ce16ef4b74822ce00516 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/app/bioconductor-scbfa_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/app/bioconductor-scbfa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8d1ca759ea8ce8f87ceb2402cd98b0aef99d3bc7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/app/bioconductor-scbfa_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_scbfa' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8ddfddb024ad9c91d3fc9d4cd013f1cb9d9e00b1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0e5aaa29f0c7f136ee493fe61a322bcf41a2787f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scbfa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ef9f5c761e496cb49c647c4b468c551764238a6f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/app/bioconductor-sccb2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/app/bioconductor-sccb2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e78a3694e1e3d73a316b75c7c69dd53bc200b264 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/app/bioconductor-sccb2_server.py @@ -0,0 +1,135 @@ +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() + + +@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": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/app/bioconductor-sccb2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/app/bioconductor-sccb2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f51eb626202f43eaa390ea8639dd0f2dbb0098f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/app/bioconductor-sccb2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_sccb2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..64f80f2c0b9fee1954c7a433abd544684a676332 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f49b35fc0692ce48114a48bf1bbad3003d57ff13 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-sccb2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c926501a4fd661158e18096512c4e1f1481c6b4a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6262e5ea82010f6d2290e68c395b98fca31465c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a04b11fde322fb9d8af18ad9cfe1626b50e4749a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/app/bioconductor-scdataviz_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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') +SERVER_NAME = 'biosci_bioconductor_scdataviz' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c505a0ca6bc8f3d61067bbe38ad54952de78ce99 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6dcce732cd877fc501a28cde5132e3bd3d44d826 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scdataviz/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5f8e016875df53696a5db64cc303a6d7da461a8e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scmageck via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scmageck -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-scmageck_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scmageck_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scmageck_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/app/bioconductor-scmageck_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/app/bioconductor-scmageck_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc802ab8284f45637e3da88be938501f5436c59 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/app/bioconductor-scmageck_server.py @@ -0,0 +1,269 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any +import tempfile + +@mcp.tool() +def scmageck_eff_estimate( + count_matrix_path: str, + barcode_file_path: str, + output_rds_path: str, + neg_control: str = "non-target", + perturb_gene: Optional[str] = None, + cell_column: str = "cell", + barcode_column: str = "barcode", + gene_column: str = "gene" +): + """ + Estimate the efficiency of guides using the scmageck_eff_estimate function. + + Args: + count_matrix_path: Path to the gene expression count matrix (CSV/TSV or RDS). + barcode_file_path: Path to the barcode-to-cell mapping file (CSV/TSV). + output_rds_path: Path where the resulting RDS object will be saved. + neg_control: Name of the negative control gene/guide. + perturb_gene: Specific gene to estimate efficiency for. If None, estimates for all. + cell_column: Column name for cell identifiers in barcode file. + barcode_column: Column name for barcode identifiers in barcode file. + gene_column: Column name for gene identifiers in barcode file. + """ + # Validate inputs + count_path = Path(count_matrix_path) + bc_path = Path(barcode_file_path) + out_path = Path(output_rds_path) + + if not count_path.exists(): + return {"error": f"Count matrix not found: {count_matrix_path}"} + if not bc_path.exists(): + return {"error": f"Barcode file not found: {barcode_file_path}"} + + # Ensure output directory exists + out_path.parent.mkdir(parents=True, exist_ok=True) + + # Construct R script + perturb_gene_cmd = f'"{perturb_gene}"' if perturb_gene else "NULL" + + r_script = f""" + library(scmageck) + + # Load data + if (grepl(".rds$", "{count_path}", ignore.case = TRUE)) {{ + counts <- readRDS("{count_path}") + }} else {{ + counts <- read.table("{count_path}", header = TRUE, sep = ",", row.names = 1) + }} + + barcodes <- read.table("{bc_path}", header = TRUE, sep = ",") + + # Run efficiency estimation + eff_result <- scmageck_eff_estimate( + count_mat = counts, + barcode_df = barcodes, + negctrl = "{neg_control}", + perturb_gene = {perturb_gene_cmd}, + cell_col = "{cell_column}", + bc_col = "{barcode_column}", + gene_col = "{gene_column}" + ) + + saveRDS(eff_result, file = "{out_path}") + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"scmageck_eff_estimate on {count_matrix_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def scmageck_lr( + expression_matrix_path: str, + perturbation_matrix_path: str, + output_csv_path: str, + lambda_val: float = 0.01, + n_cores: int = 1 +): + """ + Perform Linear Regression analysis to identify gene targets using scmageck_lr. + + Args: + expression_matrix_path: Path to the expression matrix (RDS or CSV). + perturbation_matrix_path: Path to the perturbation matrix (RDS or CSV). + output_csv_path: Path to save the regression results (CSV). + lambda_val: Penalty parameter for regression. + n_cores: Number of CPU cores to use. + """ + expr_path = Path(expression_matrix_path) + pert_path = Path(perturbation_matrix_path) + out_path = Path(output_csv_path) + + if not expr_path.exists() or not pert_path.exists(): + return {"error": "Input expression or perturbation matrix not found."} + + r_script = f""" + library(scmageck) + + # Load matrices + load_mat <- function(p) {{ + if (grepl(".rds$", p, ignore.case = TRUE)) return(readRDS(p)) + return(as.matrix(read.table(p, header = TRUE, row.names = 1, sep = ","))) + }} + + expr_mat <- load_mat("{expr_path}") + pert_mat <- load_mat("{pert_path}") + + # Run LR + lr_result <- scmageck_lr( + m_matrix = expr_mat, + g_matrix = pert_mat, + lambda = {lambda_val} + ) + + # Handle result (scmageck_lr returns a list or matrix depending on version) + write.csv(lr_result, file = "{out_path}") + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "scmageck_lr", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def scmageck_optim_perturb( + rds_input_path: str, + output_rds_path: str, + max_iter: int = 100, + threshold: float = 1e-4 +): + """ + Optimize the perturbation matrix using the scmageck_optim_perturb function. + + Args: + rds_input_path: Path to an RDS file containing the scmageck object/list. + output_rds_path: Path to save the optimized RDS object. + max_iter: Maximum number of iterations for optimization. + threshold: Convergence threshold. + """ + in_path = Path(rds_input_path) + out_path = Path(output_rds_path) + + if not in_path.exists(): + return {"error": f"Input RDS file not found: {rds_input_path}"} + + r_script = f""" + library(scmageck) + + obj <- readRDS("{in_path}") + + # Run optimization + # Note: scmageck_optim_perturb parameters may vary by version; + # usually takes the result of eff_estimate + optim_result <- scmageck_optim_perturb( + eff_obj = obj, + max_iter = {max_iter}, + tol = {threshold} + ) + + saveRDS(optim_result, file = "{out_path}") + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "scmageck_optim_perturb", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def scmageck_get_score( + rds_input_path: str, + output_csv_path: str +): + """ + Extract scores/p-values from a processed scmageck RDS object. + + Args: + rds_input_path: Path to the RDS file generated by scmageck_lr or eff_estimate. + output_csv_path: Path to save the extracted scores as CSV. + """ + in_path = Path(rds_input_path) + out_path = Path(output_csv_path) + + if not in_path.exists(): + return {"error": "Input RDS file not found."} + + r_script = f""" + library(scmageck) + obj <- readRDS("{in_path}") + + # Extracting score logic depends on the object structure + if (is.list(obj) && "score" %in% names(obj)) {{ + write.csv(obj$score, file = "{out_path}") + }} else {{ + # Fallback for matrix results + write.csv(as.data.frame(obj), file = "{out_path}") + }} + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "scmageck_get_score", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/app/bioconductor-scmageck_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/app/bioconductor-scmageck_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9b1834557f6cba6b9bd2e98af60ca143dffaa12d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/app/bioconductor-scmageck_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/app/bioconductor-scmageck_server.py') +SERVER_NAME = 'biosci_bioconductor_scmageck' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8b52be87679997a875f56ca4fd7e866ffb2037e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scmageck: + build: . + image: mcp-bioconductor-scmageck:latest + container_name: mcp-bioconductor-scmageck + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scmageck + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce0115c2ac316e90558b3f5a4f73c8a8d45677b2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scmageck + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scmageck/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..58a8ac114185fc2d3241b13de38466865743288e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-screpertoire via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-screpertoire -y && conda clean -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-screpertoire_server.py /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-screpertoire_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-screpertoire_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c206962a9def5f0b82562d4b9fd95aa78f29a002 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_server.py @@ -0,0 +1,124 @@ +import subprocess +from pathlib import Path +from typing import List, Optional + +# MCP-ready code for the Rscript command-line tool. +# This tool is often used to execute scripts from Bioconductor packages +# like 'bioconductor-screpertoire'. + +# @mcp.tool() is a placeholder for the actual decorator. +# In a real MCP environment, you would import it: +# from mcp import tool as mcp_tool +class mcp: + @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, + 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 or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper for Rscript, allowing execution of R code from + the command line. You must provide either a script file or a list of R + expressions to execute. + + Args: + 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 'file'. + script_args: A list of arguments to be passed to the R script specified by 'file'. + verbose: If True, corresponds to the --verbose flag, printing information on progress. + default_packages: A comma-separated list of package names to be loaded by default (e.g., "utils,graphics"). + save: If True, corresponds to the --save flag to save the workspace at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, corresponds to the --no-environ flag. Do not read site and user environment files. Ignored if 'vanilla' is True. + no_site_file: If True, corresponds to the --no-site-file flag. Do not read the site-wide Rprofile. Ignored if 'vanilla' is True. + no_init_file: If True, corresponds to the --no-init-file flag. Do not read the user R profile. Ignored if 'vanilla' is True. + restore: If True, corresponds to the --restore flag to 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 for a clean session. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + Note: Rscript itself does not define output files; any generated files are the responsibility of the R code being executed. + """ + # 1. Input Validation + if file and expressions: + raise ValueError("Cannot specify both 'file' and 'expressions'. They are mutually exclusive.") + if not file and not expressions: + raise ValueError("Must specify either 'file' or 'expressions' to execute.") + + if file: + if not file.is_file(): + raise FileNotFoundError(f"The specified R script file does not exist: {file}") + + if script_args and not file: + raise ValueError("'script_args' can only be provided when a 'file' is specified.") + + # 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]) + elif file: + cmd.append(str(file)) + if script_args: + cmd.extend(script_args) + + # 3. 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 for failed executions + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..97926f7fe461b52717bc679a00b86c8f82578677 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-screpertoire/app/bioconductor-screpertoire_server.py') +SERVER_NAME = 'biosci_bioconductor_screpertoire' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b0a54f57c7ea6cef53e891f8efe2038866bf1b3a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-screpertoire: + build: . + image: mcp-bioconductor-screpertoire:latest + container_name: mcp-bioconductor-screpertoire + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-screpertoire + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b21e34b0e36c58e80823e092ef267594f1c79970 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-screpertoire + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6935960696a97733edffdcdabac83c9f0cfb8ff3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-scrnaseq via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scrnaseq -y && conda clean -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-scrnaseq_server.py /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-scrnaseq_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-scrnaseq_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/app/bioconductor-scrnaseq_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/app/bioconductor-scrnaseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d408b5ebdd5929347dec7d8b059d5640bcb2ba14 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/app/bioconductor-scrnaseq_server.py @@ -0,0 +1,116 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# @mcp.tool is a placeholder for the actual decorator in the MCP environment. +# No need to import it in the final code. + +@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, +) -> 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 from + the command line. It is commonly used to run scripts that utilize libraries + from repositories like Bioconductor (e.g., for scRNA-seq analysis). You must + provide either a script file to run or a list of expressions to evaluate. + + 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, prints information on progress. Corresponds to --verbose. + default_packages: A comma-separated list of package names to be loaded by default, or 'NULL'. 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. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + The 'output_files' list will be empty as Rscript itself does not define output files; + any files created are determined by the R code being executed. + """ + # 1. Input Validation + if script_file is None and (expressions is None or not expressions): + raise ValueError("Either 'script_file' or a non-empty 'expressions' list must be provided.") + if script_file is not None and expressions is not None: + 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"Input script file not found or is not a file: {script_file}") + + # 2. Command Construction + cmd = ["Rscript"] + + 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: + for expr in expressions: + cmd.extend(["-e", expr]) + elif script_file: + cmd.append(str(script_file)) + + if script_args: + cmd.extend(script_args) + + command_executed = " ".join(cmd) + + # 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 is caught if 'Rscript' is not in the system's PATH + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # This error is caught if Rscript returns a non-zero exit code + return { + "error": "Rscript execution failed with a non-zero exit code.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/app/bioconductor-scrnaseq_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/app/bioconductor-scrnaseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ee9e0583947519b824a95a220c76b8aa9bfd7082 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/app/bioconductor-scrnaseq_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-scrnaseq/app/bioconductor-scrnaseq_server.py') +SERVER_NAME = 'biosci_bioconductor_scrnaseq' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8549e865843268bd4f159a5c4a3a0ebc0224e44b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scrnaseq: + build: . + image: mcp-bioconductor-scrnaseq:latest + container_name: mcp-bioconductor-scrnaseq + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scrnaseq + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb6a1f695b37cabd5682568ab5e2361a96feab94 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scrnaseq + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-scrnaseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..49ed5db0945a4bc42fc7769b3635b498da4a576b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-shortread via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-shortread -y && conda clean -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-shortread_server.py /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-shortread_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-shortread_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2875ce7610b17c1f939dc142900b72401fcafeaf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py @@ -0,0 +1,270 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def shortread_qa( + input_dir: str, + pattern: str = ".*\\.fastq$", + output_dir: str = "qa_report", + sample_size: int = 1000000 +) -> Dict[str, Any]: + """ + Performs Quality Assessment (QA) on FASTQ files in a directory and generates an HTML report. + + Args: + input_dir: Directory containing FASTQ files. + pattern: Regular expression to match FASTQ filenames. + output_dir: Directory where the HTML report will be saved. + sample_size: Number of reads to sample for QA (default 1M). + """ + input_path = Path(input_dir) + if not input_path.is_dir(): + return {"error": f"Input directory {input_dir} does not exist."} + + # R script to run QA + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + qa_results <- qa(dirPath = "{input_dir}", pattern = "{pattern}", sample = TRUE, n = {sample_size}) + report(qa_results, dest = "{output_dir}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::qa() on {input_dir}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(Path(output_dir).absolute()) + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def shortread_trim_tails( + input_file: str, + output_file: str, + k: int = 2, + a: str = "I", + successive: bool = True +) -> Dict[str, Any]: + """ + Trims low-quality ends from reads using the trimTails algorithm. + + Args: + input_file: Path to input FASTQ file. + output_file: Path to save the trimmed FASTQ file. + k: Number of successive nucleotides with quality <= 'a' to trigger trimming. + a: The quality threshold character (e.g., 'I' for Phred 40, '#' for Phred 2). + successive: Whether the low quality scores must be successive. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + successive_r = "TRUE" if successive else "FALSE" + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + fq <- readFastq("{input_file}") + trimmed <- trimTails(fq, k = {k}, a = "{a}", successive = {successive_r}) + writeFastq(trimmed, "{output_file}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::trimTails({input_file})", + "stdout": result.stdout, + "output_file": str(Path(output_file).absolute()) + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def shortread_filter_n( + input_file: str, + output_file: str, + max_n: int = 0 +) -> Dict[str, Any]: + """ + Filters out reads containing more than the specified number of 'N' (ambiguous) nucleotides. + + Args: + input_file: Path to input FASTQ file. + output_file: Path to save the filtered FASTQ file. + max_n: Maximum number of Ns allowed per read (default 0). + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + fq <- readFastq("{input_file}") + filt <- nFilter(threshold = {max_n}) + filtered_fq <- fq[filt(fq)] + writeFastq(filtered_fq, "{output_file}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::nFilter(threshold={max_n})", + "stdout": result.stdout, + "output_file": str(Path(output_file).absolute()) + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def shortread_alphabet_frequency( + input_file: str, + base_only: bool = True +) -> Dict[str, Any]: + """ + Calculates the frequency of nucleotides (A, C, G, T, N) across all reads in a FASTQ file. + + Args: + input_file: Path to input FASTQ file. + base_only: If True, only report standard DNA bases. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + base_only_r = "TRUE" if base_only else "FALSE" + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + fq <- readFastq("{input_file}") + freqs <- alphabetFrequency(sread(fq), baseOnly = {base_only_r}) + total_freqs <- colSums(freqs) + print(total_freqs) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::alphabetFrequency({input_file})", + "stdout": result.stdout, + "nucleotide_counts": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def shortread_fastq_count( + input_file: str +) -> Dict[str, Any]: + """ + Quickly counts the number of reads in a FASTQ file using ShortRead's optimized reader. + + Args: + input_file: Path to input FASTQ file. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + # countFastq returns a data.frame with elements, records, and bytes + cnt <- countFastq("{input_file}") + cat(cnt$records) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::countFastq({input_file})", + "read_count": int(result.stdout.strip()) if result.stdout.strip().isdigit() else result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def shortread_trim_lr_patterns( + input_file: str, + output_file: str, + left_pattern: str = "", + right_pattern: str = "", + max_l_mismatch: int = 0, + max_r_mismatch: int = 0, + with_l_indels: bool = False, + with_r_indels: bool = False +) -> Dict[str, Any]: + """ + Trims fixed patterns (like adapters or primers) from the left and/or right ends of reads. + + Args: + input_file: Path to input FASTQ file. + output_file: Path to save the trimmed FASTQ file. + left_pattern: DNA sequence pattern to trim from the 5' end. + right_pattern: DNA sequence pattern to trim from the 3' end. + max_l_mismatch: Maximum allowed mismatches for the left pattern. + max_r_mismatch: Maximum allowed mismatches for the right pattern. + with_l_indels: Allow indels in left pattern matching. + with_r_indels: Allow indels in right pattern matching. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + l_indels = "TRUE" if with_l_indels else "FALSE" + r_indels = "TRUE" if with_r_indels else "FALSE" + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + fq <- readFastq("{input_file}") + trimmed <- trimLRPatterns( + Lpattern = "{left_pattern}", + Rpattern = "{right_pattern}", + subject = fq, + max.Lmismatch = {max_l_mismatch}, + max.Rmismatch = {max_r_mismatch}, + with.Lindels = {l_indels}, + with.Rindels = {r_indels} + ) + writeFastq(trimmed, "{output_file}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "ShortRead::trimLRPatterns", + "stdout": result.stdout, + "output_file": str(Path(output_file).absolute()) + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6d6a3f693d1da524004424988cb1cc2d3f995ff7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-shortread/app/bioconductor-shortread_server.py') +SERVER_NAME = 'biosci_bioconductor_shortread' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e5fbe972d4c91c6e95055b2deae82e8adf07186e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-shortread: + build: . + image: mcp-bioconductor-shortread:latest + container_name: mcp-bioconductor-shortread + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-shortread + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42305183482f14a6b1c00be1d192ded37a6392c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-shortread + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..87c58c18dc99720b13df8531fe3ec735a53a472d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-singlecellmultimodal via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-singlecellmultimodal -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-singlecellmultimodal_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-singlecellmultimodal_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-singlecellmultimodal_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8d9f88e48b26b28ffaf85bf24967f5017bd10ae4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_server.py @@ -0,0 +1,143 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# MCP decorator is not defined here, but the function is written +# to be compatible with it, as per the instructions. +# from mcp import tool as mcp_tool +# For demonstration, we'll use a placeholder decorator. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper around Rscript, allowing for the execution of R code + either from a file or directly from command-line expressions. It supports various + options to control the R session's environment and behavior. + + Args: + script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute. Mutually exclusive with 'script_file'. + script_args: A list of arguments to be passed to the R script specified by 'script_file'. + verbose: If True, prints information on progress. + default_packages: A comma-separated list of package names to be loaded by default. + save: If True, the workspace will be saved at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, site and user environment files will not be read. Ignored if 'vanilla' is True. + no_site_file: If True, the site-wide Rprofile will not be read. Ignored if 'vanilla' is True. + no_init_file: If True, the user's R profile will not be read. Ignored if 'vanilla' is True. + restore: If True, previously saved objects will be restored at startup. Ignored if 'vanilla' is True. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + This provides a "clean" R session. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of potential output files. + """ + # 1. Input Validation + if not script_file and not expressions: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + if script_file and expressions: + raise ValueError("'script_file' and 'expressions' are mutually exclusive.") + if script_args and not script_file: + raise ValueError("'script_args' can only be used when a 'script_file' is specified.") + + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + command = ["Rscript"] + + # The --vanilla flag is a combination of other flags. + if vanilla: + command.append("--vanilla") + else: + if save: + command.append("--save") + if no_environ: + command.append("--no-environ") + if no_site_file: + command.append("--no-site-file") + if no_init_file: + command.append("--no-init-file") + if restore: + command.append("--restore") + + if verbose: + command.append("--verbose") + + if default_packages: + command.append(f"--default-packages={default_packages}") + + # Add the script file or expressions to the command + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + elif script_file: + command.append(str(script_file)) + if script_args: + command.extend(script_args) + + command_str = " ".join(command) + logger.info(f"Executing command: {command_str}") + + # 3. Subprocess Execution + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + logger.info("Rscript executed successfully.") + + except FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in your PATH.") + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript command not found. Please ensure R is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"Rscript execution failed with return code {e.returncode}.") + logger.error(f"Stderr: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 4. Structured Result Return + # Rscript itself does not define output files; the script being run does. + # The list of output_files is therefore empty unless explicitly handled. + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7ea8fd3004575447ded422234ed514577e5890 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/app/bioconductor-singlecellmultimodal_server.py') +SERVER_NAME = 'biosci_bioconductor_singlecellmultimodal' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a6f42b0a459288cb5086ca83ad44e9ad694c6bdb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-singlecellmultimodal: + build: . + image: mcp-bioconductor-singlecellmultimodal:latest + container_name: mcp-bioconductor-singlecellmultimodal + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-singlecellmultimodal + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..30cfd95ed178d3a724fdc76a21229d88702c0edc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-singlecellmultimodal + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-singlecellmultimodal/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9dbd68e1fb55260579019aed1a41043a433e47dd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-spaniel via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spaniel -y && conda clean -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-spaniel_server.py /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-spaniel_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-spaniel_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/app/bioconductor-spaniel_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/app/bioconductor-spaniel_server.py new file mode 100644 index 0000000000000000000000000000000000000000..660588ac66e4448135d06a03765c02ef0ad96d81 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/app/bioconductor-spaniel_server.py @@ -0,0 +1,144 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# Set up logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Mock mcp.tool decorator for standalone execution +def mcp_tool_mock(): + def decorator(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + return decorator + +mcp = type('mcp', (), {'tool': mcp_tool_mock}) + +@mcp.tool() +def rscript( + script_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, + vanilla: bool = False, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False +): + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper for Rscript, the non-interactive R interpreter. + It can be used to run bioinformatics scripts, such as those utilizing + Bioconductor packages. You must provide either a script file to execute or + a list of R expressions. + + Args: + script_file: Path to the R script file to be executed. + 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. + version: If True, print the R version and exit. + verbose: If True, enable verbose output, printing progress information. + 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. Overrides individual flags. + save: If True, save the workspace at the end of the session. Ignored if vanilla is True. + no_environ: If True, do not read 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. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Note: Rscript itself does not define output files; any files created are determined by the + script being executed. This tool does not track those files. + """ + # --- Input Validation --- + if version: + if script_file or expressions: + logger.warning("--version is set; other execution arguments like script_file and expressions will be ignored.") + elif not script_file and not expressions: + raise ValueError("You must provide either 'script_file' or 'expressions' to execute.") + elif script_file and expressions: + raise ValueError("You cannot provide both 'script_file' and 'expressions'. Please choose one.") + + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # --- Command Construction --- + cmd = ["Rscript"] + + if version: + cmd.append("--version") + else: + # Add R environment options + 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") + + # Add other options + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--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 arguments for the script itself + if script_args: + cmd.extend(script_args) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + logger.info("Rscript executed successfully.") + + except FileNotFoundError: + logger.error("Rscript not found. Is R installed and in your system's PATH?") + raise + except subprocess.CalledProcessError as e: + logger.error(f"Rscript execution failed with return code {e.returncode}.") + logger.error(f"STDOUT: {e.stdout}") + logger.error(f"STDERR: {e.stderr}") + # Re-raise to signal failure to the MCP controller + raise e + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # Rscript itself doesn't manage output files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/app/bioconductor-spaniel_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/app/bioconductor-spaniel_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a830ff6f694f46f4b7e32054c5cb88c4b3ec1a4f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/app/bioconductor-spaniel_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-spaniel/app/bioconductor-spaniel_server.py') +SERVER_NAME = 'biosci_bioconductor_spaniel' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e8bdb553b274706a2c79f0789f4397e161629dc9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spaniel: + build: . + image: mcp-bioconductor-spaniel:latest + container_name: mcp-bioconductor-spaniel + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spaniel + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e0ae5308d6c56dea2d8bb0f7777b29c3031a0218 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spaniel + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spaniel/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d010d9f12ec2cad4b0c4b144e3c43bcfc1cdcf43 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-spatialcpie via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spatialcpie -y && conda clean -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-spatialcpie_server.py /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-spatialcpie_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-spatialcpie_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/app/bioconductor-spatialcpie_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/app/bioconductor-spatialcpie_server.py new file mode 100644 index 0000000000000000000000000000000000000000..449d10759f0416a7fd500c474ffafaccdd7a7ab0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/app/bioconductor-spatialcpie_server.py @@ -0,0 +1,150 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Assume @mcp.tool is defined elsewhere or imported. + +@mcp.tool() +def run_rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + help_flag: bool = False, + version_flag: bool = False, + 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 or R expressions using the Rscript command-line tool. + + This tool provides an interface to the Rscript command, allowing users to run + R code from the command line. It supports running either a specified R script + file or direct R expressions. Various options are available to control the + R session environment, such as package loading, workspace saving/restoring, + and environment file handling. + + Args: + script_file: Path to an R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions (strings) to be executed. Mutually exclusive with 'script_file'. + script_args: A list of arguments (strings) to be passed to the R script itself. + help_flag: If True, print usage information and exit. + version_flag: If True, print Rscript version information and exit. + verbose: If True, print information on progress during execution. + default_packages: A comma-separated list of package names to load by default, or 'NULL'. + save_workspace: 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_workspace: 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. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any + output files (though Rscript itself doesn't typically produce named + output files directly from the command line). + """ + # Input validation + if script_file and expressions: + raise ValueError("Cannot specify both 'script_file' and 'expressions'. Please choose one.") + if not script_file and not expressions and not help_flag and not version_flag: + raise ValueError( + "Either 'script_file' or 'expressions' must be provided, " + "unless '--help' or '--version' is requested." + ) + + if script_file: + if not script_file.exists(): + raise FileNotFoundError(f"R script file not found: {script_file}") + if not script_file.is_file(): + raise ValueError(f"Provided path is not a file: {script_file}") + + command = ["Rscript"] + + # Add Rscript options + if help_flag: + command.append("--help") + if version_flag: + command.append("--version") + if verbose: + command.append("--verbose") + if default_packages is not None: + command.append(f"--default-packages={default_packages}") + 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 expressions or script file + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + elif script_file: + command.append(str(script_file)) + + # Add arguments to the R script itself + if script_args: + command.extend(script_args) + + command_executed = " ".join(command) + stdout = "" + stderr = "" + output_files: List[Path] = [] + + 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": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}: {e}", + "returncode": e.returncode, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Rscript command not found. Please ensure R is installed and in your system's PATH.", + "error": "Rscript executable not found.", + "returncode": 127, + "output_files": output_files, + } + except Exception as e: + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "error": f"An unexpected error occurred: {e}", + "returncode": 1, # Generic error code + "output_files": output_files, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/app/bioconductor-spatialcpie_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/app/bioconductor-spatialcpie_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a49013b626f0fc05621c296bd9f2db649428010b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/app/bioconductor-spatialcpie_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-spatialcpie/app/bioconductor-spatialcpie_server.py') +SERVER_NAME = 'biosci_bioconductor_spatialcpie' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..af22e63eb3cf1dfabb2a5af22b6e7f0461e24b2e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spatialcpie: + build: . + image: mcp-bioconductor-spatialcpie:latest + container_name: mcp-bioconductor-spatialcpie + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spatialcpie + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7def5d0efb796363bb7babf86d4339b4525e0ee9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spatialcpie + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialcpie/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..18e1cbca52b925fba91c315bfa8fe614cf4774cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-spatialdecon via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spatialdecon -y && conda clean -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-spatialdecon_server.py /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-spatialdecon_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-spatialdecon_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/app/bioconductor-spatialdecon_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/app/bioconductor-spatialdecon_server.py new file mode 100644 index 0000000000000000000000000000000000000000..78ebc6aca415cec9f4441220d3b23d34cd7a3b5d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/app/bioconductor-spatialdecon_server.py @@ -0,0 +1,135 @@ +import logging +import subprocess +from pathlib import Path +from typing import List, Optional + +# Assume mcp is imported and the @mcp.tool decorator is available +# from mcp import mcp + +# Configure logging +logger = logging.getLogger(__name__) + +@mcp.tool() +def spatialdecon_rscript( + script_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, +): + """ + Executes an R script using the Rscript command-line interface. + + This tool is a general-purpose wrapper for the `Rscript` executable, which is + commonly used to run scripts utilizing Bioconductor packages like SpatialDecon. + You can execute R code from a script file or directly from command-line expressions. + It exposes common Rscript options for controlling the R session environment. + + 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. + version: If True, print the Rscript version and exit. + verbose: If True, enable verbose output, printing 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. Ignored if 'vanilla' is True. + no_environ: If True, do not read the site and user environment files. Implied by 'vanilla'. + no_site_file: If True, do not read the site-wide Rprofile. Implied by 'vanilla'. + no_init_file: If True, do not read the user R profile. Implied by 'vanilla'. + restore: If True, restore previously saved objects at startup. Ignored if 'vanilla' is True. + vanilla: If True, combine --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + This provides a clean R session. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + Note: `output_files` will be empty as Rscript does not have a dedicated output file parameter. + Any files generated by the R script must be tracked separately. + """ + # 1. Input Validation + if not script_file and not expressions and not version: + raise ValueError("Either 'script_file', 'expressions', or 'version' 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 vanilla and (save or restore): + raise ValueError( + "Cannot set 'save=True' or 'restore=True' when 'vanilla=True' is used, " + "as --vanilla implies --no-save and --no-restore." + ) + + # 2. Command Construction + cmd = ["Rscript"] + + if version: + cmd.append("--version") + else: + # Add session control options + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--default-packages={default_packages}") + + 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") + + # Add script content (either expressions or a file) + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + elif script_file: + cmd.append(str(script_file)) + + # Add arguments for the R script + if script_args: + cmd.extend(script_args) + + command_str = " ".join(cmd) + logger.info(f"Executing command: {command_str}") + + # 3. Subprocess Execution + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # 4. Structured Result Return (Success) + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # 4. Structured Result Return (Error) + logger.error(f"Rscript execution failed with exit code {e.returncode}") + logger.error(f"Stderr: {e.stderr}") + logger.error(f"Stdout: {e.stdout}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/app/bioconductor-spatialdecon_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/app/bioconductor-spatialdecon_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf3ee1d3b838d89086809f77431434e38a4f2da --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/app/bioconductor-spatialdecon_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-spatialdecon/app/bioconductor-spatialdecon_server.py') +SERVER_NAME = 'biosci_bioconductor_spatialdecon' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0c0ed0c906d90e0f3d113aa5002115d8db768d83 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spatialdecon: + build: . + image: mcp-bioconductor-spatialdecon:latest + container_name: mcp-bioconductor-spatialdecon + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spatialdecon + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d63d955e7e74be859c65d8d65708872151da7394 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spatialdecon + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialdecon/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f51502a6469166062f5b32a90b5c41ef7111894c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-spatialexperiment via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spatialexperiment -y && conda clean -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-spatialexperiment_server.py /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-spatialexperiment_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-spatialexperiment_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/app/bioconductor-spatialexperiment_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/app/bioconductor-spatialexperiment_server.py new file mode 100644 index 0000000000000000000000000000000000000000..94f69fbe3ac7e3d6fa8f8d4d35ef11cb43f08de4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/app/bioconductor-spatialexperiment_server.py @@ -0,0 +1,132 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# MCP decorator placeholder. In a real MCP environment, this would be imported. +def mcp_tool(func): + """A placeholder for the @mcp.tool decorator.""" + return func + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +@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 for Rscript, allowing execution of R code from + the command line. You must provide either a path to an R script file or a list + of R expressions to execute, but not both. + + 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 '-e' for each. Mutually exclusive with 'script_file'. + script_args: A list of arguments to be passed to the R script. + verbose: If True, enables verbose output, printing information on progress. + default_packages: A comma-separated string of R package names to be loaded by default. + save: If True, saves the workspace at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, prevents reading of site and user environment files. Ignored if 'vanilla' is True. + no_site_file: If True, prevents reading of the site-wide Rprofile. Ignored if 'vanilla' is True. + no_init_file: If True, prevents reading of the user's R profile. Ignored if 'vanilla' is True. + restore: If True, restores 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. + This provides a "clean" R session. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files (if any). + """ + # 1. Input Validation + if script_file and expressions: + raise ValueError("Both 'script_file' and 'expressions' were provided. 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"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) + logging.info(f"Executing command: {command_executed}") + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = result.stdout + stderr = result.stderr + logging.info("Rscript executed successfully.") + + except FileNotFoundError: + logging.error("Rscript command not found. Make sure R is installed and in your PATH.") + raise + except subprocess.CalledProcessError as e: + logging.error(f"Rscript execution failed with return 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, + "return_code": e.returncode, + "output_files": [] + } + + # 4. Structured Result Return + # Rscript itself doesn't have a dedicated output file parameter. + # Any files created are 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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/app/bioconductor-spatialexperiment_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/app/bioconductor-spatialexperiment_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1ca7e703888294d149453ee7330f8a6202ecfc74 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/app/bioconductor-spatialexperiment_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-spatialexperiment/app/bioconductor-spatialexperiment_server.py') +SERVER_NAME = 'biosci_bioconductor_spatialexperiment' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..33c0f6d0cc7e354c915e03df3037d24bea818c82 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spatialexperiment: + build: . + image: mcp-bioconductor-spatialexperiment:latest + container_name: mcp-bioconductor-spatialexperiment + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spatialexperiment + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c4047ae88006b5844b172c47755c9915d4b4e32b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spatialexperiment + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialexperiment/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bcb4d811d5d9fc82a6372958753531073722b52 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-spatialheatmap via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spatialheatmap -y && conda clean -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-spatialheatmap_server.py /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-spatialheatmap_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-spatialheatmap_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/app/bioconductor-spatialheatmap_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/app/bioconductor-spatialheatmap_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f8aa01e910374ccd1b6ed443ba585bc93c622f3e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/app/bioconductor-spatialheatmap_server.py @@ -0,0 +1,325 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def spatial_heatmap( + expression_file: str, + svg_file: str, + gene_id: str, + output_plot: str, + data_type: str = "gene", + id_var: str = "feature", + value_var: str = "value", + color_low: str = "blue", + color_mid: str = "white", + color_high: str = "red", + scale: bool = True +): + """ + Generate a spatial heatmap by mapping expression data onto an SVG image. + + Args: + expression_file: Path to the expression data (CSV/TSV). + svg_file: Path to the SVG image file. + gene_id: The specific gene or feature ID to visualize. + output_plot: Path where the resulting plot (HTML or PNG) will be saved. + data_type: Type of data, e.g., 'gene' or 'protein'. + id_var: Column name in expression data representing spatial features. + value_var: Column name in expression data representing values. + color_low: Color for low expression values. + color_mid: Color for median expression values. + color_high: Color for high expression values. + scale: Whether to scale the data (Z-score). + """ + exp_path = Path(expression_file) + svg_path = Path(svg_file) + out_path = Path(output_plot) + + if not exp_path.exists(): + return {"error": f"Expression file not found: {expression_file}"} + if not svg_path.exists(): + return {"error": f"SVG file not found: {svg_file}"} + + # Create R script + r_script = textwrap.dedent(f""" + library(spatialHeatmap) + # Load expression data + dat <- read.table("{exp_path}", header=TRUE, sep=",", check.names=FALSE) + # Load SVG + svg <- read_svg("{svg_path}") + + # Generate spatial heatmap + # Note: This assumes a standard spatialHeatmap workflow + # In a real scenario, we'd convert the dataframe to a SummarizedExperiment + # For this tool, we use the high-level spatial_hm function + + res <- spatial_hm( + ID = "{gene_id}", + data = dat, + svg = svg, + type = "{data_type}", + col.low = "{color_low}", + col.mid = "{color_mid}", + col.high = "{color_high}", + scale = {str(scale).upper()} + ) + + # Save output + if (grepl(".html$", "{out_path}")) {{ + htmlwidgets::saveWidget(res, "{out_path}") + }} else {{ + ggplot2::ggsave("{out_path}", plot = res) + }} + """) + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + 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, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def spatial_enrichment( + expression_file: str, + output_csv: str, + method: str = "fisher", + p_cutoff: float = 0.05, + adj_method: str = "BH" +): + """ + Perform spatial enrichment analysis to identify features significantly associated with specific regions. + + Args: + expression_file: Path to the expression data (CSV/TSV). + output_csv: Path to save the enrichment results. + method: Enrichment method ('fisher', 'hypergeometric'). + p_cutoff: P-value threshold for significance. + adj_method: Multiple testing correction method (e.g., 'BH', 'bonferroni'). + """ + exp_path = Path(expression_file) + out_path = Path(output_csv) + + if not exp_path.exists(): + return {"error": f"Expression file not found: {expression_file}"} + + r_script = textwrap.dedent(f""" + library(spatialHeatmap) + dat <- read.table("{exp_path}", header=TRUE, sep=",", check.names=FALSE) + # Perform enrichment + enrich_res <- spatial_enrich( + data = dat, + method = "{method}", + p.cutoff = {p_cutoff}, + adj.method = "{adj_method}" + ) + write.csv(enrich_res, "{out_path}", row.names=FALSE) + """) + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + result = subprocess.run(["Rscript", tmp_path], capture_output=True, text=True, check=True) + + return { + "command_executed": "spatial_enrich", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "stdout": e.stdout} + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def spatial_network( + expression_file: str, + output_plot: str, + cor_method: str = "pearson", + threshold: float = 0.8, + network_type: str = "unsigned" +): + """ + Construct and visualize co-expression networks within a spatial context. + + Args: + expression_file: Path to the expression data. + output_plot: Path to save the network visualization (e.g., PNG/PDF). + cor_method: Correlation method ('pearson', 'spearman'). + threshold: Correlation threshold for edge inclusion. + network_type: Type of network ('unsigned', 'signed'). + """ + exp_path = Path(expression_file) + out_path = Path(output_plot) + + if not exp_path.exists(): + return {"error": f"Expression file not found: {expression_file}"} + + r_script = textwrap.dedent(f""" + library(spatialHeatmap) + dat <- read.table("{exp_path}", header=TRUE, sep=",", check.names=FALSE) + # Build network + net <- spatial_network( + data = dat, + cor.method = "{cor_method}", + threshold = {threshold}, + type = "{network_type}" + ) + ggplot2::ggsave("{out_path}", plot = net) + """) + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + result = subprocess.run(["Rscript", tmp_path], capture_output=True, text=True, check=True) + + return { + "command_executed": "spatial_network", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "stdout": e.stdout} + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def spatial_cluster( + expression_file: str, + output_csv: str, + k_clusters: int = 5, + cluster_method: str = "kmeans" +): + """ + Cluster spatial expression data to identify regions with similar expression profiles. + + Args: + expression_file: Path to the expression data. + output_csv: Path to save the clustering assignments. + k_clusters: Number of clusters to generate. + cluster_method: Clustering algorithm ('kmeans', 'hierarchical'). + """ + exp_path = Path(expression_file) + out_path = Path(output_csv) + + if not exp_path.exists(): + return {"error": f"Expression file not found: {expression_file}"} + if k_clusters <= 0: + return {"error": "k_clusters must be a positive integer"} + + r_script = textwrap.dedent(f""" + library(spatialHeatmap) + dat <- read.table("{exp_path}", header=TRUE, sep=",", check.names=FALSE) + # Perform clustering + clust_res <- spatial_cluster( + data = dat, + k = {k_clusters}, + method = "{cluster_method}" + ) + write.csv(clust_res, "{out_path}", row.names=TRUE) + """) + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + result = subprocess.run(["Rscript", tmp_path], capture_output=True, text=True, check=True) + + return { + "command_executed": "spatial_cluster", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "stdout": e.stdout} + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def validate_svg_mapping( + svg_file: str, + expression_file: str, + id_column: str = "feature" +): + """ + Validate that the IDs in the expression data match the IDs defined in the SVG file. + + Args: + svg_file: Path to the SVG image. + expression_file: Path to the expression data. + id_column: The column in the expression data containing spatial IDs. + """ + svg_path = Path(svg_file) + exp_path = Path(expression_file) + + if not svg_path.exists() or not exp_path.exists(): + return {"error": "Input files not found"} + + r_script = textwrap.dedent(f""" + library(spatialHeatmap) + svg_nodes <- get_node_ids("{svg_path}") + dat <- read.table("{exp_path}", header=TRUE, sep=",", check.names=FALSE) + exp_ids <- unique(dat[["{id_column}"]]) + + matches <- intersect(svg_nodes, exp_ids) + missing_in_svg <- setdiff(exp_ids, svg_nodes) + missing_in_exp <- setdiff(svg_nodes, exp_ids) + + cat("MATCHES:", length(matches), "\\n") + cat("MISSING_IN_SVG:", paste(missing_in_svg, collapse=","), "\\n") + cat("MISSING_IN_EXP:", paste(missing_in_exp, collapse=","), "\\n") + """) + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + result = subprocess.run(["Rscript", tmp_path], capture_output=True, text=True, check=True) + + return { + "command_executed": "validate_svg_mapping", + "stdout": result.stdout, + "stderr": result.stderr, + "validation_summary": result.stdout.splitlines() + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "stdout": e.stdout} + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/app/bioconductor-spatialheatmap_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/app/bioconductor-spatialheatmap_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..76e4b453431f2ff6cf44b5c7bcd732c04a41fe92 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/app/bioconductor-spatialheatmap_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-spatialheatmap/app/bioconductor-spatialheatmap_server.py') +SERVER_NAME = 'biosci_bioconductor_spatialheatmap' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..688ecf4a2246cff81669cb5b15537a22d7acde5f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spatialheatmap: + build: . + image: mcp-bioconductor-spatialheatmap:latest + container_name: mcp-bioconductor-spatialheatmap + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spatialheatmap + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..610ffebe04d9619edc7c57ceecf6e648e65ee52d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spatialheatmap + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-spatialheatmap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1ee87c374960128cb95f57a2fe6f37102f39662c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-tximport via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-tximport -y && conda clean -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-tximport_server.py /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-tximport_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-tximport_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/app/bioconductor-tximport_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/app/bioconductor-tximport_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ccff48fabee1f641241e36bc6a1ee3d294ce0c53 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/app/bioconductor-tximport_server.py @@ -0,0 +1,255 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def tximport( + files: List[str], + type: str, + tx_in: bool = True, + tx_out: bool = False, + counts_from_abundance: str = "no", + tx2gene: Optional[str] = None, + var_reduce: bool = False, + drop_inf_reps: bool = False, + ignore_tx_version: bool = False, + ignore_after_bar: bool = False, + gene_id_col: str = "gene_id", + tx_id_col: str = "tx_id", + abundance_col: str = "abundance", + counts_col: str = "counts", + length_col: str = "length", + output_rds: str = "tximport_result.rds" +): + """ + Import transcript-level abundance, count, and length estimates from various + quantification tools and summarize them to gene-level. + + Args: + files: List of paths to quantification files (e.g., quant.sf, abundance.h5). + type: Type of quantification tool ('salmon', 'kallisto', 'sailfish', 'rsem', 'stringtie', 'none'). + tx_in: Whether the input files are at transcript level. + tx_out: Whether the output should be at transcript level. + counts_from_abundance: Whether to generate estimated counts from abundance ('no', 'scaledTPM', 'lengthScaledTPM', 'dtuScaledTPM'). + tx2gene: Path to a CSV/TSV file with two columns: transcript ID and gene ID. Required for gene-level summarization. + var_reduce: Whether to reduce variance across inferential replicates. + drop_inf_reps: Whether to drop inferential replicates from the output. + ignore_tx_version: Whether to split transcript IDs on dot and keep the first part. + ignore_after_bar: Whether to split transcript IDs on bar and keep the first part. + gene_id_col: Column name for gene ID in tx2gene file. + tx_id_col: Column name for transcript ID in tx2gene file. + abundance_col: Column name for abundance (for type='none'). + counts_col: Column name for counts (for type='none'). + length_col: Column name for length (for type='none'). + output_rds: Path to save the resulting tximport list object as an RDS file. + """ + # Validation + valid_types = ["salmon", "kallisto", "sailfish", "rsem", "stringtie", "none"] + if type not in valid_types: + raise ValueError(f"Invalid type. Must be one of: {', '.join(valid_types)}") + + valid_cfa = ["no", "scaledTPM", "lengthScaledTPM", "dtuScaledTPM"] + if counts_from_abundance not in valid_cfa: + raise ValueError(f"counts_from_abundance must be one of: {', '.join(valid_cfa)}") + + for f in files: + if not Path(f).exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + if tx2gene and not Path(tx2gene).exists(): + raise FileNotFoundError(f"tx2gene file not found: {tx2gene}") + + # Construct R script + files_r_vector = 'c("' + '", "'.join(files) + '")' + + r_script_content = f""" + library(tximport) + + files <- {files_r_vector} + names(files) <- basename(dirname(files)) # Attempt to name samples by directory + + tx2gene <- NULL + if (!is.null("{tx2gene}") && "{tx2gene}" != "None") {{ + tx2gene <- read.csv("{tx2gene}", stringsAsFactors = FALSE) + # Ensure tx2gene has only two columns if not specified otherwise + if (ncol(tx2gene) > 2) {{ + # Try to find columns based on provided names + cols <- c("{tx_id_col}", "{gene_id_col}") + if (all(cols %in% colnames(tx2gene))) {{ + tx2gene <- tx2gene[, cols] + }} + }} + }} + + txi <- tximport( + files = files, + type = "{type}", + txIn = {str(tx_in).upper()}, + txOut = {str(tx_out).upper()}, + countsFromAbundance = "{counts_from_abundance}", + tx2gene = tx2gene, + varReduce = {str(var_reduce).upper()}, + dropInfReps = {str(drop_inf_reps).upper()}, + ignoreTxVersion = {str(ignore_tx_version).upper()}, + ignoreAfterBar = {str(ignore_after_bar).upper()}, + geneIdCol = "{gene_id_col}", + txIdCol = "{tx_id_col}", + abundanceCol = "{abundance_col}", + countsCol = "{counts_col}", + lengthCol = "{length_col}" + ) + + saveRDS(txi, file = "{output_rds}") + + # Also export counts as CSV for convenience + write.csv(txi$counts, file = "tximport_counts.csv") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + try: + # Using conda run as per the user's environment context + cmd = ["conda", "run", "-n", "bioenv_r_bioc", "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, "tximport_counts.csv"] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def summarize_to_gene( + txi_rds_input: str, + tx2gene: str, + ignore_tx_version: bool = False, + ignore_after_bar: bool = False, + counts_from_abundance: str = "no", + output_rds: str = "summarized_gene_txi.rds" +): + """ + Summarize transcript-level tximport list to gene-level. + Useful if tximport was run with txOut=True initially. + + Args: + txi_rds_input: Path to an RDS file containing a tximport list object (transcript level). + tx2gene: Path to a CSV/TSV file mapping transcripts to genes. + ignore_tx_version: Whether to split transcript IDs on dot. + ignore_after_bar: Whether to split transcript IDs on bar. + counts_from_abundance: How to generate counts ('no', 'scaledTPM', 'lengthScaledTPM', 'dtuScaledTPM'). + output_rds: Path to save the summarized RDS file. + """ + if not Path(txi_rds_input).exists(): + raise FileNotFoundError(f"Input RDS not found: {txi_rds_input}") + if not Path(tx2gene).exists(): + raise FileNotFoundError(f"tx2gene file not found: {tx2gene}") + + r_script_content = f""" + library(tximport) + txi <- readRDS("{txi_rds_input}") + tx2gene <- read.csv("{tx2gene}", stringsAsFactors = FALSE) + + txi_gene <- summarizeToGene( + object = txi, + tx2gene = tx2gene, + ignoreTxVersion = {str(ignore_tx_version).upper()}, + ignoreAfterBar = {str(ignore_after_bar).upper()}, + countsFromAbundance = "{counts_from_abundance}" + ) + + saveRDS(txi_gene, file = "{output_rds}") + write.csv(txi_gene$counts, file = "summarized_counts.csv") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + try: + cmd = ["conda", "run", "-n", "bioenv_r_bioc", "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, "summarized_counts.csv"] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def make_tx2gene_from_gtf( + gtf_file: str, + output_csv: str = "tx2gene.csv", + tx_id_type: str = "transcript_id", + gene_id_type: str = "gene_id" +): + """ + Helper tool to create a tx2gene mapping file from a GTF file using GenomicFeatures. + + Args: + gtf_file: Path to the GTF annotation file. + output_csv: Path to save the resulting CSV mapping. + tx_id_type: The attribute name in GTF for transcript IDs. + gene_id_type: The attribute name in GTF for gene IDs. + """ + if not Path(gtf_file).exists(): + raise FileNotFoundError(f"GTF file not found: {gtf_file}") + + r_script_content = f""" + library(GenomicFeatures) + txdb <- makeTxDbFromGFF("{gtf_file}") + k <- keys(txdb, keytype = "TXNAME") + tx2gene <- select(txdb, keys = k, columns = "{gene_id_type.upper()}", keytype = "TXNAME") + # Standardize column names for tximport + colnames(tx2gene) <- c("tx_id", "gene_id") + write.csv(tx2gene, file = "{output_csv}", row.names = FALSE) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + try: + cmd = ["conda", "run", "-n", "bioenv_r_bioc", "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_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed (Ensure GenomicFeatures is installed)", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/app/bioconductor-tximport_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/app/bioconductor-tximport_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2d7103f7d0dd7eea10e7cb43a6f8651be9c0f151 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/app/bioconductor-tximport_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-tximport/app/bioconductor-tximport_server.py') +SERVER_NAME = 'biosci_bioconductor_tximport' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2b25ee9a91f345006f65b83de9217949340d1ddf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-tximport: + build: . + image: mcp-bioconductor-tximport:latest + container_name: mcp-bioconductor-tximport + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-tximport + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2fb59aa90fa59e686c3d544a2797d80adcb4bcef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-tximport + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-tximport/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9eba1236c15352fa72134cd39a1fd198f2d672ad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-variantannotation via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-variantannotation -y && conda clean -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-variantannotation_server.py /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-variantannotation_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-variantannotation_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/app/bioconductor-variantannotation_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/app/bioconductor-variantannotation_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a528c329b8ac8fbccb9550a3e71c4060598a979a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/app/bioconductor-variantannotation_server.py @@ -0,0 +1,375 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Optional + +# MCP decorator is not imported as per instructions. +# It is assumed to be available in the execution environment. + +# @mcp.tool() +def predict_coding( + vcf_file: Path, + txdb_package: str, + bsgenome_package: str, + output_tsv: Path, + ignore_strand: bool = False, +) -> Dict: + """ + Predicts coding consequences of variants using Bioconductor's VariantAnnotation. + + This tool wraps the `predictCoding()` function from the R/Bioconductor + `VariantAnnotation` package. It identifies variants as synonymous, + nonsynonymous, frameshift, or nonsense and writes the results to a TSV file. + + Args: + vcf_file: Path to the input VCF file containing variants to be annotated. + txdb_package: The name of the Bioconductor TxDb annotation package + (e.g., "TxDb.Hsapiens.UCSC.hg19.knownGene"). This package + must be installed in the R environment. + bsgenome_package: The name of the Bioconductor BSgenome package for the + reference genome (e.g., "BSgenome.Hsapiens.UCSC.hg19"). + This package must be installed in the R environment. + output_tsv: Path to the output TSV file where annotations will be saved. + ignore_strand: If True, strand information is ignored when matching variants + to transcripts. Corresponds to the `ignore.strand` parameter. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of output files. + """ + # --- Input Validation --- + if not vcf_file.exists(): + raise FileNotFoundError(f"Input VCF file not found: {vcf_file}") + if not txdb_package: + raise ValueError("txdb_package name cannot be empty.") + if not bsgenome_package: + raise ValueError("bsgenome_package name cannot be empty.") + + output_tsv.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_content = f""" + # Load necessary libraries + suppressPackageStartupMessages(library(VariantAnnotation)) + suppressPackageStartupMessages(library({txdb_package}, character.only = TRUE)) + suppressPackageStartupMessages(library({bsgenome_package}, character.only = TRUE)) + + # Assign objects from loaded packages + txdb <- {txdb_package} + bsgenome <- {bsgenome_package} + + # Read VCF file + vcf <- readVcf("{vcf_file}") + + # Predict coding consequences + # We use rowRanges() to get the genomic locations from the VCF object + coding_predictions <- predictCoding( + vcf, + txdb, + seqSource = bsgenome, + ignore.strand = {"TRUE" if ignore_strand else "FALSE"} + ) + + # Convert the result (a GRanges object) to a data.frame for easy writing + df_predictions <- as.data.frame(coding_predictions) + + # Write to output TSV file + write.table( + df_predictions, + file = "{output_tsv}", + sep = "\\t", + quote = FALSE, + row.names = FALSE, + col.names = TRUE + ) + + cat("Annotation complete. Results saved to {output_tsv}\\n") + """ + + # --- Subprocess Execution --- + command = [] + stdout_str, stderr_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 + Path(r_script_path).unlink() + + 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 + # Add context from the R script to the error message + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(command)}\n" + f"Stderr:\n{e.stderr}\n" + "Please ensure all specified R packages (VariantAnnotation, " + f"{txdb_package}, {bsgenome_package}) are correctly installed." + ) + raise RuntimeError(error_message) from e + except Exception as e: + # Catch other potential errors and clean up the temp file + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + raise e + + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_tsv)], + } + + +# @mcp.tool() +def locate_variants( + vcf_file: Path, + txdb_package: str, + region: str, + output_tsv: Path, + ignore_strand: bool = False, + promoter_upstream: int = 2000, + promoter_downstream: int = 200, +) -> Dict: + """ + Locates variants relative to genomic features (e.g., genes, exons, promoters). + + This tool wraps the `locateVariants()` function from Bioconductor's + `VariantAnnotation` package. It identifies which variants from a VCF file + overlap with specified genomic regions from a TxDb annotation database. + + Args: + vcf_file: Path to the input VCF file. + txdb_package: The name of the Bioconductor TxDb annotation package + (e.g., "TxDb.Hsapiens.UCSC.hg19.knownGene"). + region: The genomic region to query. Must be one of: 'gene', 'tx', + 'exon', 'cds', 'promoter', 'fiveUTR', 'threeUTR'. + output_tsv: Path to the output TSV file to save the results. + ignore_strand: If True, strand is ignored when calculating overlaps. + promoter_upstream: The number of base pairs upstream of the TSS to + define the promoter region. Only used if region='promoter'. + promoter_downstream: The number of base pairs downstream of the TSS to + define the promoter region. Only used if region='promoter'. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of output files. + """ + # --- Input Validation --- + if not vcf_file.exists(): + raise FileNotFoundError(f"Input VCF file not found: {vcf_file}") + if not txdb_package: + raise ValueError("txdb_package name cannot be empty.") + + valid_regions = ['gene', 'tx', 'exon', 'cds', 'promoter', 'fiveUTR', 'threeUTR'] + if region not in valid_regions: + raise ValueError(f"Invalid region '{region}'. Must be one of {valid_regions}") + + if promoter_upstream < 0 or promoter_downstream < 0: + raise ValueError("Promoter upstream and downstream values must be non-negative.") + + output_tsv.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + # Logic to define the query regions in R + region_logic = { + 'gene': 'genes(txdb)', + 'tx': 'transcripts(txdb)', + 'exon': 'exons(txdb)', + 'cds': 'cds(txdb)', + 'promoter': f'promoters(txdb, upstream={promoter_upstream}, downstream={promoter_downstream})', + 'fiveUTR': 'fiveUTRsByTranscript(txdb)', + 'threeUTR': 'threeUTRsByTranscript(txdb)' + } + + r_script_content = f""" + suppressPackageStartupMessages(library(VariantAnnotation)) + suppressPackageStartupMessages(library(GenomicFeatures)) + suppressPackageStartupMessages(library({txdb_package}, character.only = TRUE)) + + txdb <- {txdb_package} + vcf <- readVcf("{vcf_file}") + query_regions <- {region_logic[region]} + + # Locate variants + located_variants <- locateVariants( + vcf, + txdb, + query_regions, + ignore.strand = {"TRUE" if ignore_strand else "FALSE"} + ) + + # Convert result to a data.frame and write to file + df_located <- as.data.frame(located_variants) + write.table( + df_located, + file = "{output_tsv}", + sep = "\\t", + quote = FALSE, + row.names = FALSE, + col.names = TRUE + ) + + cat("Variant location analysis complete. Results saved to {output_tsv}\\n") + """ + + # --- Subprocess Execution --- + command = [] + stdout_str, stderr_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 + Path(r_script_path).unlink() + + 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 + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(command)}\n" + f"Stderr:\n{e.stderr}\n" + "Please ensure all specified R packages (VariantAnnotation, GenomicFeatures, " + f"{txdb_package}) are correctly installed." + ) + raise RuntimeError(error_message) from e + except Exception as e: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + raise e + + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_tsv)], + } + + +# @mcp.tool() +def filter_vcf( + vcf_file: Path, + output_vcf: Path, + filter_expression: str, + genome: str, +) -> Dict: + """ + Filters a VCF file based on a user-defined R expression. + + This tool wraps the `filterVcf()` function from Bioconductor's + `VariantAnnotation` package. It allows for powerful, flexible filtering + of a VCF file using R syntax to access INFO and FORMAT fields. + + Args: + vcf_file: Path to the input VCF file. + output_vcf: Path to write the filtered VCF file. + filter_expression: An R expression that evaluates to a logical vector for + filtering. The VCF object is represented by 'x'. + Example: "info(x)$DP > 20 & qual(x) >= 30" + genome: The genome assembly name (e.g., "hg19", "hg38"). This is + required by the underlying `filterVcf` function. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of output files. + """ + # --- Input Validation --- + if not vcf_file.exists(): + raise FileNotFoundError(f"Input VCF file not found: {vcf_file}") + if not filter_expression: + raise ValueError("filter_expression cannot be empty.") + if not genome: + raise ValueError("genome assembly name cannot be empty.") + + output_vcf.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + # The filter expression needs to be properly quoted for the R script + r_safe_expression = filter_expression.replace('"', '\\"') + + r_script_content = f""" + suppressPackageStartupMessages(library(VariantAnnotation)) + + # Define the filter rule using the user's expression + # The expression is parsed and evaluated in the context of the filterVcf function + custom_filter <- function(x) {{ + {r_safe_expression} + }} + filter_rules <- FilterRules(list(custom = custom_filter)) + + # Apply the filter + filterVcf( + file = "{vcf_file}", + genome = "{genome}", + destination = "{output_vcf}", + filters = filter_rules, + verbose = TRUE + ) + + cat("VCF filtering complete. Filtered file saved to {output_vcf}\\n") + """ + + # --- Subprocess Execution --- + command = [] + stdout_str, stderr_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 + Path(r_script_path).unlink() + + 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 + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(command)}\n" + f"Stderr:\n{e.stderr}\n" + "Please ensure the VariantAnnotation R package is installed and that your " + f"filter expression '{filter_expression}' is valid R syntax." + ) + raise RuntimeError(error_message) from e + except Exception as e: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + raise e + + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_vcf)], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/app/bioconductor-variantannotation_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/app/bioconductor-variantannotation_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..01f38a308121272e2f2883b65766cbc108e52e2c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/app/bioconductor-variantannotation_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-variantannotation/app/bioconductor-variantannotation_server.py') +SERVER_NAME = 'biosci_bioconductor_variantannotation' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..fbaa53e15ac60bfa3e1f252a53099b3391f9161c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-variantannotation: + build: . + image: mcp-bioconductor-variantannotation:latest + container_name: mcp-bioconductor-variantannotation + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-variantannotation + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..53cdef0f6c570e71282a7d3bc9e4ee7d14fa1fa1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-variantannotation + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-variantannotation/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..300f89e40e09a3aa8b27e06ad5193bae60eb31ad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-xvector via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-xvector -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-xvector_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-xvector_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-xvector_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/bioconductor-xvector_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/bioconductor-xvector_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b53f4542fca2d6e83dff9ff3930eebc0201aa345 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/bioconductor-xvector_server.py @@ -0,0 +1,342 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Union, Dict, Any +import json +import tempfile + +def _run_r_command(script: str) -> dict: + """ + Helper function to execute R code via Rscript. + """ + if not subprocess.run(["which", "Rscript"], capture_output=True).returncode == 0: + raise RuntimeError("Rscript not found. Please ensure R and Bioconductor-XVector are installed.") + + # Check if XVector is installed in R + check_pkg = "if (!requireNamespace('XVector', quietly = TRUE)) quit(status = 1)" + if subprocess.run(["Rscript", "-e", check_pkg]).returncode != 0: + raise RuntimeError("R package 'XVector' is not installed.") + + try: + result = subprocess.run( + ["Rscript", "-e", script], + capture_output=True, + text=True, + check=True + ) + return { + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "error_msg": str(e) + } + +@mcp.tool() +def xvector_get_info( + rds_path: str +) -> Dict[str, Any]: + """ + Retrieve metadata about an XVector object stored in an RDS file. + + Args: + rds_path: Path to the .rds file containing the XVector object. + """ + path = Path(rds_path) + if not path.exists(): + return {"error": f"File {rds_path} not found."} + + script = f""" + library(XVector) + obj <- readRDS('{rds_path}') + cat(paste0('class:', class(obj), '\\n')) + cat(paste0('length:', length(obj), '\\n')) + cat(paste0('typeof:', typeof(obj), '\\n')) + if (is(obj, 'XVectorList')) {{ + cat(paste0('element_lengths:', paste(elementNROWS(obj), collapse=','), '\\n')) + }} + """ + + res = _run_r_command(script) + return { + "command_executed": f"Rscript -e \"{script.strip()}\"", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "status": res.get("status") + } + +@mcp.tool() +def xvector_subseq( + input_rds: str, + output_rds: str, + start: Optional[int] = None, + end: Optional[int] = None, + width: Optional[int] = None +) -> Dict[str, Any]: + """ + Extract a subsequence from an XVector object using subseq(). + + Args: + input_rds: Path to input .rds file. + output_rds: Path to save the resulting .rds file. + start: The start index of the subsequence. + end: The end index of the subsequence. + width: The width of the subsequence. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + # Build R arguments + args = [] + if start is not None: args.append(f"start={start}") + if end is not None: args.append(f"end={end}") + if width is not None: args.append(f"width={width}") + + arg_str = ", ".join(args) + if arg_str: + arg_str = ", " + arg_str + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + res <- subseq(x{arg_str}) + saveRDS(res, '{output_rds}') + """ + + res = _run_r_command(script) + return { + "command_executed": f"subseq(x{arg_str})", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_rds] if res.get("status") == "success" else [] + } + +@mcp.tool() +def xvector_narrow( + input_rds: str, + output_rds: str, + start: int = 1, + end: Optional[int] = None, + width: Optional[int] = None +) -> Dict[str, Any]: + """ + Narrow an XVector object. Unlike subseq, narrow creates a view without copying data. + + Args: + input_rds: Path to input .rds file. + output_rds: Path to save the resulting .rds file. + start: Relative start offset. + end: Relative end offset. + width: Desired width. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + args = [f"start={start}"] + if end is not None: args.append(f"end={end}") + if width is not None: args.append(f"width={width}") + + arg_str = ", ".join(args) + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + res <- narrow(x, {arg_str}) + saveRDS(res, '{output_rds}') + """ + + res = _run_r_command(script) + return { + "command_executed": f"narrow(x, {arg_str})", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_rds] + } + +@mcp.tool() +def xvector_compact( + input_rds: str, + output_rds: str +) -> Dict[str, Any]: + """ + Compact an XVector object to force memory deallocation of unused parts of the external vector. + + Args: + input_rds: Path to input .rds file. + output_rds: Path to save the compacted .rds file. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + res <- compact(x) + saveRDS(res, '{output_rds}') + """ + + res = _run_r_command(script) + return { + "command_executed": "compact(x)", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_rds] + } + +@mcp.tool() +def xvector_slice( + input_rds: str, + lower: float = -float('inf'), + upper: float = float('inf') +) -> Dict[str, Any]: + """ + Slice an XInteger or XDouble vector to find ranges where values are within [lower, upper]. + Returns a summary of the ranges. + + Args: + input_rds: Path to input .rds file. + lower: Lower bound for slicing. + upper: Upper bound for slicing. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + # Handle infinity for R + r_lower = "-Inf" if lower == -float('inf') else lower + r_upper = "Inf" if upper == float('inf') else upper + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + sl <- slice(x, lower={r_lower}, upper={r_upper}) + print(sl) + """ + + res = _run_r_command(script) + return { + "command_executed": f"slice(x, lower={r_lower}, upper={r_upper})", + "stdout": res.get("stdout"), + "stderr": res.get("stderr") + } + +@mcp.tool() +def xvector_to_raw( + input_rds: str, + output_bin: str +) -> Dict[str, Any]: + """ + Export the raw content of an XVector to a binary file. + + Args: + input_rds: Path to input .rds file. + output_bin: Path to the output binary file. + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + # Ensure it is an XRaw or similar + writeBin(as.raw(x), '{output_bin}') + """ + + res = _run_r_command(script) + return { + "command_executed": "writeBin(as.raw(x), ...)", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_bin] + } + +@mcp.tool() +def xvector_aggregate( + input_rds: str, + method: str = "sum" +) -> Dict[str, Any]: + """ + Perform aggregation on an XVector (sum, mean, min, max). + + Args: + input_rds: Path to input .rds file. + method: Aggregation method ('sum', 'mean', 'min', 'max'). + """ + if method not in ["sum", "mean", "min", "max"]: + return {"error": "Method must be one of: sum, mean, min, max"} + + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + script = f""" + library(XVector) + x <- readRDS('{input_rds}') + val <- {method}(x, na.rm=TRUE) + cat(val) + """ + + res = _run_r_command(script) + return { + "command_executed": f"{method}(x)", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "result": res.get("stdout").strip() if res.get("status") == "success" else None + } + +@mcp.tool() +def xvector_create_from_list( + data: List[float], + type: str = "double", + output_rds: str = "vector.rds" +) -> Dict[str, Any]: + """ + Create an XVector object from a Python list and save as RDS. + + Args: + data: List of numeric values. + type: Type of XVector to create ('integer', 'double', 'raw'). + output_rds: Filename for the output RDS. + """ + if type not in ["integer", "double", "raw"]: + return {"error": "Type must be 'integer', 'double', or 'raw'"} + + # Create a temporary file for the data to pass to R + with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as tmp: + json.dump(data, tmp) + tmp_path = tmp.name + + r_class = { + "integer": "XInteger", + "double": "XDouble", + "raw": "XRaw" + }[type] + + script = f""" + library(XVector) + library(jsonlite) + raw_data <- fromJSON('{tmp_path}') + vec <- as(raw_data, '{r_class}') + saveRDS(vec, '{output_rds}') + """ + + try: + res = _run_r_command(script) + return { + "command_executed": f"as(data, '{r_class}')", + "stdout": res.get("stdout"), + "stderr": res.get("stderr"), + "output_files": [output_rds] + } + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/bioconductor-xvector_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/bioconductor-xvector_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7a64dc4d1deab749835427232a7ffb45f8778326 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/bioconductor-xvector_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/bioconductor-xvector_server.py') +SERVER_NAME = 'biosci_bioconductor_xvector' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5a5367493fffc3a6cb5c8110673556796cf375d6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-xvector: + build: . + image: mcp-bioconductor-xvector:latest + container_name: mcp-bioconductor-xvector + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-xvector + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb31b4b13d7d554be35fbdf864159c5e39fd7541 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-xvector + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-xvector/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..48bafb10c18bb5ffc2209a4f57ce2b58af3f38a3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-zlibbioc via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-zlibbioc -y && conda clean -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-zlibbioc_server.py /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-zlibbioc_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-zlibbioc_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/app/bioconductor-zlibbioc_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/app/bioconductor-zlibbioc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4a770418dda4a68dded2fed1465752b979c1d46d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/app/bioconductor-zlibbioc_server.py @@ -0,0 +1,172 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Assume @mcp.tool is imported from the mcp library +# from mcp import tool + +@mcp.tool() +def run_rscript( + r_script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + r_script_args: Optional[List[str]] = None, + help_flag: bool = False, + version_flag: 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 file or R expressions using the Rscript command. + + This tool provides an interface to the Rscript command, allowing users to run R code + from the command line, either by specifying a script file or by providing R expressions + directly. It supports various Rscript options for controlling the R session behavior. + + Args: + r_script_file: Path to an R script file to execute. Mutually exclusive with 'expressions'. + The file must exist. + expressions: A list of R expressions to execute. Each string in the list will be + passed with a separate '-e' flag. Mutually exclusive with 'r_script_file'. + r_script_args: A list of arguments to be passed to the R script itself. These are + appended after the script file or expressions. + help_flag: If True, print usage information and exit. When True, all other parameters + related to script execution are ignored. + version_flag: If True, print version information and exit. When True, all other parameters + related to script execution are ignored. + verbose: If True, print information on progress during Rscript execution. + default_packages: A comma-separated list of package names, or 'NULL', to load by default. + If None, this option is not included. + save: If True, save the workspace at the end of the session. Cannot be used with 'vanilla'. + no_environ: If True, don't read the site and user environment files. + This is implied by 'vanilla'. + no_site_file: If True, don't read the site-wide Rprofile. + This is implied by 'vanilla'. + no_init_file: If True, don't read the user R profile. + This is implied by 'vanilla'. + restore: If True, restore previously saved objects at startup. Cannot be used with 'vanilla'. + vanilla: If True, combine --no-save, --no-restore, --no-site-file, --no-init-file, + and --no-environ. Cannot be used with 'save' or 'restore'. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + 'output_files' will typically be empty unless the R script itself creates files + in a known location. + """ + cmd = ["Rscript"] + output_files: List[Path] = [] + + # Handle --help and --version first, as they are standalone and override other options + if help_flag: + cmd.append("--help") + elif version_flag: + cmd.append("--version") + else: + # Input validation for script/expressions + if r_script_file and expressions: + raise ValueError("Cannot specify both 'r_script_file' and 'expressions'. Choose one.") + if not r_script_file and not expressions: + raise ValueError("Either 'r_script_file' or 'expressions' must be provided.") + + # Validate --vanilla conflicts + if vanilla: + conflicting_options = [] + if save: + conflicting_options.append("--save") + if restore: + conflicting_options.append("--restore") + if conflicting_options: + raise ValueError( + f"Cannot use --vanilla with conflicting options: {', '.join(conflicting_options)}. " + "--vanilla implies --no-save and --no-restore." + ) + + # Add general options + if verbose: + cmd.append("--verbose") + if default_packages is not None: + cmd.append(f"--default-packages={default_packages}") + + # Add R session options + if vanilla: + cmd.append("--vanilla") + else: + # Only add these if vanilla is not set, to avoid redundancy and potential conflicts + 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") + + # Handle script file vs expressions + if r_script_file: + if not r_script_file.is_file(): + raise FileNotFoundError(f"R script file not found: {r_script_file}") + cmd.append(str(r_script_file)) + elif expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + # Add arguments to the R script + if r_script_args: + cmd.extend(r_script_args) + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + command_executed = " ".join(cmd) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except FileNotFoundError: + # This specific error means the 'Rscript' executable itself was not found + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: Rscript command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + # This means Rscript ran, but exited with a non-zero status + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except ValueError as e: + # Catch validation errors before subprocess call + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Input validation error: {e}", + "output_files": [], + } + except Exception as e: + # Catch any other unexpected errors + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"An unexpected error occurred: {e}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/app/bioconductor-zlibbioc_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/app/bioconductor-zlibbioc_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f70f867cd8e6e8f42b9b42afe798ece33628d3db --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/app/bioconductor-zlibbioc_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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-zlibbioc/app/bioconductor-zlibbioc_server.py') +SERVER_NAME = 'biosci_bioconductor_zlibbioc' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0725bb33611e65ca6c39a977c9733243aa80647c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-zlibbioc: + build: . + image: mcp-bioconductor-zlibbioc:latest + container_name: mcp-bioconductor-zlibbioc + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-zlibbioc + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4d1768c84dd8493e0a4816be7680761fd5fb9a40 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-zlibbioc + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-zlibbioc/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e618d5ca452137ae2321ec6a1288fb5f692d1015 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install blast via conda (e.g., from bioconda) +RUN conda install -c bioconda blast -y && conda clean -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/blast_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/blast_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/blast_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/app/blast_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/app/blast_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6362c267d735b88183fdf7163b3eb267c29abc54 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/app/blast_server.py @@ -0,0 +1,433 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Mock decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def run_perl_script( + programfile: Path, + script_args: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + run_debugger: bool = False, + debugger_name: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_backup_ext: Optional[str] = None, + include_dirs: Optional[List[Path]] = None, + line_ending: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + extract_from_text: bool = False, + extract_from_text_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script with a comprehensive set of interpreter switches. + + Args: + programfile: Path to the Perl program file to execute. + script_args: A list of arguments to pass to the program file. + record_separator: (-0[octal]) Specify the record separator. + autosplit: (-a) Enable autosplit mode with -n or -p. + unicode_features: (-C[number/list]) Enable listed Unicode features. + run_debugger: (-d) Run the program under the debugger. + debugger_name: (:-d[debugger]) Specify a debugger to use. + debugging_flags: (-D[number/list]) Set debugging flags. + no_sitecustomize: (-f) Do not do $sitelib/sitecustomize.pl at startup. + split_pattern: (-F/pattern/) Specify the split() pattern for autosplit mode. + in_place_edit_backup_ext: (-i[extension]) Edit <> files in place. Provide an extension for backups (e.g., '.bak'). + include_dirs: (-Idirectory) Specify @INC/#include directories. + line_ending: (-l[octal]) Enable line ending processing and specify the terminator. + use_modules: (-Mmodule) Execute "use module..." before the program. + no_modules: (-m[-]module) Execute "no module..." before the program. + loop_around_program: (-n) Assume "while (<>) { ... }" loop around the program. + loop_and_print: (-p) Assume loop like -n but also print the line. + parse_switches: (-s) Enable rudimentary parsing for switches after the program file. + search_path: (-S) Look for the program file using the PATH environment variable. + tainting_warnings: (-t) Enable tainting warnings. + tainting_checks: (-T) Enable tainting checks. + dump_core: (-u) Dump core after parsing the program. + unsafe_operations: (-U) Allow unsafe operations. + enable_warnings: (-w) Enable many useful warnings. + enable_all_warnings: (-W) Enable all warnings. + extract_from_text: (-x) Ignore text before the #!perl line. + extract_from_text_dir: (-x[directory]) Optionally cd to this directory before executing. + disable_all_warnings: (-X) Disable all warnings. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + if not search_path and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if debugger_name: + cmd.append(f"-d:{debugger_name}") + elif run_debugger: + cmd.append("-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit_backup_ext is not None: + cmd.append(f"-i{in_place_edit_backup_ext}") + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + if line_ending is not None: + cmd.append(f"-l{line_ending}") + if use_modules: + for module in use_modules: + cmd.append(f"-M{module}") + if no_modules: + for module in no_modules: + cmd.append(f"-m{module}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if unsafe_operations: + cmd.append("-U") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if extract_from_text_dir: + cmd.append(f"-x{str(extract_from_text_dir)}") + elif extract_from_text: + cmd.append("-x") + if disable_all_warnings: + cmd.append("-X") + + cmd.append(str(programfile)) + + if script_args: + cmd.extend(script_args) + + command_executed = shlex.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 subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool +def run_perl_oneliner( + program: str, + enable_all_features: bool = False, + script_args: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + debugging_flags: Optional[str] = None, + split_pattern: Optional[str] = None, + include_dirs: Optional[List[Path]] = None, + line_ending: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + unsafe_operations: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a one-line Perl program from a string. + + Args: + program: One line of program to execute. + enable_all_features: (-E) Like -e, but enables all optional features. + script_args: A list of arguments to pass to the program. + record_separator: (-0[octal]) Specify the record separator. + autosplit: (-a) Enable autosplit mode with -n or -p. + unicode_features: (-C[number/list]) Enable listed Unicode features. + debugging_flags: (-D[number/list]) Set debugging flags. + split_pattern: (-F/pattern/) Specify the split() pattern for autosplit mode. + include_dirs: (-Idirectory) Specify @INC/#include directories. + line_ending: (-l[octal]) Enable line ending processing and specify the terminator. + use_modules: (-Mmodule) Execute "use module..." before the program. + no_modules: (-m[-]module) Execute "no module..." before the program. + loop_around_program: (-n) Assume "while (<>) { ... }" loop around the program. + loop_and_print: (-p) Assume loop like -n but also print the line. + tainting_warnings: (-t) Enable tainting warnings. + tainting_checks: (-T) Enable tainting checks. + unsafe_operations: (-U) Allow unsafe operations. + enable_warnings: (-w) Enable many useful warnings. + enable_all_warnings: (-W) Enable all warnings. + disable_all_warnings: (-X) Disable all warnings. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + if line_ending is not None: + cmd.append(f"-l{line_ending}") + if use_modules: + for module in use_modules: + cmd.append(f"-M{module}") + if no_modules: + for module in no_modules: + cmd.append(f"-m{module}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if unsafe_operations: + cmd.append("-U") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if disable_all_warnings: + cmd.append("-X") + + if enable_all_features: + cmd.extend(["-E", program]) + else: + cmd.extend(["-e", program]) + + if script_args: + cmd.extend(script_args) + + command_executed = shlex.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: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with exit code {e.returncode}" + } + +@mcp.tool +def check_perl_syntax( + programfile: Path, + include_dirs: Optional[List[Path]] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + tainting_checks: bool = False, + unsafe_operations: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Checks the syntax of a Perl script without executing it. + + Args: + programfile: Path to the Perl program file to check. + include_dirs: (-Idirectory) Specify @INC/#include directories. + use_modules: (-Mmodule) Execute "use module..." before checking. + no_modules: (-m[-]module) Execute "no module..." before checking. + tainting_checks: (-T) Enable tainting checks during compilation. + unsafe_operations: (-U) Allow unsafe operations during compilation. + enable_warnings: (-w) Enable many useful warnings during compilation. + enable_all_warnings: (-W) Enable all warnings during compilation. + disable_all_warnings: (-X) Disable all warnings during compilation. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + cmd = ["perl", "-c"] + + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + if use_modules: + for module in use_modules: + cmd.append(f"-M{module}") + if no_modules: + for module in no_modules: + cmd.append(f"-m{module}") + if tainting_checks: + cmd.append("-T") + if unsafe_operations: + cmd.append("-U") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if disable_all_warnings: + cmd.append("-X") + + cmd.append(str(programfile)) + + command_executed = shlex.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, + "syntax_ok": f"{programfile} syntax OK" in result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl syntax check failed with exit code {e.returncode}", + "syntax_ok": False + } + +@mcp.tool +def get_perl_version() -> Dict[str, Any]: + """ + Prints the version, patchlevel, and license of the Perl interpreter. + + Returns: + A dictionary containing the command executed and the version information. + """ + cmd = ["perl", "-v"] + command_executed = shlex.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: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl command failed with exit code {e.returncode}" + } + +@mcp.tool +def get_perl_config(variable: Optional[str] = None) -> Dict[str, Any]: + """ + Prints the configuration summary or a single Config.pm variable. + + Args: + variable: A specific Config.pm variable to print. If None, prints the summary. + + Returns: + A dictionary containing the command executed and the configuration information. + """ + cmd = ["perl"] + if variable: + cmd.append(f"-V:{variable}") + else: + cmd.append("-V") + + command_executed = shlex.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: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl command failed with exit code {e.returncode}" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/app/blast_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/app/blast_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18fa049e60b90ae5050e65194fcc43362b0baae7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/app/blast_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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_blast/app/blast_server.py') +SERVER_NAME = 'biosci_blast' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..584a513c193f074997f9910a0f401e62c2399081 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-blast: + build: . + image: mcp-blast:latest + container_name: mcp-blast + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=blast + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..52bd9ef7155d746e85f7965e26c24e5f4a19eca9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - blast + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_blast/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e92733ea1e0f47e2a97581359f7a5c599ccda71a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bowtie via conda (e.g., from bioconda) +RUN conda install -c bioconda bowtie -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bowtie_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bowtie_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bowtie_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/bowtie_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/bowtie_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6f37b0f719388ff8c8c473751cc46c645805b2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/bowtie_server.py @@ -0,0 +1,206 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + check_syntax_only: bool = False, + loop_around_program: bool = False, + loop_and_print: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + use_modules_no_import: Optional[List[str]] = None, + no_modules_no_import: Optional[List[str]] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + enable_tainting_checks: bool = False, + enable_tainting_warnings: bool = False, + search_path_for_program: bool = False, + record_separator: Optional[str] = None, + enable_line_ending_processing: Optional[str] = None, + enable_switch_parsing: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + extract_program: bool = False, + extract_directory: Optional[Path] = None, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + unicode_features: Optional[str] = None, + disable_sitecustomize: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, +) -> dict: + """ + Executes the Perl interpreter with a wide range of options. + + This tool can run a Perl script from a file, execute one-liners, check syntax, + and modify Perl's behavior with various switches for warnings, modules, + input processing, and more. + """ + # --- Input Validation --- + actionable_input = any([ + programfile, + execute_program, + execute_program_extended, + print_version, + print_config is not None, + check_syntax_only + ]) + if not actionable_input: + raise ValueError( + "Either a programfile, an executable string (-e/-E), or an action " + "like --print_version, --print_config, or --check_syntax_only must be provided." + ) + + if programfile and (execute_program or execute_program_extended): + raise ValueError("Cannot specify both a 'programfile' and an inline program via '-e' or '-E'.") + + if programfile and not programfile.exists(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if loop_around_program and loop_and_print: + raise ValueError("The flags '-n' (loop_around_program) and '-p' (loop_and_print) are mutually exclusive.") + + if enable_all_warnings and disable_all_warnings: + raise ValueError("The flags '-W' (enable_all_warnings) and '-X' (disable_all_warnings) are mutually exclusive.") + + if split_pattern and not autosplit: + raise ValueError("A 'split_pattern' (-F) can only be used with 'autosplit' mode (-a).") + + if extract_directory and not extract_program: + raise ValueError("Specifying 'extract_directory' requires 'extract_program' (-x) to be enabled.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger is not None: + cmd.append(f"-d{run_under_debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_extended: + for prog_line in execute_program_extended: + cmd.extend(["-E", prog_line]) + if disable_sitecustomize: + cmd.append("-f") + if split_pattern: + cmd.extend(["-F", split_pattern]) + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if include_directories: + for directory in include_directories: + cmd.extend(["-I", str(directory)]) + if enable_line_ending_processing is not None: + cmd.append(f"-l{enable_line_ending_processing}") + if use_modules: + for module in use_modules: + cmd.append(f"-M{module}") + if no_modules: + for module in no_modules: + cmd.append(f"-M-{module}") + if use_modules_no_import: + for module in use_modules_no_import: + cmd.append(f"-m{module}") + if no_modules_no_import: + for module in no_modules_no_import: + cmd.append(f"-m-{module}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if enable_switch_parsing: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V{print_config}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if extract_program: + cmd.append("-x") + if extract_directory: + cmd.extend([str(extract_directory)]) + if disable_all_warnings: + cmd.append("-X") + + # Add program file and arguments + if programfile: + cmd.append(str(programfile)) + + if arguments: + # The '--' switch is good practice to separate perl options from script arguments + if programfile or execute_program or execute_program_extended: + cmd.append("--") + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Perl execution doesn't have a defined output file + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/bowtie_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/bowtie_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d54cb40e6eafcf34f6402a2a45dbea5fdf58ca97 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/bowtie_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/bowtie_server.py') +SERVER_NAME = 'biosci_bowtie' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b590c5d861b6fcc1f695edf5c47bf23f69e96dbc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bowtie: + build: . + image: mcp-bowtie:latest + container_name: mcp-bowtie + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bowtie + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a94f45ccfd6430e8677fdd9d183a45bb30cda4a9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bowtie + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..484df324fc962e67f03afc5f4a0efc621fb6b948 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bowtie2 via conda (e.g., from bioconda) +RUN conda install -c bioconda bowtie2 -y && conda clean -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/bowtie2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bowtie2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bowtie2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/app/bowtie2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/app/bowtie2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4d5d6dcff7bd10985dcfd158490b540fc04e122b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/app/bowtie2_server.py @@ -0,0 +1,227 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def run_perl_script( + script_file: Optional[Path] = None, + program_strings: Optional[List[str]] = None, + program_strings_extended: Optional[List[str]] = None, + script_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_use_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_programfile_in_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_on_parse_error: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner with specified switches and arguments. + + This function provides comprehensive control over the Perl interpreter, + allowing users to run Perl programs from a file or directly from a string, + and configure various aspects of its execution environment. + + Args: + script_file: Path to the Perl program file to execute. Mutually exclusive with `program_strings` and `program_strings_extended`. + program_strings: A list of Perl program lines to execute directly from the command line using the -e switch. + Multiple -e switches are allowed. Mutually exclusive with `script_file`. + program_strings_extended: A list of Perl program lines to execute directly from the command line using the -E switch. + Like -e, but enables all optional features. Multiple -E switches are allowed. + Mutually exclusive with `script_file`. + script_arguments: Arguments to be passed to the Perl script itself. These are appended after the script source. + record_separator_octal: Specifies the input record separator (-0 switch). Can be an octal number (e.g., "0777") or empty string for '\0'. + autosplit_mode: Enables autosplit mode with -n or -p (splits $_ into @F) (-a switch). Requires `loop_around_program` or `loop_and_print`. + unicode_features: Enables listed Unicode features (-C switch). Argument is a number or list (e.g., "all", "0x10"). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks) (-c switch). + debugger: Run program under debugger (-d switch). If an empty string, uses default debugger; otherwise, specifies debugger (e.g., "MyDebugger"). + debugging_flags: Set debugging flags (argument is a bit mask or alphabets) (-D switch, e.g., "t", "1024"). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup (-f switch). + split_pattern: split() pattern for -a switch (//'s are optional) (-F switch, e.g., "/\s+/"). Requires `autosplit_mode`. + edit_in_place_extension: Edit <> files in place (-i switch). If an empty string, no backup is made; otherwise, specifies backup extension (e.g., ".bak"). + include_directories: Specify @INC/#include directory (several -I's allowed) (-I switch). Paths must exist. + line_ending_processing: Enable line ending processing, specifies line terminator (-l switch). Can be an octal number (e.g., "012") or empty string for newline. + use_modules: List of modules to execute "use module..." before executing program (-m or -M switch, e.g., "strict", "warnings"). + no_use_modules: List of modules to execute "no module..." before executing program (-m- or -M- switch, e.g., "strict"). + loop_around_program: Assume "while (<>) { ... }" loop around program (-n switch). + loop_and_print: Assume loop like -n but print line also, like sed (-p switch). + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile (-s switch). + search_programfile_in_path: Look for programfile using PATH environment variable (-S switch). + tainting_warnings: Enable tainting warnings (-t switch). + tainting_checks: Enable tainting checks (-T switch). + dump_core_on_parse_error: Dump core after parsing program (-u switch). + allow_unsafe_operations: Allow unsafe operations (-U switch). + print_version: Print version, patchlevel and license (-v switch). + print_config_summary_variable: Print configuration summary (-V switch). If an empty string, prints full summary; otherwise, prints a single Config.pm variable (e.g., "osname"). + enable_warnings: Enable many useful warnings (-w switch). + enable_all_warnings: Enable all warnings (-W switch). + ignore_text_before_shebang_dir: Ignore text before #!perl line (-x switch). If an empty path, ignores text without changing directory; otherwise, changes to the specified directory. + disable_all_warnings: Disable all warnings (-X switch). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + command: List[Union[str, Path]] = ["perl"] + output_files: List[Path] = [] + + # --- Input Validation --- + script_source_provided = script_file is not None or program_strings is not None or program_strings_extended is not None + + if script_file and (program_strings or program_strings_extended): + raise ValueError("Cannot specify both a script file and program strings (-e/-E). Choose one.") + if not script_source_provided and not (print_version or print_config_summary_variable is not None or check_syntax_only): + # If no script source is provided, it must be a utility command like -v, -V, -c + raise ValueError("Either a script file, program strings (-e/-E), or a utility switch (-v, -V, -c) must be provided.") + + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"Script file not found: {script_file}") + + if ignore_text_before_shebang_dir is not None and ignore_text_before_shebang_dir != Path("") and not ignore_text_before_shebang_dir.is_dir(): + raise NotADirectoryError(f"Directory for -x switch not found: {ignore_text_before_shebang_dir}") + + if autosplit_mode and not (loop_around_program or loop_and_print): + raise ValueError("Autosplit mode (-a) requires either loop_around_program (-n) or loop_and_print (-p).") + + if split_pattern is not None and not autosplit_mode: + raise ValueError("Split pattern (-F) requires autosplit mode (-a).") + + # --- Build Command --- + + if record_separator_octal is not None: + command.append(f"-0{record_separator_octal}") + if autosplit_mode: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags is not None: + command.append(f"-D{debugging_flags}") + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + raise NotADirectoryError(f"Include directory not found: {inc_dir}") + command.append(f"-I{inc_dir}") + if line_ending_processing is not None: + command.append(f"-l{line_ending_processing}") + if use_modules: + for module in use_modules: + command.append(f"-M{module}") # Using -M for 'use module' as it's common. + if no_use_modules: + for module in no_use_modules: + command.append(f"-M-{module}") # Using -M- for 'no module'. + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if search_programfile_in_path: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core_on_parse_error: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary_variable is not None: + command.append(f"-V:{print_config_summary_variable}" if print_config_summary_variable else "-V") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_shebang_dir is not None: + command.append(f"-x{ignore_text_before_shebang_dir}") + if disable_all_warnings: + command.append("-X") + + # Add program strings (-e/-E) + if program_strings: + for prog_str in program_strings: + command.extend(["-e", prog_str]) + if program_strings_extended: + for prog_str in program_strings_extended: + command.extend(["-E", prog_str]) + + # Add script file and its arguments + if script_file: + command.append(str(script_file)) + + if script_arguments: + # The `--` is typically used to separate Perl switches from script arguments + # if there's ambiguity. If the user needs `--`, they can include it as + # the first element of script_arguments. + command.extend(script_arguments) + + # Convert Path objects to strings for subprocess.run + final_command = [str(arg) for arg in command] + command_str = " ".join(final_command) + + # --- Execute Command --- + try: + process = subprocess.run( + final_command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "error": "Perl executable not found.", + "returncode": 127, + "output_files": output_files, + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/app/bowtie2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/app/bowtie2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..75a3a1ce190e795514985ba0e2bfd9a912d30403 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/app/bowtie2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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_bowtie2/app/bowtie2_server.py') +SERVER_NAME = 'biosci_bowtie2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..add4d2c95250fdada71909666fb03ab9baf80c82 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bowtie2: + build: . + image: mcp-bowtie2:latest + container_name: mcp-bowtie2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bowtie2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..56712b35c54c869a0d14e760ba6372aa027278b9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bowtie2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bowtie2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..08c5a4ad2668f0ac67e8120ccc090b88ef191270 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install brooklyn_plot via conda (e.g., from bioconda) +RUN conda install -c bioconda brooklyn_plot -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY brooklyn_plot_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/brooklyn_plot_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/brooklyn_plot_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/app/brooklyn_plot_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/app/brooklyn_plot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d0cebb2b93217dd0e74d9bdd441c256def655dac --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/app/brooklyn_plot_server.py @@ -0,0 +1,162 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Optional, Literal, Dict, Any + +# Set up a logger for internal use +logger = logging.getLogger(__name__) + +# @mcp.tool() decorator is assumed to be imported from the MCP framework. +# No need to define it here. + +@mcp.tool() +def run_brooklyn_plot( + input_file: Path, + output_file: str, + input_type: Literal["vcf", "txt"], + title: str = "Brooklyn Plot", + width: int = 12, + height: int = 8, + dpi: int = 300, + output_format: Literal["png", "pdf", "svg", "jpg"] = "png", + style: str = "seaborn-whitegrid", + palette: str = "colorblind", + font_scale: float = 1.2, + hide_legend: bool = False, + show_genes: bool = False, + gene_fontsize: int = 8, + min_vaf: float = 0.0, + max_vaf: float = 1.0, + min_depth: int = 0, + genes_to_label: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Generates a Brooklyn plot from variant data. + + A Brooklyn plot is a type of visualization used in genomics to display variant allele frequencies (VAFs) + of mutations across different samples or time points, often used in cancer genomics to track clonal evolution. + This tool takes a VCF or a tab-delimited file as input and produces a customizable plot. + + Args: + input_file: Path to the input file containing variant data (VCF or tab-delimited text). + output_file: Name for the output plot file. The extension should match the chosen format. + input_type: Type of the input file. + title: Title of the plot. + width: Width of the plot in inches. + height: Height of the plot in inches. + dpi: Resolution of the plot in dots per inch. + output_format: Format of the output plot. + style: Style of the plot. Any valid matplotlib style is accepted. + palette: Color palette for the plot. Any valid seaborn palette is accepted. + font_scale: Font scale for the plot. + hide_legend: If True, hides the legend from the plot. + show_genes: If True, shows gene names on the plot. + gene_fontsize: Font size for gene names. + min_vaf: Minimum variant allele frequency (VAF) to include in the plot. + max_vaf: Maximum variant allele frequency (VAF) to include in the plot. + min_depth: Minimum read depth to include in the plot. + genes_to_label: A list of specific gene names to label on the plot. + + Returns: + A dictionary containing the command executed, 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 width <= 0 or height <= 0 or dpi <= 0: + raise ValueError("Plot dimensions (width, height, dpi) must be positive.") + if font_scale <= 0 or gene_fontsize <= 0: + raise ValueError("Font scaling parameters (font_scale, gene_fontsize) must be positive.") + if min_depth < 0: + raise ValueError("min_depth cannot be negative.") + + if not (0.0 <= min_vaf <= 1.0): + raise ValueError(f"min_vaf must be between 0.0 and 1.0, but got {min_vaf}") + if not (0.0 <= max_vaf <= 1.0): + raise ValueError(f"max_vaf must be between 0.0 and 1.0, but got {max_vaf}") + if min_vaf > max_vaf: + raise ValueError(f"min_vaf ({min_vaf}) cannot be greater than max_vaf ({max_vaf})") + + # --- Command Construction --- + cmd = [ + "brooklyn_plot", + "-i", str(input_file), + "-o", output_file, + "-t", input_type, + ] + + # Add optional arguments if they differ from the default + if title != "Brooklyn Plot": + cmd.extend(["--title", title]) + if width != 12: + cmd.extend(["--width", str(width)]) + if height != 8: + cmd.extend(["--height", str(height)]) + if dpi != 300: + cmd.extend(["--dpi", str(dpi)]) + if output_format != "png": + cmd.extend(["--format", output_format]) + if style != "seaborn-whitegrid": + cmd.extend(["--style", style]) + if palette != "colorblind": + cmd.extend(["--palette", palette]) + if font_scale != 1.2: + cmd.extend(["--font_scale", str(font_scale)]) + if gene_fontsize != 8: + cmd.extend(["--gene_fontsize", str(gene_fontsize)]) + if min_vaf != 0.0: + cmd.extend(["--min_vaf", str(min_vaf)]) + if max_vaf != 1.0: + cmd.extend(["--max_vaf", str(max_vaf)]) + if min_depth != 0: + cmd.extend(["--min_depth", str(min_depth)]) + + # Add boolean flags if True + if hide_legend: + cmd.append("--hide_legend") + if show_genes: + cmd.append("--show_genes") + + # Add list-based argument + if genes_to_label: + cmd.append("--genes_to_label") + cmd.extend(genes_to_label) + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + output_path = Path(output_file) + output_files = [str(output_path)] if output_path.exists() else [] + if not output_files: + logger.warning(f"Output file '{output_file}' was not created by the tool.") + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except FileNotFoundError: + error_message = "Error: 'brooklyn_plot' command not found. Please ensure the tool is installed and in the system's PATH." + logger.error(error_message) + # Re-raising as a more specific error for the MCP framework + raise RuntimeError(error_message) from None + except subprocess.CalledProcessError as e: + logger.error(f"brooklyn_plot failed with exit code {e.returncode}") + # Return structured error information as per MCP guidelines + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/app/brooklyn_plot_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/app/brooklyn_plot_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cc2b0cc5e877d52598362db77695e8a538afb28a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/app/brooklyn_plot_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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_brooklyn_plot/app/brooklyn_plot_server.py') +SERVER_NAME = 'biosci_brooklyn_plot' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..821fcc1f62c40c20276c1b35c3a537c8912da6ac --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-brooklyn_plot: + build: . + image: mcp-brooklyn_plot:latest + container_name: mcp-brooklyn_plot + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=brooklyn_plot + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a8bbdd2f0101423b4cb128095f50fddc252d0ee4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - brooklyn_plot + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_brooklyn_plot/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1c540403613c57c4f7059830d34ca4cd57ef217e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bwa via conda (e.g., from bioconda) +RUN conda install -c bioconda bwa -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bwa_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bwa_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bwa_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/bwa_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/bwa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e17632ce5ce5d6426dd66b5f43cee9a8e7ed533c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/bwa_server.py @@ -0,0 +1,774 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# In a real MCP environment, you would import mcp. +# This is a placeholder to allow the code to be syntactically valid. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def bwa_index( + in_fa: Path, + prefix: Optional[Path] = None, + algorithm: str = "is", + color_space: bool = False, + block_size_bwtsw: int = 10000000, + index_for_64bit_genome: bool = False, +): + """ + Constructs the BWA index for a reference genome. + + This command builds the FM-index for a reference genome in FASTA format. + The index is composed of several files, all of which are required for alignment. + + Args: + in_fa: Path to the input reference genome file in FASTA format. + prefix: Prefix for the output index files. If not provided, it defaults to the input FASTA filename. + algorithm: Algorithm for index construction. Can be 'is' (default) or 'bwtsw'. + color_space: Build a color-space index. + block_size_bwtsw: Block size for the 'bwtsw' algorithm. + index_for_64bit_genome: Index files for 64-bit genome. + + Returns: + A dictionary containing the execution details and paths to the output index files. + """ + if not in_fa.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {in_fa}") + if algorithm not in ["is", "bwtsw"]: + raise ValueError(f"Invalid algorithm '{algorithm}'. Must be 'is' or 'bwtsw'.") + + output_prefix = prefix if prefix else in_fa.with_suffix('') + + cmd = ["bwa", "index"] + if algorithm != "is": + cmd.extend(["-a", algorithm]) + if color_space: + cmd.append("-c") + if block_size_bwtsw != 10000000 and algorithm == "bwtsw": + cmd.extend(["-b", str(block_size_bwtsw)]) + if index_for_64bit_genome: + cmd.append("-6") + + cmd.extend(["-p", str(output_prefix)]) + cmd.append(str(in_fa)) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_str = [ + f"{output_prefix}.amb", + f"{output_prefix}.ann", + f"{output_prefix}.bwt", + f"{output_prefix}.pac", + f"{output_prefix}.sa", + ] + if index_for_64bit_genome: + output_files_str[2] = f"{output_prefix}.bwt.64" + + for f in output_files_str: + if not Path(f).is_file(): + raise FileNotFoundError(f"Expected output file was not created: {f}") + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_str, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA index command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_mem( + idx_prefix: Path, + in1_fq: Path, + in2_fq: Optional[Path] = None, + output_file: Optional[Path] = None, + threads: int = 1, + min_seed_len: int = 19, + band_width: int = 100, + off_diagonal_x_dropoff: int = 100, + reseeding_factor: float = 1.5, + max_mem_occurrences: int = 500, + drop_chain_threshold: float = 0.50, + mark_shorter_splits_sec: bool = False, + perform_sw_rescue: bool = False, + match_score: int = 1, + mismatch_penalty: int = 4, + gap_open_penalty: str = "6,6", + gap_extension_penalty: str = "1,1", + clipping_penalty: str = "5,5", + unpaired_read_penalty: int = 17, + interleaved_input: bool = False, + read_group_header: Optional[str] = None, + min_score_to_output: int = 30, + header: Optional[str] = None, + treat_alt_as_primary: bool = False, + verbosity_level: int = 3, + soft_clip_supplementary: bool = False, + mark_shorter_splits_picard: bool = False, + read_length_params: Optional[str] = None, + read_type: Optional[str] = None, + output_all_alignments: bool = False, + append_fastq_comment: bool = False, + output_ref_header_in_xr: bool = False, + skip_mate_rescue: bool = False, + batch_size: int = 10000000, +): + """ + Aligns 70bp-1Mbp query sequences with the BWA-MEM algorithm. + + Args: + idx_prefix: Path to the BWA index prefix. + in1_fq: Path to the FASTQ file of reads (or first reads for PE). + in2_fq: Path to the FASTQ file of second reads for paired-end data. + output_file: Path to the output SAM file. If None, output is sent to stdout. + threads: Number of threads. + min_seed_len: Minimum seed length. + band_width: Band width for chaining. + off_diagonal_x_dropoff: Off-diagonal X-dropoff. + reseeding_factor: Trigger re-seeding for a MEM longer than min_seed_len * r. + max_mem_occurrences: Discard a MEM if it has more than this many occurrences. + drop_chain_threshold: Drop chains shorter than this fraction of the longest extension. + mark_shorter_splits_sec: Mark shorter split hits as secondary. + perform_sw_rescue: Perform Smith-Waterman to rescue missing hits. + match_score: Score for a sequence match. + mismatch_penalty: Penalty for a mismatch. + gap_open_penalty: Gap open penalty as a string "INT" or "INT,INT". + gap_extension_penalty: Gap extension penalty as a string "INT" or "INT,INT". + clipping_penalty: Penalty for a clipped read as a string "INT" or "INT,INT". + unpaired_read_penalty: Penalty for an unpaired read pair. + interleaved_input: Input file is an interleaved paired-end FASTQ. + read_group_header: Read group header line (e.g., '@RG\\tID:foo\\tSM:bar'). + min_score_to_output: Don't output alignment with score lower than this. + header: Insert this string to header, or read from file if it's a path. + treat_alt_as_primary: Treat ALT contigs as part of the primary assembly. + verbosity_level: Verbosity level. + soft_clip_supplementary: Use soft-clipping for supplementary alignments. + mark_shorter_splits_picard: Mark shorter split hits as secondary (for Picard compatibility). + read_length_params: Comma-separated string of "avg,std,max_is,min_is". + read_type: Read type. Can be 'pacbio', 'ont2d', or 'intractg'. + output_all_alignments: Output all found alignments for single-end or unpaired paired-end reads. + append_fastq_comment: Append FASTA/Q comment to SAM output. + output_ref_header_in_xr: Output the reference FASTA header in the XR tag. + skip_mate_rescue: Skip mate rescue. + batch_size: Process INT reads in a batch. + + Returns: + A dictionary containing the execution details and path to the output SAM file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in1_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ file not found: {in1_fq}") + if in2_fq and not in2_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ file 2 not found: {in2_fq}") + if read_type and read_type not in ['pacbio', 'ont2d', 'intractg']: + raise ValueError(f"Invalid read_type '{read_type}'.") + + cmd = ["bwa", "mem"] + + # Add options + if threads != 1: cmd.extend(["-t", str(threads)]) + if min_seed_len != 19: cmd.extend(["-k", str(min_seed_len)]) + if band_width != 100: cmd.extend(["-w", str(band_width)]) + if off_diagonal_x_dropoff != 100: cmd.extend(["-d", str(off_diagonal_x_dropoff)]) + if reseeding_factor != 1.5: cmd.extend(["-r", str(reseeding_factor)]) + if max_mem_occurrences != 500: cmd.extend(["-c", str(max_mem_occurrences)]) + if drop_chain_threshold != 0.50: cmd.extend(["-D", str(drop_chain_threshold)]) + if mark_shorter_splits_sec: cmd.append("-m") + if perform_sw_rescue: cmd.append("-P") + if match_score != 1: cmd.extend(["-A", str(match_score)]) + if mismatch_penalty != 4: cmd.extend(["-B", str(mismatch_penalty)]) + if gap_open_penalty != "6,6": cmd.extend(["-O", gap_open_penalty]) + if gap_extension_penalty != "1,1": cmd.extend(["-E", gap_extension_penalty]) + if clipping_penalty != "5,5": cmd.extend(["-L", clipping_penalty]) + if unpaired_read_penalty != 17: cmd.extend(["-U", str(unpaired_read_penalty)]) + if interleaved_input: cmd.append("-p") + if read_group_header: cmd.extend(["-R", read_group_header]) + if min_score_to_output != 30: cmd.extend(["-T", str(min_score_to_output)]) + if header: cmd.extend(["-H", header]) + if treat_alt_as_primary: cmd.append("-j") + if verbosity_level != 3: cmd.extend(["-v", str(verbosity_level)]) + if soft_clip_supplementary: cmd.append("-Y") + if mark_shorter_splits_picard: cmd.append("-M") + if read_length_params: cmd.extend(["-I", read_length_params]) + if read_type: cmd.extend(["-x", read_type]) + if output_all_alignments: cmd.append("-a") + if append_fastq_comment: cmd.append("-C") + if output_ref_header_in_xr: cmd.append("-V") + if skip_mate_rescue: cmd.append("-S") + if batch_size != 10000000: cmd.extend(["-K", str(batch_size)]) + if output_file: cmd.extend(["-o", str(output_file)]) + + # Add positional arguments + cmd.append(str(idx_prefix)) + cmd.append(str(in1_fq)) + if in2_fq: + cmd.append(str(in2_fq)) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_file)] if output_file else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA mem command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_aln( + idx_prefix: Path, + in_fq: Path, + output_sai: Optional[Path] = None, + max_diff: float = 0.04, + max_gap_opens: int = 1, + max_gap_extensions: int = -1, + disallow_long_del_at_3_end: int = 16, + disallow_indel_at_ends: int = 5, + seed_length: int = 32, + max_diff_in_seed: int = 2, + threads: int = 1, + mismatch_penalty: int = 3, + gap_open_penalty: int = 11, + gap_extension_penalty: int = 4, + stop_search_threshold: int = 30, + trimming_quality: int = 0, + barcode_length: int = 0, + reverse_query_no_complement: bool = False, + disable_iterative_search: bool = False, + illumina_1_3_plus_fastq: bool = False, + input_is_bam: bool = False, +): + """ + Finds the SA coordinates of the input reads using the BWA-backtrack algorithm. + + Args: + idx_prefix: Path to the BWA index prefix. + in_fq: Path to the input FASTQ file. + output_sai: Path to the output SAI file. If None, output is sent to stdout. + max_diff: Max #diff (int) or missing prob under 0.02 err rate (float). + max_gap_opens: Maximum number of gap opens. + max_gap_extensions: Maximum number of gap extensions. -1 to disable. + disallow_long_del_at_3_end: Disallow a long deletion within INT bp towards the 3'-end. + disallow_indel_at_ends: Disallow an indel within INT bp towards the ends. + seed_length: Take the first INT subsequence as seed. If INT is larger than the query sequence, seeding will be disabled. + max_diff_in_seed: Maximum edit distance in the seed. + threads: Number of threads. + mismatch_penalty: Mismatch penalty. + gap_open_penalty: Gap open penalty. + gap_extension_penalty: Gap extension penalty. + stop_search_threshold: Stop searching when there are > INT equally best hits. + trimming_quality: Quality threshold for read trimming down to 35bp. + barcode_length: Length of barcode starting from the 5'-end. + reverse_query_no_complement: Reverse query but not complement it. + disable_iterative_search: Disable iterative search. + illumina_1_3_plus_fastq: Input is in Illumina 1.3+ FASTQ format. + input_is_bam: Input is BAM. + + Returns: + A dictionary containing the execution details and path to the output SAI file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ/BAM file not found: {in_fq}") + + cmd = ["bwa", "aln"] + + if max_diff != 0.04: cmd.extend(["-n", str(max_diff)]) + if max_gap_opens != 1: cmd.extend(["-o", str(max_gap_opens)]) + if max_gap_extensions != -1: cmd.extend(["-e", str(max_gap_extensions)]) + if disallow_long_del_at_3_end != 16: cmd.extend(["-d", str(disallow_long_del_at_3_end)]) + if disallow_indel_at_ends != 5: cmd.extend(["-i", str(disallow_indel_at_ends)]) + if seed_length != 32: cmd.extend(["-l", str(seed_length)]) + if max_diff_in_seed != 2: cmd.extend(["-k", str(max_diff_in_seed)]) + if threads != 1: cmd.extend(["-t", str(threads)]) + if mismatch_penalty != 3: cmd.extend(["-M", str(mismatch_penalty)]) + if gap_open_penalty != 11: cmd.extend(["-O", str(gap_open_penalty)]) + if gap_extension_penalty != 4: cmd.extend(["-E", str(gap_extension_penalty)]) + if stop_search_threshold != 30: cmd.extend(["-R", str(stop_search_threshold)]) + if trimming_quality != 0: cmd.extend(["-q", str(trimming_quality)]) + if barcode_length != 0: cmd.extend(["-B", str(barcode_length)]) + if reverse_query_no_complement: cmd.append("-c") + if disable_iterative_search: cmd.append("-N") + if illumina_1_3_plus_fastq: cmd.append("-I") + if input_is_bam: cmd.append("-b") + if output_sai: cmd.extend(["-f", str(output_sai)]) + + cmd.extend([str(idx_prefix), str(in_fq)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_sai)] if output_sai else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA aln command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_samse( + idx_prefix: Path, + in_sai: Path, + in_fq: Path, + output_sam: Optional[Path] = None, + read_group_header: Optional[str] = None, + max_alignments_in_xa: int = 3, +): + """ + Generates alignments in the SAM format given single-end reads. + + Args: + idx_prefix: Path to the BWA index prefix. + in_sai: Path to the input SAI file from `bwa aln`. + in_fq: Path to the input FASTQ file. + output_sam: Path to the output SAM file. If None, output is sent to stdout. + read_group_header: Read group header line. + max_alignments_in_xa: Maximum number of alignments to output in the XA tag. + + Returns: + A dictionary containing the execution details and path to the output SAM file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in_sai.is_file(): + raise FileNotFoundError(f"Input SAI file not found: {in_sai}") + if not in_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ file not found: {in_fq}") + + cmd = ["bwa", "samse"] + + if output_sam: cmd.extend(["-f", str(output_sam)]) + if read_group_header: cmd.extend(["-r", read_group_header]) + if max_alignments_in_xa != 3: cmd.extend(["-n", str(max_alignments_in_xa)]) + + cmd.extend([str(idx_prefix), str(in_sai), str(in_fq)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_sam)] if output_sam else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA samse command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_sampe( + idx_prefix: Path, + in1_sai: Path, + in2_sai: Path, + in1_fq: Path, + in2_fq: Path, + output_sam: Optional[Path] = None, + read_group_header: Optional[str] = None, + max_insert_size: int = 500, + max_occurrences: int = 100000, + max_abnormal_xa: int = 3, + max_discordant_xa: int = 10, + load_entire_fm_index: bool = False, +): + """ + Generates alignments in the SAM format given paired-end reads. + + Args: + idx_prefix: Path to the BWA index prefix. + in1_sai: Path to the SAI file for the first reads. + in2_sai: Path to the SAI file for the second reads. + in1_fq: Path to the FASTQ file for the first reads. + in2_fq: Path to the FASTQ file for the second reads. + output_sam: Path to the output SAM file. If None, output is sent to stdout. + read_group_header: Read group header line. + max_insert_size: Maximum insert size for a read pair to be considered being mapped properly. + max_occurrences: Maximum occurrences for one end before mate-SW is used. + max_abnormal_xa: Maximum number of alignments to output in the XA tag for reads paired abnormally. + max_discordant_xa: Maximum number of alignments to output in the XA tag for disconcordant read pairs. + load_entire_fm_index: Load the entire FM-index into memory to reduce disk operations. + + Returns: + A dictionary containing the execution details and path to the output SAM file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in1_sai.is_file(): raise FileNotFoundError(f"Input SAI file not found: {in1_sai}") + if not in2_sai.is_file(): raise FileNotFoundError(f"Input SAI file not found: {in2_sai}") + if not in1_fq.is_file(): raise FileNotFoundError(f"Input FASTQ file not found: {in1_fq}") + if not in2_fq.is_file(): raise FileNotFoundError(f"Input FASTQ file not found: {in2_fq}") + + cmd = ["bwa", "sampe"] + + if output_sam: cmd.extend(["-f", str(output_sam)]) + if read_group_header: cmd.extend(["-r", read_group_header]) + if max_insert_size != 500: cmd.extend(["-a", str(max_insert_size)]) + if max_occurrences != 100000: cmd.extend(["-o", str(max_occurrences)]) + if max_abnormal_xa != 3: cmd.extend(["-n", str(max_abnormal_xa)]) + if max_discordant_xa != 10: cmd.extend(["-N", str(max_discordant_xa)]) + if load_entire_fm_index: cmd.append("-P") + + cmd.extend([str(idx_prefix), str(in1_sai), str(in2_sai), str(in1_fq), str(in2_fq)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_sam)] if output_sam else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA sampe command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_fastmap( + idx_prefix: Path, + in_fq: Path, + output_file: Optional[Path] = None, + min_smem_length: int = 17, + max_interval_size: int = 20, + threads: int = 1, +): + """ + Identify super-maximal exact matches (SMEMs). + + Args: + idx_prefix: Path to the BWA index prefix. + in_fq: Path to the input FASTQ file. + output_file: Path to the output file. If None, output is sent to stdout. + min_smem_length: Minimum length for a SMEM. + max_interval_size: Maximum interval size to find SMEMs. + threads: Number of threads. + + Returns: + A dictionary containing the execution details and path to the output file. + """ + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + if not in_fq.is_file(): + raise FileNotFoundError(f"Input FASTQ file not found: {in_fq}") + + cmd = ["bwa", "fastmap"] + + if min_smem_length != 17: cmd.extend(["-l", str(min_smem_length)]) + if max_interval_size != 20: cmd.extend(["-w", str(max_interval_size)]) + if threads != 1: cmd.extend(["-t", str(threads)]) + if output_file: cmd.extend(["-o", str(output_file)]) + + cmd.extend([str(idx_prefix), str(in_fq)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + + output_files_list = [str(output_file)] if output_file else [] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA fastmap command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_shm( + command: str, + idx_prefix: Path, +): + """ + Manage BWA index in shared memory. + + Args: + command: The command to execute: 'load', 'get', or 'rm'. + idx_prefix: Path to the BWA index prefix. + + Returns: + A dictionary containing the execution details. + """ + if command not in ["load", "get", "rm"]: + raise ValueError("Command must be one of 'load', 'get', or 'rm'.") + if not idx_prefix.with_suffix(".bwt").is_file(): + raise FileNotFoundError(f"BWA index file not found: {idx_prefix}.bwt") + + cmd = ["bwa", "shm", command, str(idx_prefix)] + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA shm command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_fa2pac( + in_fa: Path, + out_pac: Path, + force_overwrite: bool = False, +): + """ + Convert FASTA to PAC format (binary sequence). + + Args: + in_fa: Path to the input FASTA file. + out_pac: Path for the output PAC file. + force_overwrite: Force overwrite of the output file if it exists. + + Returns: + A dictionary containing the execution details and path to the output PAC file. + """ + if not in_fa.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {in_fa}") + + cmd = ["bwa", "fa2pac"] + if force_overwrite: + cmd.append("-f") + cmd.extend([str(in_fa), str(out_pac)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + if not out_pac.is_file(): + raise FileNotFoundError(f"Expected output file was not created: {out_pac}") + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_pac)], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA fa2pac command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_pac2bwt( + in_pac: Path, + out_bwt: Path, + use_manber_myers: bool = False, + use_z_algorithm: bool = False, + force_overwrite: bool = False, +): + """ + Generate BWT from PAC format. + + Args: + in_pac: Path to the input PAC file. + out_bwt: Path for the output BWT file. + use_manber_myers: Use the Manber-Myers algorithm for D-critical characters. + use_z_algorithm: Use the Z-algorithm for D-critical characters. + force_overwrite: Force overwrite of the output file if it exists. + + Returns: + A dictionary containing the execution details and path to the output BWT file. + """ + if not in_pac.is_file(): + raise FileNotFoundError(f"Input PAC file not found: {in_pac}") + + cmd = ["bwa", "pac2bwt"] + if use_manber_myers: + cmd.append("-d") + if use_z_algorithm: + cmd.append("-z") + if force_overwrite: + cmd.append("-f") + cmd.extend([str(in_pac), str(out_bwt)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + if not out_bwt.is_file(): + raise FileNotFoundError(f"Expected output file was not created: {out_bwt}") + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_bwt)], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA pac2bwt command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_bwtupdate( + in_bwt: Path, + out_bwt: Path, +): + """ + Update BWT for the new reference sequence. + + Args: + in_bwt: Path to the input BWT file. + out_bwt: Path for the output BWT file. + + Returns: + A dictionary containing the execution details and path to the output BWT file. + """ + if not in_bwt.is_file(): + raise FileNotFoundError(f"Input BWT file not found: {in_bwt}") + + cmd = ["bwa", "bwtupdate", str(in_bwt), str(out_bwt)] + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + if not out_bwt.is_file(): + raise FileNotFoundError(f"Expected output file was not created: {out_bwt}") + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_bwt)], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA bwtupdate command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def bwa_bwt2sa( + in_bwt: Path, + out_sa: Path, + force_overwrite: bool = False, + sa_interval: int = 16, +): + """ + Generate SA from BWT and Occ. + + Args: + in_bwt: Path to the input BWT file. + out_sa: Path for the output SA file. + force_overwrite: Force overwrite of the output file if it exists. + sa_interval: SA interval. + + Returns: + A dictionary containing the execution details and path to the output SA file. + """ + if not in_bwt.is_file(): + raise FileNotFoundError(f"Input BWT file not found: {in_bwt}") + + cmd = ["bwa", "bwt2sa"] + if force_overwrite: + cmd.append("-f") + if sa_interval != 16: + cmd.extend(["-i", str(sa_interval)]) + cmd.extend([str(in_bwt), str(out_sa)]) + + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + if not out_sa.is_file(): + raise FileNotFoundError(f"Expected output file was not created: {out_sa}") + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_sa)], + } + except FileNotFoundError: + raise RuntimeError("bwa command not found. Please ensure BWA is installed and in your PATH.") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"BWA bwt2sa command failed with exit code {e.returncode}.\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/bwa_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/bwa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e274c624dbed66baf68bafa11bee644f98c002f6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/bwa_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/bwa_server.py') +SERVER_NAME = 'biosci_bwa' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6c34807f2062027c5a22e819759fe77c42ff13b8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bwa: + build: . + image: mcp-bwa:latest + container_name: mcp-bwa + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bwa + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f74db625e040cbe9746d3807eb4a3e3672bf5953 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bwa + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bwa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff7a9d5afb15ee9ed48b941671202aa2435b509b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install cd-hit via conda (e.g., from bioconda) +RUN conda install -c bioconda cd-hit -y && conda clean -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/cd-hit_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/cd-hit_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/cd-hit_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/app/cd-hit_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/app/cd-hit_server.py new file mode 100644 index 0000000000000000000000000000000000000000..260bd2529ca74af5d01a3ab19c087b3126371bb6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/app/cd-hit_server.py @@ -0,0 +1,184 @@ +import subprocess +import logging +from pathlib import Path +from typing import List + +# @mcp.tool() is a decorator provided by the Model Context Protocol (MCP) framework. +# It is used here to define a bioinformatics tool that can be executed by the MCP server. +# For the purpose of this code generation, we assume 'mcp' is an available module. +# No need to import it in the final code. + +@mcp.tool() +def cd_hit( + input_file: Path, + output_file: Path, + identity_threshold: float = 0.9, + global_identity: bool = True, + band_width: int = 20, + memory_limit: int = 800, + threads: int = 1, + word_length: int = 5, + throw_away_length: int = 10, + redundancy_tolerance: int = 2, + description_length: int = 20, + length_diff_cutoff_percent: float = 0.0, + length_diff_cutoff_aa: int = 999999, + align_coverage_longer_percent: float = 0.0, + align_coverage_longer_abs: int = 99999999, + align_coverage_shorter_percent: float = 0.0, + align_coverage_shorter_abs: int = 99999999, + min_align_coverage_both: int = 0, + max_unmatched_percent_longer: float = 1.0, + max_unmatched_percent_shorter: float = 1.0, + max_unmatched_length: int = 99999999, + print_alignment_overlap: bool = False, + best_cluster: bool = False, + sort_clusters_by_size: bool = False, + sort_fasta_by_cluster_size: bool = False, + write_backup_file: bool = False, +): + """ + Clusters a FASTA file of sequences using CD-HIT. + + CD-HIT is a fast program for clustering and comparing large sets of protein or nucleotide sequences. + It clusters sequences based on a specified identity threshold. + + Args: + input_file: Input filename in FASTA format, can be in .gz format. + output_file: Output filename for the representative sequences. + identity_threshold: Sequence identity threshold (0.0 to 1.0). Default is 0.9. + global_identity: If True (default), use global sequence identity. If False, use local sequence identity. + band_width: Band width of alignment. Default is 20. + memory_limit: Memory limit in MB for the program. 0 for unlimited. Default is 800. + threads: Number of threads. 0 for all CPUs. Default is 1. + word_length: Word length for the algorithm. Default is 5. + throw_away_length: Length of sequences to throw away. Default is 10. + redundancy_tolerance: Tolerance for redundancy. Default is 2. + description_length: Length of description in .clstr file. 0 takes the full defline. Default is 20. + length_diff_cutoff_percent: Shorter sequences must be at least this fraction of the representative's length. Default is 0.0. + length_diff_cutoff_aa: The length difference between shorter sequences and the representative cannot be bigger than this value. Default is 999999. + align_coverage_longer_percent: Alignment must cover this fraction of the longer sequence. Default is 0.0. + align_coverage_longer_abs: Alignment length must be >= (longer sequence length - this value). Default is 99999999. + align_coverage_shorter_percent: Alignment must cover this fraction of the shorter sequence. Default is 0.0. + align_coverage_shorter_abs: Alignment length must be >= (shorter sequence length - this value). Default is 99999999. + min_align_coverage_both: Minimal alignment coverage for both sequences. Default is 0. + max_unmatched_percent_longer: Max unmatched percentage for the longer sequence (0.0 to 1.0). Default is 1.0. + max_unmatched_percent_shorter: Max unmatched percentage for the shorter sequence (0.0 to 1.0). Default is 1.0. + max_unmatched_length: Maximum unmatched length in bases. Default is 99999999. + print_alignment_overlap: If True, print alignment overlap in .clstr file. Default is False. + best_cluster: If True, cluster to the most similar cluster (slow but accurate). Default is False (fast cluster). + sort_clusters_by_size: If True, sort clusters by decreasing size. Default is False (sort by length). + sort_fasta_by_cluster_size: If True, sort output FASTA/FASTQ by decreasing cluster size. Default is False. + write_backup_file: If True, write a backup cluster file (.clstr.bak). Default is False. + + Returns: + A dictionary containing the command executed, 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 not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Parameter value validation + if not (0.0 <= identity_threshold <= 1.0): + raise ValueError("identity_threshold (-c) must be between 0.0 and 1.0") + if threads < 0: + raise ValueError("threads (-T) cannot be negative.") + if memory_limit < 0: + raise ValueError("memory_limit (-M) cannot be negative.") + if not (0.0 <= length_diff_cutoff_percent <= 1.0): + raise ValueError("length_diff_cutoff_percent (-s) must be between 0.0 and 1.0") + if not (0.0 <= align_coverage_longer_percent <= 1.0): + raise ValueError("align_coverage_longer_percent (-aL) must be between 0.0 and 1.0") + if not (0.0 <= align_coverage_shorter_percent <= 1.0): + raise ValueError("align_coverage_shorter_percent (-aS) must be between 0.0 and 1.0") + if not (0.0 <= max_unmatched_percent_longer <= 1.0): + raise ValueError("max_unmatched_percent_longer (-uL) must be between 0.0 and 1.0") + if not (0.0 <= max_unmatched_percent_shorter <= 1.0): + raise ValueError("max_unmatched_percent_shorter (-uS) must be between 0.0 and 1.0") + + # Special validation for local identity mode + if not global_identity: + coverage_controls_set = ( + align_coverage_longer_percent != 0.0 or + align_coverage_longer_abs != 99999999 or + align_coverage_shorter_percent != 0.0 or + align_coverage_shorter_abs != 99999999 + ) + if not coverage_controls_set: + logging.warning( + "Using local sequence identity (-G 0) without setting alignment coverage controls " + "(-aL, -AL, -aS, -AS) is not recommended by the tool's documentation." + ) + + # --- Command Construction --- + cmd = [ + "cd-hit", + "-i", str(input_file), + "-o", str(output_file), + "-c", str(identity_threshold), + "-G", "1" if global_identity else "0", + "-b", str(band_width), + "-M", str(memory_limit), + "-T", str(threads), + "-n", str(word_length), + "-l", str(throw_away_length), + "-t", str(redundancy_tolerance), + "-d", str(description_length), + "-s", str(length_diff_cutoff_percent), + "-S", str(length_diff_cutoff_aa), + "-aL", str(align_coverage_longer_percent), + "-AL", str(align_coverage_longer_abs), + "-aS", str(align_coverage_shorter_percent), + "-AS", str(align_coverage_shorter_abs), + "-A", str(min_align_coverage_both), + "-uL", str(max_unmatched_percent_longer), + "-uS", str(max_unmatched_percent_shorter), + "-U", str(max_unmatched_length), + "-p", "1" if print_alignment_overlap else "0", + "-g", "1" if best_cluster else "0", + "-sc", "1" if sort_clusters_by_size else "0", + "-sf", "1" if sort_fasta_by_cluster_size else "0", + "-bak", "1" if write_backup_file else "0", + ] + + # --- Subprocess Execution --- + command_str = " ".join(cmd) + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'cd-hit' command not found. Please ensure it 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": [] + } + + # --- Structured Result Return --- + output_files: List[str] = [str(output_file), f"{output_file}.clstr"] + if write_backup_file: + backup_path = Path(f"{output_file}.clstr.bak") + if backup_path.exists(): + output_files.append(str(backup_path)) + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/app/cd-hit_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/app/cd-hit_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cd86e6556c6e9ccc45a095a3f5dc6181698f41 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/app/cd-hit_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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_cd-hit/app/cd-hit_server.py') +SERVER_NAME = 'biosci_cd_hit' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5c51c300967d68d853e465b1ab25c478c681991d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-cd-hit: + build: . + image: mcp-cd-hit:latest + container_name: mcp-cd-hit + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=cd-hit + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d20832c25dd850af35a5d8a5a567a3b839a8c10 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - cd-hit + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cd-hit/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..364a2345123f3e08531b1152331714134be57161 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install cellrank via conda (e.g., from bioconda) +RUN conda install -c bioconda cellrank -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY cellrank_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/cellrank_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/cellrank_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/app/cellrank_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/app/cellrank_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3ece79996b7b2e27f7b91ba22eb6e00b7395eaf0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/app/cellrank_server.py @@ -0,0 +1,169 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Optional + +# MCP decorator is omitted as per instructions, but would be present in a real MCP environment +# @mcp.tool() +def cellrank_run_analysis( + input_h5ad: Path, + output_h5ad: Path, + cluster_key: str, + velocity_key: str = "velocity", + connectivity_key: Optional[str] = None, + n_macrostates: int = 10, + schur_components: int = 20, + compute_fate_maps: bool = True, + n_jobs: int = 1, + backend: str = "loky", +) -> Dict: + """ + Runs a standard CellRank analysis pipeline on an AnnData object. + + This tool serves as a command-line wrapper for the CellRank Python library, + which does not have a native CLI. It initializes a kernel (VelocityKernel, + ConnectivityKernel, or a combined kernel), computes a transition matrix, + and then uses an estimator (GPCCA) to find macrostates and compute fate maps. + + Args: + input_h5ad: Path to the input AnnData file (`.h5ad`). + output_h5ad: Path to save the annotated output AnnData file. + cluster_key: Key in `adata.obs` where cluster annotations are stored. + velocity_key: Key in `adata.layers` for RNA velocity data. Used for VelocityKernel. + connectivity_key: Key in `adata.obsp` for connectivities. Used for ConnectivityKernel. + If both velocity and connectivity keys are provided, a combined kernel is used. + n_macrostates: Number of macrostates (terminal states) to compute. + schur_components: Number of Schur components to compute for the estimator. + compute_fate_maps: If True, computes fate maps (absorption probabilities). + n_jobs: Number of parallel jobs to use. + backend: The parallelization backend to use (e.g., 'loky', 'multiprocessing'). + + Returns: + A dictionary containing the execution command, stdout, stderr, and output file paths. + """ + # --- Input Validation --- + if not input_h5ad.is_file(): + raise FileNotFoundError(f"Input file not found: {input_h5ad}") + if not output_h5ad.parent.exists(): + output_h5ad.parent.mkdir(parents=True, exist_ok=True) + if n_macrostates <= 0: + raise ValueError("n_macrostates must be a positive integer.") + if schur_components <= 0: + raise ValueError("schur_components must be a positive integer.") + if n_jobs <= 0: + raise ValueError("n_jobs must be a positive integer.") + if backend not in ["loky", "multiprocessing", "threading"]: + raise ValueError(f"Invalid backend: {backend}. Must be one of 'loky', 'multiprocessing', 'threading'.") + if not velocity_key and not connectivity_key: + raise ValueError("At least one of `velocity_key` or `connectivity_key` must be provided.") + + # --- Script Generation --- + # This script will be executed in a separate Python process + script_content = f""" +import sys +import anndata as ad +import cellrank as cr +import scvelo as scv + +try: + # Set verbosity and logging + scv.settings.verbosity = 3 + cr.settings.verbosity = "info" + + # Load data + print(f"Loading data from {input_h5ad}") + adata = ad.read_h5ad("{input_h5ad}") + + # Initialize Kernel + vk = None + ck = None + if "{velocity_key}": + print("Initializing VelocityKernel...") + vk = cr.tl.kernels.VelocityKernel(adata, vkey="{velocity_key}") + vk.compute_transition_matrix() + + if "{connectivity_key}": + print("Initializing ConnectivityKernel...") + ck = cr.tl.kernels.ConnectivityKernel(adata, conn_key="{connectivity_key}") + ck.compute_transition_matrix() + + if vk and ck: + print("Combining kernels...") + kernel = 0.8 * vk + 0.2 * ck + elif vk: + kernel = vk + else: + kernel = ck + + # Initialize and run Estimator + print("Initializing GPCCA estimator...") + g = cr.tl.estimators.GPCCA(kernel) + + print(f"Computing Schur decomposition with {schur_components} components...") + g.compute_schur(n_components={schur_components}) + + print(f"Computing {n_macrostates} macrostates using cluster key '{cluster_key}'...") + g.compute_macrostates(n_states={n_macrostates}, cluster_key="{cluster_key}") + + if {compute_fate_maps}: + print("Computing fate maps (absorption probabilities)...") + g.compute_fate_maps(n_jobs={n_jobs}, backend="{backend}") + + # Save results to AnnData object + print("Writing results to AnnData object...") + g.write_to_anndata() + + # Save annotated data + print(f"Saving annotated data to {output_h5ad}") + adata.write_h5ad("{output_h5ad}") + + print("CellRank analysis completed successfully.") + +except Exception as e: + print(f"An error occurred during CellRank execution: {{e}}", file=sys.stderr) + sys.exit(1) +""" + + # --- Subprocess Execution --- + command_executed = "" + stdout_str = "" + stderr_str = "" + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as tmp_script: + tmp_script_path = Path(tmp_script.name) + tmp_script.write(script_content) + + command = ["python", str(tmp_script_path)] + command_executed = " ".join(command) + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except subprocess.CalledProcessError as e: + # Re-raise with more context + raise RuntimeError( + f"CellRank 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 + except Exception as e: + raise e + finally: + # Clean up the temporary script file + if 'tmp_script_path' in locals() and tmp_script_path.exists(): + tmp_script_path.unlink() + + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": {"annotated_adata": str(output_h5ad)}, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/app/cellrank_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/app/cellrank_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5530d7de7c096ed93299d53515caa5731e7e385b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/app/cellrank_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +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_cellrank/app/cellrank_server.py') +SERVER_NAME = 'biosci_cellrank' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..13d6193cd1d0d337ae01b47b6377d88464ef3d23 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-cellrank: + build: . + image: mcp-cellrank:latest + container_name: mcp-cellrank + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=cellrank + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ccc87d9cb856e78cccbfa2126826b18e82f31f2d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - cellrank + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cellrank/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7aef2682e4708f4951775888341113d6336c96e9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install celltypist via conda (e.g., from bioconda) +RUN conda install -c bioconda celltypist -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY celltypist_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/celltypist_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/celltypist_server.py"] + \ No newline at end of file